cycle.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. # coding: utf-8
  2. import multiprocessing
  3. from synergine2.base import BaseObject
  4. from synergine2.config import Config
  5. from synergine2.log import SynergineLogger
  6. from synergine2.processing import ProcessManager
  7. from synergine2.simulation import SimulationMechanism
  8. from synergine2.simulation import SimulationBehaviour
  9. from synergine2.simulation import Simulation
  10. from synergine2.simulation import SubjectBehaviour
  11. from synergine2.simulation import SubjectMechanism
  12. from synergine2.simulation import Event
  13. from synergine2.utils import ChunkManager
  14. class CycleManager(BaseObject):
  15. def __init__(
  16. self,
  17. config: Config,
  18. logger: SynergineLogger,
  19. simulation: Simulation,
  20. process_manager: ProcessManager=None,
  21. ):
  22. if process_manager is None:
  23. process_manager = ProcessManager(
  24. process_count=config.get('use_x_cores', multiprocessing.cpu_count()),
  25. chunk_manager=ChunkManager(multiprocessing.cpu_count()),
  26. )
  27. self.config = config
  28. self.logger = logger
  29. self.simulation = simulation
  30. self.process_manager = process_manager
  31. self.current_cycle = -1
  32. self.first_cycle = True
  33. def next(self) -> [Event]:
  34. if self.first_cycle:
  35. # To dispatch subjects add/removes, enable track on them
  36. self.simulation.subjects.track_changes = True
  37. self.first_cycle = False
  38. self.current_cycle += 1
  39. self.logger.info('Process cycle {}'.format(self.current_cycle))
  40. events = []
  41. # TODO: gestion des behaviours non parallelisables
  42. # TODO: Proposer des ordres d'execution
  43. events.extend(self._get_subjects_events())
  44. events.extend(self._get_simulation_events())
  45. self.logger.info('Cycle {} generate {} events'.format(
  46. str(self.current_cycle),
  47. str(len(events)),
  48. ))
  49. return events
  50. def _get_simulation_events(self) -> [Event]:
  51. events = []
  52. results = {}
  53. self.logger.info('Process simulation events')
  54. results_by_processes = self.process_manager.execute_jobs(
  55. data=self.simulation,
  56. job_maker=self.simulation_computing,
  57. )
  58. for process_result in results_by_processes:
  59. for behaviour_class, behaviour_result in process_result.items():
  60. results[behaviour_class] = behaviour_class.merge_data(
  61. behaviour_result,
  62. results.get(behaviour_class),
  63. )
  64. self.logger.info('Simulation generate {} behaviours'.format(len(results)))
  65. # Make events
  66. for behaviour_class, behaviour_data in results.items():
  67. behaviour_events = self.simulation.behaviours[behaviour_class].action(behaviour_data)
  68. self.logger.info('{} behaviour generate {} events'.format(
  69. str(behaviour_class),
  70. str(len(behaviour_events)),
  71. ))
  72. if self.logger.is_debug:
  73. self.logger.debug('{} behaviour generated events: {}'.format(
  74. str(behaviour_class),
  75. str([e.repr_debug() for e in behaviour_events]),
  76. ))
  77. events.extend(behaviour_events)
  78. self.logger.info('Simulation behaviours generate {} events'.format(len(events)))
  79. return events
  80. def _get_subjects_events(self) -> [Event]:
  81. events = []
  82. results = {}
  83. self.logger.info('Process subjects events')
  84. results_by_processes = self.process_manager.chunk_and_execute_jobs(
  85. data=self.simulation.subjects,
  86. job_maker=self.subjects_computing,
  87. )
  88. for process_results in results_by_processes:
  89. results.update(process_results)
  90. # Duplicate list to prevent conflicts with behaviours subjects manipulations
  91. for subject in self.simulation.subjects[:]:
  92. subject_behaviours = results.get(subject.id, {})
  93. if subject.behaviour_selector:
  94. # TODO: Looging
  95. subject_behaviours = subject.behaviour_selector.reduce_behaviours(dict(subject_behaviours))
  96. for behaviour_class, behaviour_data in subject_behaviours.items():
  97. # TODO: Ajouter une etape de selection des actions a faire (genre neuronnal)
  98. # (genre se cacher et fuir son pas compatibles)
  99. behaviour_events = subject.behaviours[behaviour_class].action(behaviour_data)
  100. self.logger.info('{} behaviour for subject {} generate {} events'.format(
  101. str(behaviour_class),
  102. str(subject.id),
  103. str(len(behaviour_events)),
  104. ))
  105. if self.logger.is_debug:
  106. self.logger.debug('{} behaviour for subject {} generated events: {}'.format(
  107. str(behaviour_class),
  108. str(subject.id),
  109. str([e.repr_debug() for e in behaviour_events]),
  110. ))
  111. events.extend(behaviour_events)
  112. self.logger.info('Subjects behaviours generate {} events'.format(len(events)))
  113. return events
  114. def simulation_computing(
  115. self,
  116. simulation,
  117. process_number,
  118. process_count,
  119. ):
  120. self.logger.info('Simulation computing')
  121. # TODO: necessaire de passer simulation ?
  122. mechanisms = self.get_mechanisms_to_compute(simulation)
  123. mechanisms_data = {}
  124. behaviours_data = {}
  125. self.logger.info('{} mechanisms to compute'.format(str(len(mechanisms))))
  126. if self.logger.is_debug:
  127. self.logger.debug('Mechanisms are: {}'.format(
  128. str([m.repr_debug() for m in mechanisms])
  129. ))
  130. for mechanism in mechanisms:
  131. mechanism_data = mechanism.run(
  132. process_number=process_number,
  133. process_count=process_count,
  134. )
  135. if self.logger.is_debug:
  136. self.logger.debug('{} mechanism product data: {}'.format(
  137. type(mechanism).__name__,
  138. str(mechanism_data),
  139. ))
  140. mechanisms_data[type(mechanism)] = mechanism_data
  141. behaviours = self.get_behaviours_to_compute(simulation)
  142. self.logger.info('{} behaviours to compute'.format(str(len(behaviours))))
  143. if self.logger.is_debug:
  144. self.logger.debug('Behaviours are: {}'.format(
  145. str([b.repr_debug() for b in behaviours])
  146. ))
  147. for behaviour in behaviours:
  148. behaviour_data = behaviour.run(mechanisms_data) # TODO: Behaviours dependencies
  149. if self.logger.is_debug:
  150. self.logger.debug('{} behaviour produce data: {}'.format(
  151. type(behaviour).__name__,
  152. behaviour_data,
  153. ))
  154. if behaviour_data:
  155. behaviours_data[type(behaviour)] = behaviour_data
  156. return behaviours_data
  157. def subjects_computing(
  158. self,
  159. subjects,
  160. process_number=None,
  161. process_count=None,
  162. ):
  163. results = {}
  164. self.logger.info('Subjects computing: {} subjects to compute'.format(str(len(subjects))))
  165. for subject in subjects:
  166. mechanisms = self.get_mechanisms_to_compute(subject)
  167. if mechanisms:
  168. self.logger.info('Subject {}: {} mechanisms'.format(
  169. str(subject.id),
  170. str(len(mechanisms)),
  171. ))
  172. if self.logger.is_debug:
  173. self.logger.info('Subject {}: mechanisms are: {}'.format(
  174. str(subject.id),
  175. str([m.repr_debug for m in mechanisms])
  176. ))
  177. mechanisms_data = {}
  178. behaviours_data = {}
  179. for mechanism in mechanisms:
  180. mechanism_data = mechanism.run()
  181. if self.logger.is_debug:
  182. self.logger.info('Subject {}: {} mechanisms produce data: {}'.format(
  183. str(subject.id),
  184. type(mechanism).__name__,
  185. str(mechanism_data),
  186. ))
  187. mechanisms_data[type(mechanism)] = mechanism_data
  188. if mechanisms:
  189. if self.logger.is_debug:
  190. self.logger.info('Subject {}: mechanisms data are: {}'.format(
  191. str(subject.id),
  192. str(mechanisms_data),
  193. ))
  194. subject_behaviours = self.get_behaviours_to_compute(subject)
  195. if not subject_behaviours:
  196. break
  197. self.logger.info('Subject {}: have {} behaviours'.format(
  198. str(subject.id),
  199. str(len(subject_behaviours)),
  200. ))
  201. for behaviour in subject_behaviours:
  202. self.logger.info('Subject {}: run {} behaviour'.format(
  203. str(subject.id),
  204. str(type(behaviour)),
  205. ))
  206. # We identify behaviour data with it's class to be able to intersect it after subprocess data collect
  207. behaviour_data = behaviour.run(mechanisms_data) # TODO: Behaviours dependencies
  208. if self.logger.is_debug:
  209. self.logger.debug('Subject {}: behaviour {} produce data: {}'.format(
  210. str(type(behaviour)),
  211. str(subject.id),
  212. str(behaviour_data),
  213. ))
  214. if behaviour_data:
  215. behaviours_data[type(behaviour)] = behaviour_data
  216. results[subject.id] = behaviours_data
  217. return results
  218. def get_mechanisms_to_compute(self, mechanisable) -> [SubjectMechanism, SimulationMechanism]:
  219. # TODO: Implementer un systeme qui inhibe des mechanisme (ex. someil inhibe l'ouie)
  220. return mechanisable.mechanisms.values()
  221. def get_behaviours_to_compute(self, mechanisable) -> [SubjectBehaviour, SimulationBehaviour]:
  222. # TODO: Implementer un systeme qui inhibe des behaviours (ex. someil inhibe avoir faim)
  223. behaviours = list(mechanisable.behaviours.values())
  224. for behaviour in behaviours[:]:
  225. if behaviour.frequency != 1:
  226. if self.current_cycle % behaviour.frequency:
  227. behaviours.remove(behaviour)
  228. return behaviours
  229. def apply_actions(
  230. self,
  231. simulation_actions: [tuple]=None,
  232. subject_actions: [tuple]=None,
  233. ) -> [Event]:
  234. """
  235. TODO: bien specifier la forme des parametres
  236. simulation_actions = [(class, {'data': 'foo'})]
  237. subject_actions = [(subject_id, [(class, {'data': 'foo'}])]
  238. """
  239. simulation_actions = simulation_actions or []
  240. subject_actions = subject_actions or []
  241. events = []
  242. self.logger.info('Apply {} simulation_actions and {} subject_actions'.format(
  243. len(simulation_actions),
  244. len(subject_actions),
  245. ))
  246. for subject_id, behaviours_and_data in subject_actions:
  247. subject = self.simulation.subjects.index.get(subject_id)
  248. for behaviour_class, behaviour_data in behaviours_and_data:
  249. behaviour = behaviour_class(
  250. simulation=self.simulation,
  251. subject=subject,
  252. )
  253. self.logger.info('Apply {} behaviour on subject {}'.format(
  254. str(behaviour_class),
  255. str(subject_id),
  256. ))
  257. if self.logger.is_debug:
  258. self.logger.debug('{} behaviour data is {}'.format(
  259. str(behaviour_class),
  260. str(behaviour_data),
  261. ))
  262. behaviour_events = behaviour.action(behaviour_data)
  263. self.logger.info('{} events from behaviour {} from subject {}'.format(
  264. len(behaviour_events),
  265. str(behaviour_class),
  266. str(subject_id),
  267. ))
  268. if self.logger.is_debug:
  269. self.logger.debug('Events from behaviour {} from subject {} are: {}'.format(
  270. str(behaviour_class),
  271. str(subject_id),
  272. str([e.repr_debug() for e in behaviour_events])
  273. ))
  274. events.extend(behaviour_events)
  275. for behaviour_class, behaviour_data in simulation_actions:
  276. behaviour = behaviour_class(
  277. config=self.config,
  278. simulation=self.simulation,
  279. )
  280. self.logger.info('Apply {} simulation behaviour'.format(
  281. str(behaviour_class),
  282. ))
  283. behaviour_events = behaviour.action(behaviour_data)
  284. if self.logger.is_debug:
  285. self.logger.debug('Events from behaviour {} are: {}'.format(
  286. str(behaviour_class),
  287. str([e.repr_debug() for e in behaviour_events])
  288. ))
  289. events.extend(behaviour_events)
  290. self.logger.info('{} events generated'.format(len(events)))
  291. return events