cycle.py 2.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import multiprocessing
  2. from synergine2.processing import ProcessManager
  3. from synergine2.simulation import Subject, Behaviour, Mechanism
  4. from synergine2.utils import ChunkManager
  5. class CycleManager(object):
  6. def __init__(
  7. self,
  8. subjects: list,
  9. process_manager: ProcessManager=None,
  10. ):
  11. if process_manager is None:
  12. process_manager = ProcessManager(
  13. process_count=multiprocessing.cpu_count(),
  14. chunk_manager=ChunkManager(multiprocessing.cpu_count()),
  15. job_maker=self.computing,
  16. )
  17. self.subjects = subjects
  18. self._process_manager = process_manager
  19. self._current_cycle = 0
  20. def next(self):
  21. results = {}
  22. results_by_processes = self._process_manager.execute_jobs(self.subjects)
  23. for process_results in results_by_processes:
  24. results.update(process_results)
  25. for subject in self.subjects[:]: # Duplicate list to prevent conflicts with behaviours subjects manipulations
  26. for behaviour_class in results[subject.id]:
  27. # TODO: Ajouter une etape de selection des actions a faire (genre neuronnal)
  28. # TODO: les behaviour_class ont le même uniqueid apres le process ?
  29. subject.behaviours[behaviour_class].action(results[subject.id][behaviour_class])
  30. def computing(self, subjects):
  31. # compute mechanisms (prepare check to not compute slienced or not used mechanisms)
  32. # compute behaviours with mechanisms data
  33. # return list with per subject: [behaviour: return, behaviour: return] if behaviour return True something
  34. results = {}
  35. for subject in subjects:
  36. mechanisms = self.get_mechanisms_to_compute(subject)
  37. mechanisms_data = {}
  38. behaviours_data = {}
  39. for mechanism in mechanisms:
  40. mechanisms_data[type(mechanism)] = mechanism.run()
  41. for behaviour in self.get_behaviours_to_compute(subject):
  42. # We identify behaviour data with it's class to be able to intersect it after subprocess data collect
  43. behaviour_data = behaviour.run(mechanisms_data)
  44. if behaviour_data:
  45. behaviours_data[type(behaviour)] = behaviour_data
  46. results[subject.id] = behaviours_data
  47. # TODO: Tester les performances si on utilise un index numerique pour les results[subject]
  48. # et behaviours_data[type(behaviours_data)]
  49. return results
  50. def get_mechanisms_to_compute(self, subject: Subject) -> [Mechanism]:
  51. # TODO: Implementer un systeme qui inhibe des mechanisme (ex. someil inhibe l'ouie)
  52. return subject.mechanisms.values()
  53. def get_behaviours_to_compute(self, subject: Subject) -> [Behaviour]:
  54. # TODO: Implementer un systeme qui inhibe des behaviours (ex. someil inhibe avoir faim)
  55. return subject.behaviours.values()