simulation.py 1.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import random
  2. from synergine2.config import Config
  3. from synergine2.share import shared
  4. from synergine2.simulation import SubjectMechanism, SubjectBehaviour, Event, Subject
  5. def compute(complexity: int):
  6. random_floats = []
  7. result = 0.0
  8. for i in range(complexity):
  9. random_floats.append(random.uniform(0, 100))
  10. for j, random_float in enumerate(random_floats):
  11. if not j % 2:
  12. result += random_float
  13. else:
  14. result -= random_float
  15. return result
  16. class ComputeMechanism(SubjectMechanism):
  17. def run(self):
  18. complexity = self.config.get('complexity')
  19. value = compute(complexity)
  20. return {
  21. 'mechanism_value': value,
  22. 'complexity': complexity,
  23. }
  24. class ComplexityEvent(Event):
  25. def __init__(self, complexity, *args, **kwargs):
  26. self.complexity = complexity
  27. class ComputeBehaviour(SubjectBehaviour):
  28. use = [ComputeMechanism]
  29. def run(self, data):
  30. return not data.get('ComputeMechanism').get('mechanism_value') % 2
  31. def action(self, data):
  32. mechanism_value = data.get('ComputeMechanism').get('mechanism_value')
  33. complexity = data.get('ComputeMechanism').get('complexity')
  34. if not int(str(mechanism_value)[-1]) % 2:
  35. compute(complexity)
  36. return [Event(complexity)]
  37. class ComputeSubject(Subject):
  38. behaviours_classes = [ComputeBehaviour]
  39. data = shared.create_self('data', lambda: [])
  40. def __init__(
  41. self,
  42. config: Config,
  43. simulation: 'Simulation',
  44. ):
  45. super().__init__(config, simulation)