cycle.py 13KB

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