pn_simulate.alc 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. include "primitives.alh"
  2. include "modelling.alh"
  3. include "random.alh"
  4. Element function simulate(inputs : Element):
  5. Element outputs
  6. outputs = create_node()
  7. // Copy over the model to the output dictionary
  8. dict_add(outputs, "models/PetriNets_Runtime", model_copy(inputs["models/PetriNets_Runtime"))
  9. // Do a single simulation step
  10. Element model
  11. model = outputs["models/PetriNets_Runtime"]
  12. // Find enabled transitions
  13. Element all_transitions
  14. Element enabled_transitions
  15. String under_study
  16. Boolean enabled
  17. Element in_arcs
  18. all_transitions = allInstances(model, "Transition")
  19. enabled_transitions = create_node()
  20. while (0 < read_nr_out(all_transitions)):
  21. under_study = set_pop(all_transitions)
  22. enabled = True
  23. // Find all incoming transitions
  24. in_arcs = allIncomingAssociationInstances(model, under_study, "P2T")
  25. while (0 < read_nr_out(in_arcs)):
  26. arc_under_study = set_pop(in_arcs)
  27. Integer present_tokens
  28. Integer required_tokens
  29. required_tokens = read_attribute(model, arc_under_study, "weight")
  30. log("Weight: " + cast_i2s(required_tokens))
  31. present_tokens = read_attribute(model, reverseKeyLookup(model["model"], read_edge_src(model["model"][arc_under_study])), "tokens")
  32. log("Tokens: " + cast_i2s(present_tokens))
  33. if (present_tokens < required_tokens):
  34. // Less tokens than required, so disable the transition completely
  35. enabled = False
  36. if (enabled):
  37. set_add(enabled_transitions, under_study)
  38. // Pick random enabled transition
  39. String transition
  40. transition = random_choice(enabled_transitions)
  41. // Consume tokens
  42. Element workset
  43. String working_arc
  44. String working_place
  45. Integer new_value
  46. workset = allIncomingAssociationInstances(model, transition, "P2T")
  47. while (0 < read_nr_out(workset)):
  48. working_arc = set_pop(workset)
  49. working_place = reverseKeyLookup(model["model"], read_edge_src(model["model"][working_arc]))
  50. new_value = integer_subtraction(read_attribute(model, working_place, "tokens"), read_attribute(model, working_arc, "weight"))
  51. instantiate_attribute(model, working_place, "tokens", new_value)
  52. // Add tokens
  53. workset = allOutgoingAssociationInstances(model, transition, "T2P")
  54. while (0 < read_nr_out(workset)):
  55. working_arc = set_pop(workset)
  56. working_place = reverseKeyLookup(model["model"], read_edge_dst(model["model"][working_arc]))
  57. new_value = integer_addition(read_attribute(model, working_place, "tokens"), read_attribute(model, working_arc, "weight"))
  58. instantiate_attribute(model, working_place, "tokens", new_value)
  59. // Finish up
  60. return outputs!