|
| 1 | +from osp.core.session import SimWrapperSession |
| 2 | +from osp.wrappers.simple_simulation import SimulationEngine |
| 3 | +from osp.core.namespaces import simple_ontology |
| 4 | + |
| 5 | + |
| 6 | +class SimpleSimulationSession(SimWrapperSession): |
| 7 | + """ |
| 8 | + Session class for some engine. |
| 9 | + """ |
| 10 | + |
| 11 | + def __init__(self, engine=None, **kwargs): |
| 12 | + super().__init__(engine or SimulationEngine(), **kwargs) |
| 13 | + self.mapper = dict() # maps uuid to index in the backend |
| 14 | + |
| 15 | + def __str__(self): |
| 16 | + return "Simple sample Wrapper Session" |
| 17 | + |
| 18 | + # OVERRIDE |
| 19 | + def _apply_added(self, root_obj, buffer): |
| 20 | + """Adds the added cuds to the engine.""" |
| 21 | + for obj in buffer.values(): |
| 22 | + if obj.is_a(simple_ontology.Atom): |
| 23 | + self.mapper[obj.uid] = len(self.mapper) |
| 24 | + pos = obj.get(oclass=simple_ontology.Position)[0].value |
| 25 | + vel = obj.get(oclass=simple_ontology.Velocity)[0].value |
| 26 | + self._engine.add_atom(pos, vel) |
| 27 | + |
| 28 | + # OVERRIDE |
| 29 | + def _apply_updated(self, root_obj, buffer): |
| 30 | + """Updates the updated cuds in the engine.""" |
| 31 | + for obj in buffer.values(): |
| 32 | + |
| 33 | + # case 1: we change the velocity |
| 34 | + if obj.is_a(simple_ontology.Velocity): |
| 35 | + atom = obj.get(rel=simple_ontology.isPartOf)[0] |
| 36 | + idx = self.mapper[atom.uid] |
| 37 | + self._engine.update_velocity(idx, obj.value) |
| 38 | + |
| 39 | + # case 2: we change the position |
| 40 | + elif obj.is_a(simple_ontology.Position): |
| 41 | + atom = obj.get(rel=simple_ontology.isPartOf)[0] |
| 42 | + idx = self.mapper[atom.uid] |
| 43 | + self._engine.update_position(idx, obj.value) |
| 44 | + |
| 45 | + # OVERRIDE |
| 46 | + def _apply_deleted(self, root_obj, buffer): |
| 47 | + """Deletes the deleted cuds from the engine.""" |
| 48 | + |
| 49 | + # OVERRIDE |
| 50 | + def _load_from_backend(self, uids, expired=None): |
| 51 | + """Loads the cuds object from the simulation engine""" |
| 52 | + for uid in uids: |
| 53 | + if uid in self._registry: |
| 54 | + obj = self._registry.get(uid) |
| 55 | + |
| 56 | + # check whether user wants to load a position |
| 57 | + if obj.is_a(simple_ontology.Position): |
| 58 | + atom = obj.get(rel=simple_ontology.isPartOf)[0] |
| 59 | + idx = self.mapper[atom.uid] |
| 60 | + pos = self._engine.get_position(idx) |
| 61 | + obj.value = pos |
| 62 | + |
| 63 | + # check whether user wants to load a velocity |
| 64 | + elif obj.is_a(simple_ontology.Velocity): |
| 65 | + atom = obj.get(rel=simple_ontology.isPartOf)[0] |
| 66 | + idx = self.mapper[atom.uid] |
| 67 | + vel = self._engine.get_velocity(idx) |
| 68 | + obj.value = vel |
| 69 | + |
| 70 | + yield obj |
| 71 | + |
| 72 | + # OVERRIDE |
| 73 | + def _run(self, root_cuds_object): |
| 74 | + """Call the run command of the engine.""" |
| 75 | + self._engine.run() |
0 commit comments