Agents connection not restricted to one type of agents in AnyLogic - connection

I have a rectangular node where 30 people and 5 facility randomly located. I wanted to create distance-based connection among people only. On the main tab, I did- Network type: Distance-based, Connection range:70. On the Person tab, Agent type: Person and turn on "Draw line". So, what I got (attached figure), it's not only create connection among people but also with facility within that distance range. But I want to create connection only among people. How can I do it?connection output

Well, you need to ensure that your Person agents are only connected to other persons.
Do not use the default Connections object to manage agent connections. Create custom "Agent link" objects, one Person.conn_MyOtherPersons and another Person.conn_MyBuildings.
Then only animate Person.conn_MyOtherPersons
Check the example models and tutorials for learning more about agent connections, they are very powerful to use.

Following code is working perfectly to solve the above described problem. I have created this function in main and call it on startup.
for (int i=0; i<people.size(); i++){
Person p=people.get(i);
for (int j=i+1; j<people.size(); j++){
Person q=people.get(j);
if (people.get(i).distanceTo(people.get(j))<100)
p.connectTo(q);
}
}
applyNetwork();

Related

Is it possible to fetch multiple features from feast feature-store in a single request?

In use-cases like search one might need to apply a model to multiple entries at runtime. Having a single query is much more resilient than one per product. Does feast support it?
In this scenario, the "feature service" component of the Feast can be utilized to pull data from one or more feature views. This makes it possible to fetch multiple features in a single call.
For example, let's say we have multiple feature views -
Feature view for demographics data
demographics_fv = FeatureView(
name="demographics_fv",
entities=[cust_id],
ttl=timedelta(days=365),
schema=[
Field(name="gender", dtype=String),
Field(name="age", dtype=Int32),
Field(name="location", dtype=String),
],
online=True,
source=cust_data,
tags={}
)
Feature view for medical data
medical_fv = FeatureView(
name="medical_fv",
entities=[cust_id],
ttl=timedelta(days=365),
schema=[
Field(name="weight", dtype=Int32),
Field(name="height", dtype=Int32),
Field(name="blood_group", dtype=String),
],
online=True,
source=cust_data,
tags={}
)
A feature service definition can be created that will consist references to multiple feature views -
cust_data_fs = FeatureService(
name="cust_data_fs",
features=[demographics_fv, medical_fv[["weight", "height"]]]
)
Now a call can be made to this feature service to retrieve required data that may be coming from one or more feature views -
feature_service = feature_store.get_feature_service("cust_data_fs")
feature_store.get_historical_features(features=feature_service, entity_df=entity_df)
You can find more details on this link: https://docs.feast.dev/getting-started/concepts/feature-retrieval#feature-services

How to define collision filter groups across model instances?

When constructing a MultiBodyPlant from multiple ModelInstances each loaded from a separate URDF, is there a way to define collision filter groups to exclude collisions across model instances? In the multibody URDF parser, loading collision filter groups is restricted to the those present in the same model instance.
What I would like to do is in URDF A specify:
<drake:collision_filter_group name="model_a_group">
<drake:member link="link1"/>
<drake:member link="link2"/>
<drake:ignored_collision_filter_group name="model_b_group"/>
</drake:collision_filter_group>
and in URDF B specify:
<drake:collision_filter_group name="model_b_group">
<drake:member link="link4"/>
<drake:member link="link5"/>
<drake:ignored_collision_filter_group name="model_a_group"/>
</drake:collision_filter_group>
But currently attempting to do this results in the following error:
abort: Failure at multibody/parsing/detail_urdf_parser.cc:238 in abort:
Failure at multibody/parsing/detail_urdf_parser.cc:238 in ParseCollisionFilterGroup():
condition 'collision_filter_group_b != collision_filter_groups.end()' failed.
The scope of drake:collision_filter_group is limited to the scope of the file. So, it's sufficient to prevent "fake" collision at a robot's joints but insufficient to prevent two robots that get parsed independently from colliding.
In order to achieve that end, you'll have to parse the two robots, and then algorithmically declare the collision filters.
I don't have a great deal of time right now, so I'll give a rough overview of what it looks like, and then provide code when I free up later:
The approach.
Parse both URDFs (SDFs).
Grab the bodies for model instance "a" (link1 and link2), and similarly the bodies for model instance "b" (link4 and link5).
Using the MBP interface get the geometry::FrameId associated with each of those bodies. (We'll call them frameA1, frameA2, frameB4, frameB5, respectively.
Create two instances of geometry::GeometrySet. geometry_set_A = {frameA1, frameA2} and geometry_set_B = {frameB4, frameB5}.
Invoke SceneGraph::ExcludeCollisionsBetween(geometry_set_A, geometry_set_b).
Done
This should give you the first glimmer of how to proceed. I'll come by for a second pass to give concrete code to accomplish the task later.

How to optimize performance of Results change listeners in Realm (Swift) with a deep hierarchy?

We're using Realm (Swift binding currently in version 3.12.0) from the earliest days in our project. In some early versions before 1.0 Realm provided change listeners for Results without actually giving changeSets.
We used this a lot in order to find out if a specific Results list changed.
Later the guys at Realm exchanged this API with changeSet providing methods. We had to switch and are now mistreating this API just in order to find out if anything in a specific List changed (inserts, deletions, modifications).
Together with RxSwift we wrote our own implementation of Results change listening which looks like this:
public var observable: Observable<Base> {
return Observable.create { observer in
let token = self.base.observe { changes in
if case .update = changes {
observer.onNext(self.base)
}
}
observer.onNext(self.base)
return Disposables.create(with: {
observer.onCompleted()
token.invalidate()
})
}
}
When we now want to have consecutive updates on a list we subscribe like so:
someRealm.objects(SomeObject.self).filter(<some filter>).rx.observable
.subscribe(<subscription code that gets called on every update>)
//dispose code missing
We wrote the extension on RealmCollection so that we can subscribe to List type as well.
The concept is equal to RxRealm's approach.
So now in our App we have a lot of filtered lists/results that we are subscribing to.
When data gets more and more we notice significant performance losses when it comes to seeing a change visually after writing something into the DB.
For example:
Let's say we have a Car Realm Object class with some properties and some 1-to-n and some 1-to-1 relationships. One of the properties is a Bool, namely isDriving.
Now we have a lot of cars stored in the DB and bunch of change listeners with different filters listing to changes of the cars collection (collection observers listening for changeSets in order to find out if the list was changed).
If I take one car of some list and set the property of isDriving from false to true (important: we do writes in the background) ideally the change listener fires fast and I have the nearly immediate correct response to my write on the main thread.
Added with edit on 2019-06-19:
Let's make the scenario still a little more real:
Let's change something down the hierarchy, let's say the tires manufacturer's name. Let's say a Car has a List<Tire>, a Tire has a Manufacturer and a Manufacturer has aname.
Now we're still listing toResultscollection changes with some more or less complex filters applied.
Then we're changing the name of aManufacturer` which is connected to one of the tires which are connected to one of the cars which is in that filtered list.
Can this still be fast?
Obviously when the length of results/lists where change listeners are attached to gets longer Realm's internal change listener takes longer to calculate the differences and fires later.
So after a write we see the changes - in worst case - much later.
In our case this is not acceptable. So we are thinking through different scenarios.
One scenario would be to not use .observe on lists/results anymore and switch to Realm.observe which fires every time anything did change in the realm, which is not ideal, but it is fast because the change calculation process is skipped.
My question is: What can I do to solve this whole dilemma and make our app fast again?
The crucial thing is the threading stuff. We're always writing in the background due to our design. So the writes itself should be very fast, but then that stuff needs to synchronize to the other threads where Realms are open.
In my understanding that happens after the change detection for all Results has run through, is that right?
So when I read on another thread, the data is only fresh after the thread sync, which happens after all notifications were sent out. But I am not sure currently if the sync happens before, that would be more awesome, did not test it by now.

GameplayKit - Confusion about sending messages between components

I'm diving into GameplayKit with Spritekit and from what I gather, you subclass GKEntity and then start adding GKComponents to that entity. The entity would more or less just be a bag of components that fill some function.
The part I'm confused about is communication between components. How do you keep them decoupled. For example, lets say I have a HealthComponent class, and I add that component to a PlayerEntity, and an EnemyEntity. I also have a HealthBarComponent but I only want a health bar to appear above the player. When the player takes damage, that information needs to be updated in the HealthBarComponent.
So how should that information be sent? I see there is a class called GKComponentSystem in the documentation. I'm not 100% on how that should be used.
Another question is.. when the player's health reaches zero he should regenerate while the enemy should stay dead. When the player runs out of lives, the game ends.
The health system for both an enemy and player would be roughly the same, but the events around death would be totally different for each. I'm not following how to use a component system while keeping the unique behavior of each entity.
some pseudo-code would be great
It looks like this framework works a bit differently than others I've seen, in that systems only work on a single type of component rather than on entities with groups of component types.
In the GamePlay-Kit framework you can either loop through and update your entities manually (which in turns updates each entities components) or create a class which inherits from GKComponentSystem. Then when you update the system it updates all the components you have added to it so long as their class type matches the type you initialized the system with
To handle your health bar issue I would say make a HealthBarComponent which, during its update, retrieves the HealthComponent from its owner entity, reads the health value & renders itself every frame. But you only add a HealthBarComponent to your player entity.
You can retrieve the owner entity from a component and vice versa (see GKComponent.entity & GKEntity.components) so you could update your health bar like this:
/*Note: I'm not an ios developer, this is pseudocode*/
HealthBarComponent.update(){
int healthValue = self.entity.components.get(HealthComponent).value;
//Now render your health bar accordingly or hold onto this for later
}
To handle the player death issue I would think your best bet would be to have two different types of Health components (PlayerHealth & EnemyHealth) with two different corresponding systems. That or have a single Health component but 2 separate 'Death' components. Yeah it seems redundant but I'm having a hard time thinking of a better way inside of this framework. In my experience you either spend your time worrying about keeping everything completely decoupled and reusable or you build a game :)
Components can access their entities via the self.entity property. From there, you can query other components to pass data to via the entity componentForClass property:
guard let moveComponent = entity?.componentForClass(MoveComponent.self) else {
fatalError("A MovementComponent's entity must have a MoveComponent")
}
The iOS Games by Tutorials book has an excellent tutorial that covers GameplayKit entities and components.
Notifications are nice for this kind of problem. There's no direct object coupling at all, and it's very extensible if more than one object ends up needing to know (e.g. your health bar component, a higher-level game object that determines game over, maybe even enemy/ally AI to behave differently when health is low).
You could have a notification named "playerHealthChanged" and have your health-bar component and other objects register independently to respond to that event. (You likely need to let the HealthComponent instance know whether it should post this notification, so only the player posts - perhaps it could use isKind(of:) on its entity, or just have a bool field to enable posting, set to true for the player instance).
I usually put all notification name definitions in a single module so any class can access them:
let kPlayerHealthChangedNotification = Notification.Name("playerHealthChanged")
Here's the way the component would post the notification (you could pass an object other than self if desired):
NotificationCenter.default.post(name: kPlayerHealthChangedNotification, object:self)
Then the objects that care about player health changes can register like so in their init code - create a handler function, than add self as an observer for the notification:
#objc func onPlayerHealthChanged(_ notification:Notification) {
// do whatever is needed; notification.object
// has the object from the post
}
// put this in a setup method - init or similar:
NotificationCenter.default.addObserver(self,
selector: #selector(onPlayerHealthChanged(_:)),
name: kPlayerHealthChangedNotification
object:nil)
Here's the documentation: https://developer.apple.com/documentation/foundation/notifications

Why is Entity framework loading data from the db when I set a property?

I have two tables (there are more in the database but only two are involved here).
Account and AccountStatus, an account can have an AccountStatus (active,inactive etc).
I create a new Account and set a couple of properties but when I reach this code:
1. var status = db.AccountStatuses.SingleOrDefault(s => s.ID == (long)AccountStatusEnum.Active);
2. account.AccountStatus = status;
3. db.Accounts.AddObject(account);
The first line executes fine, but when I reach the second line it takes a REALLY long time, and when I step in to the code it seems that every single account is loaded from the database.
I don't see why it should even want to load all the accounts?
We use Entity Framework 4 and Poco and we have lazy loading enabled.
Any suggestions?
Cheers
/Jimmy
You have to be careful which constructs you use to fetch data, as some will pull in the whole set and filter afterword. (aside: the long time delay may be the database being created and seeded, if there isn't one already, it will occur the first time you touch it, likely with a query of some sort. Also remember that when you retrieve a whole dataset, you may in actuality only have what amounts to a compiled query that won't be evaluated until you interact with it).
Try this form instead and see if you have the same issue:
var status = db.AccountStatuses.Where(s => s.ID == (long)AccountStatusEnum.Active);

Resources