Browse Source

initial commit

Simon Van Mierlo 8 years ago
commit
e94b5905ef
100 changed files with 27347 additions and 0 deletions
  1. 15 0
      .gitignore
  2. 58 0
      README.md
  3. 11 0
      bouncing.html
  4. 1743 0
      bouncing_balls.js
  5. 403 0
      bouncing_balls.js.xml
  6. 203 0
      debugging_environment/debugging_environment.html
  7. 1857 0
      debugging_environment/debugging_environment.js
  8. 1109 0
      debugging_environment/debugging_environment.xml
  9. 147 0
      debugging_environment/debugging_server.js
  10. 152 0
      debugging_environment/examples_sccd_sim/client.py
  11. 296 0
      debugging_environment/examples_sccd_sim/model.py
  12. 167 0
      debugging_environment/examples_sccd_sim/model_processor.py
  13. 498 0
      debugging_environment/examples_sccd_sim/particle_interaction/model.py
  14. 51 0
      debugging_environment/examples_sccd_sim/simple_dsdevs/model.py
  15. 104 0
      debugging_environment/examples_sccd_sim/trace.txt
  16. 75 0
      debugging_environment/examples_sccd_sim/trafficlight_classic/experiment.py
  17. 296 0
      debugging_environment/examples_sccd_sim/trafficlight_classic/model.py
  18. 277 0
      debugging_environment/examples_sccd_sim/trafficlight_parallel/model.py
  19. BIN
      debugging_environment/img/bigstep.png
  20. BIN
      debugging_environment/img/breakpoint.png
  21. BIN
      debugging_environment/img/delete-bp.png
  22. BIN
      debugging_environment/img/pause.png
  23. BIN
      debugging_environment/img/reset.png
  24. BIN
      debugging_environment/img/rubbish-bin.png
  25. BIN
      debugging_environment/img/simulate.png
  26. 87 0
      debugging_environment/img/simulate.svg
  27. BIN
      debugging_environment/img/simulatert.png
  28. 99 0
      debugging_environment/img/simulatert.svg
  29. BIN
      debugging_environment/img/smallstep.png
  30. 4 0
      debugging_environment/javascript_runtime/libs/d3.v2.min.js
  31. 4 0
      debugging_environment/javascript_runtime/libs/jquery.min.js
  32. 132 0
      debugging_environment/javascript_runtime/libs/old/svg.js
  33. 126 0
      debugging_environment/javascript_runtime/libs/old/ui.js
  34. 14 0
      debugging_environment/javascript_runtime/libs/old/utils.js
  35. 58 0
      debugging_environment/javascript_runtime/libs/ui.js
  36. 2 0
      debugging_environment/javascript_runtime/libs/w2ui-1.4.3.min.css
  37. 11 0
      debugging_environment/javascript_runtime/libs/w2ui-1.4.3.min.js
  38. 719 0
      debugging_environment/javascript_runtime/statecharts_core.js
  39. 111 0
      debugging_environment/javascript_runtime_old/libs/svg.js
  40. 135 0
      debugging_environment/javascript_runtime_old/libs/ui.js
  41. 14 0
      debugging_environment/javascript_runtime_old/libs/utils.js
  42. 1204 0
      debugging_environment/javascript_runtime_old/statecharts_core.js
  43. 9 0
      debugging_environment/package.json
  44. 329 0
      debugging_environment/particle_interaction.py
  45. 954 0
      debugging_environment/pypdevs/DEVS.py
  46. 0 0
      debugging_environment/pypdevs/__init__.py
  47. 68 0
      debugging_environment/pypdevs/classicDEVSWrapper.py
  48. 17 0
      debugging_environment/pypdevs/devsexception.py
  49. 1 0
      debugging_environment/pypdevs/infinity.py
  50. 1930 0
      debugging_environment/pypdevs/sccd.py
  51. 1086 0
      debugging_environment/pypdevs/sccd.xml
  52. 835 0
      debugging_environment/pypdevs/sccd_classic.xml
  53. 1082 0
      debugging_environment/pypdevs/sccd_fixed_reset.xml
  54. 791 0
      debugging_environment/pypdevs/sccd_parallel.xml
  55. 178 0
      debugging_environment/pypdevs/scheduler.py
  56. 11 0
      debugging_environment/pypdevs/tracer.py
  57. 11 0
      debugging_environment/pypdevs/verbose_tracing.xml
  58. 61 0
      debugging_environment/python_sccd_compiler/code_generation.py
  59. 14 0
      debugging_environment/python_sccd_compiler/compiler_exceptions.py
  60. 994 0
      debugging_environment/python_sccd_compiler/constructs.py
  61. 701 0
      debugging_environment/python_sccd_compiler/csharp_generator.py
  62. 714 0
      debugging_environment/python_sccd_compiler/javascript_generator.py
  63. 149 0
      debugging_environment/python_sccd_compiler/lexer.py
  64. 69 0
      debugging_environment/python_sccd_compiler/path_calculator.py
  65. 644 0
      debugging_environment/python_sccd_compiler/python_generator.py
  66. 112 0
      debugging_environment/python_sccd_compiler/sccdc.py
  67. 151 0
      debugging_environment/python_sccd_compiler/state_linker.py
  68. 154 0
      debugging_environment/python_sccd_compiler/tests.py
  69. 73 0
      debugging_environment/python_sccd_compiler/utils.py
  70. 30 0
      debugging_environment/python_sccd_compiler/visitor.py
  71. 178 0
      debugging_environment/simulation_client.py
  72. 674 0
      javascript_models/LICENSE
  73. 52 0
      javascript_models/README.md
  74. 11 0
      javascript_models/bouncing.html
  75. 1733 0
      javascript_models/bouncing_balls.js
  76. 403 0
      javascript_models/bouncing_balls.js.xml
  77. 1733 0
      javascript_models/bouncing_balls_backup.js
  78. 77 0
      javascript_models/csharp_runtime/Association.cs
  79. 23 0
      javascript_models/csharp_runtime/AssociationException.cs
  80. 22 0
      javascript_models/csharp_runtime/AssociationReferenceException.cs
  81. 12 0
      javascript_models/csharp_runtime/AssociationWrapper.cs
  82. 38 0
      javascript_models/csharp_runtime/ConcurrentOutputListener.cs
  83. 89 0
      javascript_models/csharp_runtime/ControllerBase.cs
  84. 41 0
      javascript_models/csharp_runtime/Event.cs
  85. 105 0
      javascript_models/csharp_runtime/EventQueue.cs
  86. 22 0
      javascript_models/csharp_runtime/GameControllerBase.cs
  87. 11 0
      javascript_models/csharp_runtime/IOutputListener.cs
  88. 23 0
      javascript_models/csharp_runtime/InputException.cs
  89. 34 0
      javascript_models/csharp_runtime/InstanceWrapper.cs
  90. 12 0
      javascript_models/csharp_runtime/MyClass.cs
  91. 253 0
      javascript_models/csharp_runtime/ObjectManagerBase.cs
  92. 34 0
      javascript_models/csharp_runtime/OutputListener.cs
  93. 22 0
      javascript_models/csharp_runtime/ParameterException.cs
  94. 27 0
      javascript_models/csharp_runtime/Properties/AssemblyInfo.cs
  95. 22 0
      javascript_models/csharp_runtime/RunTimeException.cs
  96. 95 0
      javascript_models/csharp_runtime/RuntimeClassBase.cs
  97. 146 0
      javascript_models/csharp_runtime/ThreadsControllerBase.cs
  98. 55 0
      javascript_models/csharp_runtime/sccdlib.csproj
  99. 50 0
      javascript_models/csharp_runtime/sccdlib.sln
  100. 0 0
      javascript_models/csharp_sccd_compiler/Action.cs

+ 15 - 0
.gitignore

@@ -0,0 +1,15 @@
+**/*.pyc
+debugging_environment/node_modules
+debugging_environment/debuglog.txt
+debugging_environment/debug_output.txt
+**/*.project
+**/*.pydevproject
+**/*.log
+**/*.aux
+**/*.bbl
+**/*.aux
+**/*.bak
+**/*.synctex.gz
+**/*.blg
+**/*.out
+**/*.svgz

+ 58 - 0
README.md

@@ -0,0 +1,58 @@
+Usage
+* Server:
+    * inside debugging_environment: `node debugging_server.js`
+* Client:
+    * inside debugging_environment: `python simulation_client.py`
+* Interface:
+    * go to [localhost:9595] (http://localhost:9595) for the debugging interface
+        * Operations (Toolbar):
+            * Simulate: simulates the model as-fast-as-possible.
+            * Realtime Simulate: simulates the model in (scaled) real-time (change the scale by adjusting the parameter to the right of the button).
+            * Pause
+            * Big Step: perform one iteration of the simulation algorithm.
+            * Small Step: perform one of the eight phases of one iteration of the simulation algorithm. Detail on each phase is listed below.
+                * Imminent components are shown in blue.
+                * Selected component is shown in blue.
+                * Output generated is visualized under the output ports. Click on a message to show its contents in the console.
+                * Output is routed along port connections (and potentially translated).
+                * Components that will execute their external transition function are shown in red, those that will execute their internal transition function in blue.
+                * The next state of each transitioning component is computed.
+                * The next time at which an internal transition function is scheduled is computed and displayed.
+                * Structural changes are displayed.
+            * Reset the simulation to its initial state. Also resets the visualization.
+            * Add a Breakpoint with four parameters:
+                * The name of the breakpoint.
+                * A function, returning `True` (simulation halts) or `False` (simulation does not halt). The parameter `t` is an array of two elements representing the current time and phase, `m` is the model being simulated, and `tr` is a set of models that just transitioned to a new state.
+                * Enabled allows to specify whether the breakpoint is enabled or not.
+                * Disable on Trigger allows to specify whether the breakpoint is to be disabled once it has been triggered.
+        * Operations (Canvas Elements):
+            * Instances:
+                * Left-clicking an instance will log its current state in the console.
+                * Right-clicking an instance allows to change one of its state variables with a god event.
+                * Left-clicking an input port allows to inject a message on that port at a specified time.
+            * Breakpoints:
+                * Clicking the trash bin icon next to the breakpoint's name will delete it.
+                * Clicking the breakpoint will enable or disable it.
+                * Triggered breakpoints are highlighted in red.
+        * Information:
+            * Instances:
+                * Names of coupled DEVS models are displayed in italics.
+                * Input ports are green, output ports are purple.
+                * The time at which the next internal transition function is scheduled is shown in the top right corner.
+                * Hovering over an instance will display its current state.
+                * Hovering over a port of an instance shows its name and connections.
+            * The simulation time is displayed, as well as the phase (in case multiple transitions are executed on the same simulated time instance).
+    * go to [localhost:9696] (http://localhost:9696) for the visualization
+        * Left-clicking a particle sends a realtime interrupt to the simulation (which selects that particle).
+        * Pressing the delete button sends a realtime interrupt to the simulation (deleting all selected particles).
+        * Right-clicking a particle will display the state of that particle in the debugging interface.
+
+Models and Source Files
+* User Model: `particle_interaction.py`
+* User Visualization:
+    * Statechart model: `javascript_models/particle_interaction_vis_js_instrumented.xml`
+    * Webpage: `visualization_server.html`
+* Simulator:
+    * Statechart model: `debugging_environment/pypdevs/sccd.xml`
+    * Simulation client: `debugging_environment/simulation_client.py`
+* Communication Layer: `debugging_server.js`

+ 11 - 0
bouncing.html

@@ -0,0 +1,11 @@
+<div>
+<script src="javascript_runtime/statecharts_core.js"></script>
+<script src="javascript_runtime/libs/utils.js"></script>
+<script src="javascript_runtime/libs/svg.js"></script>
+<script src="javascript_runtime/libs/ui.js"></script>
+<script src="bouncing_balls.js"></script>
+<script>
+controller = new Bouncing_Balls.Controller(new JsEventLoop());
+controller.start();
+</script> 
+</div>

File diff suppressed because it is too large
+ 1743 - 0
bouncing_balls.js


+ 403 - 0
bouncing_balls.js.xml

@@ -0,0 +1,403 @@
+<?xml version="1.0" ?>
+<diagram name="Bouncing_Balls" author="Simon Van Mierlo+Joeri Exelmans+Raphael Mannadiar">
+	<description>
+		Tkinter frame with bouncing balls in it.
+	</description>
+	<inport name="field_ui"/>
+	<inport name="ball_ui"/>
+	<inport name="input"/>
+	<class name="Button">
+		<relationships>
+			<association name="parent" class="Field" min="1" max="1"/>
+		</relationships>
+		<method name="Button">
+			<parameter name="parent" type="Field"/>
+			<parameter name="event_name" type="str"/>
+			<parameter name="button_text" type="str"/>
+			<body>
+			<![CDATA[
+				this.event_name = event_name;
+				var button = ui.append_button(parent.field_window, event_name);
+				ui.bind_event(button.element, ui.EVENTS.MOUSE_CLICK, this.controller, 'mouse_click');
+			]]>
+			</body>
+		</method>
+		<scxml  initial="initializing">
+			<state id="initializing">
+				<transition target="../running">
+					<raise event="button_created" scope="narrow" target="'parent'">
+					</raise>
+				</transition>
+			</state>
+			<state id="running">
+				<transition port="ui" target="." event="mouse_click" cond="button == ui.MOUSE_BUTTONS.LEFT">
+					<parameter name="x" type="int"/>
+					<parameter name="y" type="int"/>
+					<parameter name="button" type="Button"/>
+					<raise event="button_pressed" scope="narrow" target="'parent'">
+						<parameter expr="this.event_name"/>
+					</raise>
+				</transition>
+			</state>
+		</scxml>
+	</class>
+	<class name="Field">
+		<inport name="field_ui"/>
+		<relationships>
+			<association name="parent" class="MainApp" min="1" max="1"/>
+			<association name="buttons" class="Button"/>
+			<association name="balls" class="Ball"/>
+		</relationships>
+		<attribute name="field_window"/>
+		<attribute name="canvas"/>
+		<method name="Field">
+			<body>
+			<![CDATA[
+				this.field_window = ui.new_window(400, 450);
+				this.canvas = ui.append_canvas(this.field_window, 400, 400, {'background':'#eee'});
+				ui.bind_event(this.field_window, ui.EVENTS.WINDOW_CLOSE, this.controller, 'window_close');
+				ui.bind_event(this.field_window, ui.EVENTS.KEY_PRESS, this.controller, 'key_press');
+				ui.bind_event(this.canvas.element, ui.EVENTS.MOUSE_RIGHT_CLICK, this.controller, 'right_click', this.inports['field_ui']);
+				ui.bind_event(this.canvas.element, ui.EVENTS.MOUSE_MOVE, this.controller, 'mouse_move');
+				ui.bind_event(this.canvas.element, ui.EVENTS.MOUSE_RELEASE, this.controller, 'mouse_release');
+			]]>
+			</body>
+		</method>
+		<method name="~Field">
+			<body>
+			<![CDATA[
+				ui.close_window(this.field_window);
+			]]>
+			</body>
+		</method>
+		<scxml  initial="root">
+			<state id="root" initial="waiting">
+				<state id="waiting">
+					<transition target="../initializing" event="set_association_name">
+						<parameter name="association_name" type="str"/>
+						<script>
+							<![CDATA[
+								this.association_name = association_name;
+							]]>
+						</script>
+					</transition>
+				</state>
+				<state id="packing">
+					<transition target="../running" event="button_created">
+					</transition>
+				</state>
+				<state id="deleting">
+					<transition after="0.05" target="../deleted">
+						<raise event="delete_field" scope="narrow" target="'parent'">
+							<parameter expr="this.association_name"/>
+						</raise>
+					</transition>
+				</state>
+				<state id="creating">
+					<transition target="../packing" event="instance_created">
+						<parameter name="association_name" type="string"/>
+						<raise event="start_instance" scope="cd">
+							<parameter expr="association_name"/>
+						</raise>
+					</transition>
+				</state>
+				<state id="initializing">
+					<transition target="../creating">
+						<raise event="create_instance" scope="cd">
+							<parameter expr="'buttons'"/>
+							<parameter expr="'Button'"/>
+							<parameter expr="this"/>
+							<parameter expr="'create_new_field'"/>
+							<parameter expr="'Spawn New Window'"/>
+						</raise>
+					</transition>
+				</state>
+				<state id="deleted">
+				</state>
+				<parallel id="running">
+					<transition port="ui" target="../deleting" event="window_close" cond="window == this.field_window || window == ui.window">
+						<parameter name="window" type="Window"/>
+						<raise event="delete_instance" scope="cd">
+							<parameter expr="'buttons'"/>
+						</raise>
+						<raise event="delete_self" scope="narrow" target="'balls'">
+						</raise>
+					</transition>
+					<state id="main_behaviour" initial="running">
+						<state id="running">
+							<transition port="field_ui" target="../creating" event="right_click">
+								<parameter name="x" type="int"/>
+								<parameter name="y" type="int"/>
+								<parameter name="button" type="Button"/>
+								<raise event="create_instance" scope="cd">
+									<parameter expr="'balls'"/>
+									<parameter expr="'Ball'"/>
+									<parameter expr="this.canvas"/>
+									<parameter expr="x"/>
+									<parameter expr="y"/>
+									<parameter expr="this.field_window"/>
+								</raise>
+							</transition>
+						</state>
+						<state id="creating">
+							<transition target="../running" event="instance_created">
+								<parameter name="association_name" type="string"/>
+								<raise event="set_association_name" scope="narrow" target="association_name">
+									<parameter expr="association_name"/>
+								</raise>
+								<raise event="start_instance" scope="cd">
+									<parameter expr="association_name"/>
+								</raise>
+							</transition>
+						</state>
+					</state>
+					<state id="deleting_behaviour" initial="running">
+						<state id="running">
+							<transition target="." event="delete_ball">
+								<parameter name="association_name" type="str"/>
+								<raise event="delete_instance" scope="cd">
+									<parameter expr="association_name"/>
+								</raise>
+							</transition>
+						</state>
+					</state>
+					<state id="child_behaviour" initial="listening">
+						<state id="listening">
+							<transition target="." event="button_pressed">
+								<parameter name="event_name" type="str"/>
+								<raise event="button_pressed" scope="narrow" target="'parent'">
+									<parameter expr="event_name"/>
+								</raise>
+							</transition>
+						</state>
+					</state>
+				</parallel>
+			</state>
+		</scxml>
+	</class>
+	<class name="MainApp" default="True">
+		<relationships>
+			<association name="fields" class="Field"/>
+		</relationships>
+		<method name="MainApp">
+			<body>
+			<![CDATA[
+				this.nr_of_fields = 0;
+				ui.bind_event(ui.window, ui.EVENTS.WINDOW_CLOSE, this.controller, 'window_close');
+			]]>
+			</body>
+		</method>
+		<scxml  initial="running">
+			<state id="running" initial="root">
+				<state id="stopped">
+				</state>
+				<parallel id="root">
+					<state id="main_behaviour" initial="initializing">
+						<state id="initializing">
+							<transition target="../running">
+								<raise event="create_field">
+								</raise>
+							</transition>
+						</state>
+						<state id="running">
+							<transition target="." event="button_pressed" cond="event_name == 'create_new_field'">
+								<parameter name="event_name" type="str"/>
+								<raise event="create_field">
+								</raise>
+							</transition>
+						</state>
+					</state>
+					<state id="cd_behaviour" initial="waiting">
+						<state id="creating">
+							<transition target="../waiting" event="instance_created">
+								<parameter name="association_name" type="string"/>
+								<raise event="start_instance" scope="cd">
+									<parameter expr="association_name"/>
+								</raise>
+								<raise event="set_association_name" scope="narrow" target="association_name">
+									<parameter expr="association_name"/>
+								</raise>
+								<script>
+									<![CDATA[
+										this.nr_of_fields += 1;
+									]]>
+								</script>
+							</transition>
+						</state>
+						<state id="waiting">
+							<transition target="../creating" event="create_field">
+								<raise event="create_instance" scope="cd">
+									<parameter expr="'fields'"/>
+								</raise>
+							</transition>
+							<transition target="../check_nr_of_fields" event="delete_field">
+								<parameter name="association_name" type="str"/>
+								<raise event="delete_instance" scope="cd">
+									<parameter expr="association_name"/>
+								</raise>
+								<script>
+									<![CDATA[
+										this.nr_of_fields -= 1;
+									]]>
+								</script>
+							</transition>
+						</state>
+						<state id="check_nr_of_fields">
+							<transition target="../waiting" cond="this.nr_of_fields != 0">
+							</transition>
+							<transition target="../../../stopped" cond="this.nr_of_fields == 0">
+								<script>
+									<![CDATA[
+										ui.close_window(ui.window);
+									]]>
+								</script>
+							</transition>
+						</state>
+					</state>
+				</parallel>
+			</state>
+		</scxml>
+	</class>
+	<class name="Ball">
+		<inport name="ball_ui"/>
+		<relationships>
+			<association name="parent" class="Field" min="1" max="1"/>
+		</relationships>
+		<attribute name="field_window"/>
+		<attribute name="canvas"/>
+		<attribute name="element"/>
+		<method name="Ball">
+			<parameter name="canvas"/>
+			<parameter name="x"/>
+			<parameter name="y"/>
+			<parameter name="field_window"/>
+			<body>
+			<![CDATA[
+				this.canvas = canvas;
+				this.field_window = field_window;
+				this.r = 20.0;
+				this.vel = {'x':utils.random() * 2.0 - 1.0, 'y':utils.random() * 2.0 - 1.0};
+				this.mouse_pos = {'':''};
+				this.smooth = 0.4;
+				var circle = this.canvas.add_circle(x, y, this.r, {'fill':'#000'});
+				ui.bind_event(circle, ui.EVENTS.MOUSE_PRESS, this.controller, 'mouse_press', this.inports['ball_ui']);
+				ui.bind_event(circle, ui.EVENTS.MOUSE_RIGHT_CLICK, this.controller, 'right_click');
+				this.element = circle;
+			]]>
+			</body>
+		</method>
+		<method name="~Ball">
+			<body>
+			<![CDATA[
+				this.canvas.remove_element(this.element);
+			]]>
+			</body>
+		</method>
+		<scxml  initial="main_behaviour">
+			<state id="main_behaviour" initial="initializing">
+				<transition target="../deleted" event="delete_self">
+					<raise event="delete_ball" scope="narrow" target="'parent'">
+						<parameter expr="this.association_name"/>
+					</raise>
+				</transition>
+				<state id="dragging">
+					<transition port="ui" target="../bouncing" event="mouse_release">
+						<parameter name="x" type="int"/>
+						<parameter name="y" type="int"/>
+						<script>
+							<![CDATA[
+								this.element.set_color('#f00');
+							]]>
+						</script>
+					</transition>
+					<transition port="ui" target="." event="mouse_move">
+						<parameter name="x" type="int"/>
+						<parameter name="y" type="int"/>
+						<parameter name="button" type="Button"/>
+						<script>
+							<![CDATA[
+								var dx = x - this.mouse_pos['x'];
+								var dy = y - this.mouse_pos['y'];
+								this.element.move(dx, dy);
+								var pos = this.element.get_position();
+								if(pos.x - this.r <= 0) {
+									pos.x = this.r + 1;
+								} else {
+									if(pos.x + this.r >= this.canvas.width) {
+										pos.x = this.canvas.width - this.r - 1;
+									}
+								}
+								if(pos.y - this.r <= 0) {
+									pos.y = this.r + 1;
+								} else {
+									if(pos.y + this.r >= this.canvas.height) {
+										pos.y = this.canvas.height - this.r - 1;
+									}
+								}
+								this.element.set_position(pos.x, pos.y);
+								this.mouse_pos = {'x':x, 'y':y};
+								this.vel = {'x':(1 - this.smooth) * dx + this.smooth * this.vel['x'], 'y':(1 - this.smooth) * dy + this.smooth * this.vel['y']};
+							]]>
+						</script>
+					</transition>
+				</state>
+				<state id="selected">
+					<transition port="ball_ui" target="../dragging" event="mouse_press" cond="button == ui.MOUSE_BUTTONS.LEFT">
+						<parameter name="x" type="int"/>
+						<parameter name="y" type="int"/>
+						<parameter name="button" type="Button"/>
+						<script>
+							<![CDATA[
+								this.mouse_pos = {'x':x, 'y':y};
+							]]>
+						</script>
+					</transition>
+					<transition port="ui" target="." event="key_press" cond="key == ui.KEYCODES.DELETE &amp;&amp; active_window == this.field_window">
+						<parameter name="key" type="Key"/>
+						<parameter name="active_window" type="Window"/>
+						<raise event="delete_self" scope="local">
+						</raise>
+					</transition>
+				</state>
+				<state id="initializing">
+					<transition target="../bouncing" event="set_association_name">
+						<parameter name="association_name" type="str"/>
+						<script>
+							<![CDATA[
+								this.association_name = association_name;
+							]]>
+						</script>
+					</transition>
+				</state>
+				<state id="bouncing">
+					<transition after="0.01" target=".">
+						<script>
+							<![CDATA[
+								var pos = this.element.get_position();
+								if(pos.x - this.r <= 0 || pos.x + this.r >= this.canvas.width) {
+									this.vel['x'] = -this.vel['x'];
+								}
+								if(pos.y - this.r <= 0 || pos.y + this.r >= this.canvas.height) {
+									this.vel['y'] = -this.vel['y'];
+								}
+								this.element.move(this.vel['x'], this.vel['y']);
+							]]>
+						</script>
+					</transition>
+					<transition port="ball_ui" target="../selected" event="mouse_press" cond="button == ui.MOUSE_BUTTONS.LEFT">
+						<parameter name="x" type="int"/>
+						<parameter name="y" type="int"/>
+						<parameter name="button" type="Button"/>
+						<script>
+							<![CDATA[
+								this.element.set_color('#ff0');
+							]]>
+						</script>
+					</transition>
+				</state>
+			</state>
+			<state id="deleted">
+			</state>
+		</scxml>
+	</class>
+</diagram>

+ 203 - 0
debugging_environment/debugging_environment.html

@@ -0,0 +1,203 @@
+<!DOCTYPE html>
+<head>
+    <meta charset="utf-8">
+    <script type="text/javascript" src="http://code.jquery.com/jquery-2.2.1.min.js"></script>
+    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
+    <link rel="stylesheet" type="text/css" href="javascript_runtime/libs/w2ui-1.4.3.min.css" />
+    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
+    <script src="javascript_runtime/libs/w2ui-1.4.3.min.js"></script>
+    <script src="http://d3js.org/d3.v3.min.js"></script>
+    <script type="text/javascript" src="javascript_runtime/libs/ui.js"></script>
+    <script type="text/javascript" src="javascript_runtime/statecharts_core.js"></script>
+    <script src="/socket.io/socket.io.js"></script>
+    
+    <style type="text/css">
+        .w2ui-icon.simulate { background: url('img/simulate.png') no-repeat center !important; }
+        .w2ui-icon.simulatert { background: url('img/simulatert.png') no-repeat center !important; }
+        .w2ui-icon.pause { background: url('img/pause.png') no-repeat center !important; }
+        .w2ui-icon.bigstep { background: url('img/bigstep.png') no-repeat center !important; }
+        .w2ui-icon.smallstep { background: url('img/smallstep.png') no-repeat center !important; }
+        .w2ui-icon.reset { background: url('img/reset.png') no-repeat center !important; }
+        .w2ui-icon.breakpoint { background: url('img/breakpoint.png') no-repeat center !important; }
+    </style>
+    
+    <style type="text/css">
+        .node rect {
+          fill: #fff;
+          stroke: #000;
+          stroke-width: 1px;
+          fill-opacity: 0.7;
+        }
+        .imminent rect {
+          fill: lightblue;
+        }
+        .INTERNAL rect {
+          fill: lightblue;
+        }
+        .EXTERNAL rect {
+          fill: tomato;
+        }
+        text { font: bold 12px sans-serif; }
+        .timeNext { font: bold 10px sans-serif; }
+        .link {
+          fill: none;
+          stroke: #bbb;
+        }
+        .portConnection {
+          fill: none;
+          stroke: red;
+          marker-mid: url(#marker_arrow);
+        }
+        .input {
+          stroke: green;
+          marker-mid: url(#marker_arrow_green);
+        }
+        .invisibleLink {         
+         stroke-width: 0;
+        }
+        .invisible text { 
+          fill-opacity: 0;
+        }
+        .visible text { 
+          fill-opacity: 1;
+        }
+        .outmessage {
+          fill: yellow;
+          stroke: #000;
+          fill-opacity: 0.7;
+        }
+        .inmessage {
+          fill: orange;
+          stroke: #000;
+          fill-opacity: 0.7;
+        }
+        .invisibleInfo tspan {
+          fill-opacity: 0;
+        }
+        .smallStepInfo {
+          border: 1px solid black;
+          background-color: blue;
+          width: 7px;
+          height: 7px;
+          float: left;
+        }
+        .inactive {
+          opacity: 0.3;
+        }
+        .invisibleInfo {
+          display: none;
+        }
+        .coupled text {
+          font-style: italic;
+        }
+        form { display: table;      }
+        form p { display: table-row;  }
+        form p label { display: table-cell; }
+        form p input { display: table-cell; }
+    </style>
+</head>
+<body>
+    <div id="godEventPopup" class="popupWindow" title="Insert God Event">
+        <form>
+            <p>
+                <label for="godEventName">Name:</label>
+                <input type="text" id="godEventName" class="text ui-widget-content ui-corner-all" />
+            </p>
+            <p>
+                <label for="godEventValue">Value:</label>
+                <input type="text" id="godEventValue" class="text ui-widget-content ui-corner-all" />
+            </p>
+        </form>
+    </div>
+    <div id="injectEventPopup" class="popupWindow" title="Inject Event">
+        <form>
+            <p>
+                <label for="injectEvent">Event:</label>
+                <input type="text" id="injectEvent" class="text ui-widget-content ui-corner-all" />
+            </p>
+            <p>
+                <label for="injectTime">Time:</label>
+                <input type="text" id="injectTime" class="text ui-widget-content ui-corner-all" />
+            </p>
+        </form>
+    </div>
+    <div id="breakpointPopup" class="popupWindow" title="Add Breakpoint">
+        <form>
+            <p>
+                <label for="breakpointName">Name:</label>
+                <input type="text" id="breakpointName" class="text ui-widget-content ui-corner-all" />
+            </p>
+            <p>
+                <label for="breakpointFunction">Function:</label>
+                <textarea id="breakpointFunction" class="text ui-widget-content ui-corner-all" style="width:400px;height:150px;">def breakpoint(t, m, tr, ob, ib):
+  </textarea>
+            </p>
+            <p>
+                <label for="breakpointEnabled">Enabled:</label>
+                <input type="checkbox" id="breakpointEnabled" class="ui-widget-content ui-corner-all" checked />
+            </p>
+            <p>
+                <label for="breakpointDisableOnTrigger">Disable on Trigger:</label>
+                <input type="checkbox" id="breakpointDisableOnTrigger" class="ui-widget-content ui-corner-all" checked />
+            </p>
+        </form>
+    </div>
+    <script type="text/javascript" src="debugging_environment.js"></script>
+    <script>
+        var controller = new DebuggingEnvironment.Controller();
+        var ui_reply_port = controller.addOutputListener('output');
+        var socket = io();
+
+        /*
+        Check whether the user interacted with the debugging UI. If so, forward to communication layer.
+        */
+        setInterval(function() {
+            while (true) {
+                reply_msg = ui_reply_port.fetch(0)
+                if (reply_msg == undefined) {
+                    break
+                }
+                // console.log(JSON.stringify(reply_msg));
+                socket.emit('message', JSON.stringify(reply_msg) + "\n");
+            }
+        }, 5)
+
+        /*
+        When we receive a message from the communication layer (either from the simulator itself or the visualization interface),
+        translate it to the correct event for the visualization Statechart.
+        */
+        socket.on('msg', function(msg){
+            if (msg.substring(0, 4) == "vis_") {
+                // message from the visualization interface
+                msg = JSON.parse(msg.substring(4));
+                cmd = msg["name"];
+                if (cmd == "select_instance") {
+                    controller.addInput(new Event("select_instance", "ui_input", msg["parameters"]), 0.0);
+                }
+            } else {
+                // message from the simulator (a state update, breakpoint trigger, ...)
+                // console.log(msg);
+                msg = JSON.parse(msg)[0];
+                if (msg["name"] == "all_states"
+                    || msg["name"] == "all_states_reset"
+                    || msg["name"] == "new_states"
+                    || msg["name"] == "imminents"
+                    || msg["name"] == "selected_imminent"
+                    || msg["name"] == "outbag"
+                    || msg["name"] == "inbags"
+                    || msg["name"] == "transitioning"
+                    || msg["name"] == "new_internal_states"
+                    || msg["name"] == "new_tn"
+                    || msg["name"] == "structural_changes"
+                    || msg["name"] == "god_event_ok"
+                    || msg["name"] == "inject_ok"
+                    || msg["name"] == "breakpoint_triggered") {
+                    controller.addInput(new Event(msg["name"], "simulation_input", [msg["parameters"]]), 0.0)
+                }
+            }
+        });
+
+        controller.start();
+    </script>
+    <span id="currLoc" style="display:none" />
+</body>

File diff suppressed because it is too large
+ 1857 - 0
debugging_environment/debugging_environment.js


File diff suppressed because it is too large
+ 1109 - 0
debugging_environment/debugging_environment.xml


+ 147 - 0
debugging_environment/debugging_server.js

@@ -0,0 +1,147 @@
+var express = require('express');
+var http = require('http')
+var io = require('socket.io');
+var net = require('net');
+
+var app_debugging = express();
+var http_debugging = http.Server(app_debugging)
+var io_debugging = io(http_debugging);
+var app_vis = express();
+var http_vis = http.Server(app_vis)
+var io_vis = io(http_vis);
+
+var queue = []
+
+// serve GET requests of client for debugging interface
+app_debugging.get('*', function(req, res) {
+    if ( req.url == '/' ) {
+        res.sendFile(__dirname + '/debugging_environment.html');
+    } else if ( req.url.match(/\.js$/)
+                || req.url.match(/\.html$/)
+                || req.url.match(/\.css$/)
+                || req.url.match(/\.png$/)
+               ) {
+        res.sendFile(__dirname + req.url);
+    }
+});
+
+// user connects on the debugging interface: queue all incoming messages and tag them as debug messages
+io_debugging.on('connection', function(socket){
+    console.log('A user connected!');
+    
+    socket.on('message', function(msg) {
+        queue.push('dbg_' + msg);
+    })
+});
+
+http_debugging.listen(9595, function() {
+    console.log('Listening for user on port 9595');
+});
+
+// serve GET requests of client for visualization interface
+app_vis.get('*', function(req, res) {
+    if ( req.url == '/' ) {
+        res.sendFile('/visualization_server.html', {root: '../'});
+    } else if ( req.url.match(/\.js$/)
+                || req.url.match(/\.html$/)
+                || req.url.match(/\.css$/)
+                || req.url.match(/\.png$/)
+               ) {
+        res.sendFile(req.url, {root: '../'});
+    }
+});
+
+// user connects on the visualization interface: queue all incoming messages and tag them as visualization messages
+io_vis.on('connection', function(socket){
+    console.log('A user connected!');
+    
+    socket.on('message', function(msg) {
+        queue.push('vis_' + msg);
+    })
+});
+
+http_vis.listen(9696, function() {
+    console.log('Listening for user on port 9696');
+});
+
+String.prototype.endsWith = function(suffix) {
+    return this.indexOf(suffix, this.length - suffix.length) !== -1;
+};
+
+/*
+This is the server that ties debugging UI - visualization UI - debuggable simulator together.
+It waits for the simulation client to connect on port 9999 and coordinates all message traffic between the three components.
+*/
+net.createServer(function(sock) {
+    console.log('CONNECTED: ' + sock.remoteAddress + ':' + sock.remotePort);
+    
+    buffer = '';
+    
+    // Protocol: each message ends with a newline. Buffers messages until the buffer ends with a new line, in case a message is only partially sent.
+    sock.on('data', function(data) {       
+        buffer += String(data);
+        if (buffer.endsWith('\n')) {
+            String(buffer).split('\n').forEach(function(entry) {
+                if (entry != '') {
+                    try {
+                        msg = eval(entry); // TODO: probably not a very good idea, msg = JSON.parse(entry); is better but doesn't work with Infinity
+                    } catch (err) {
+                        throw err;
+                    }
+                    if (msg[0] == "VIS") {
+                        // visualization messages are sent to the visualization interface
+                        io_vis.emit('msg', JSON.stringify(msg.slice(1)));
+                    } else if (msg[0] == "DBG") {
+                        // debugging messages (state updates, for example) are sent to the debugging interface
+                        io_debugging.emit('msg', JSON.stringify(msg.slice(1)));
+                    }
+                }
+            })
+            buffer = '';
+        }
+        
+    });
+    
+    sock.on('close', function(data) {
+        console.log('CLOSED: ' + sock.remoteAddress + ' ' + sock.remotePort);
+    });
+    
+    sock.on('error', function(error) {
+        console.log('ERROR: ' + error);
+    });
+    
+    /*
+    Every 5 milliseconds, check whether any message was sent by the user from the debugging interface and/or the visualization interface. If so, pass it on.
+    In case of a message from the debugging interface: send it to the simulator, although if it's a reset, also forward to the visualization.
+    In case of a message from the visualization interface: only send it to the debugger when it's an interrupt. Send it to the debugging interface if it's a message wanting to select an entity.
+    */
+    setInterval(function() {
+        while (queue.length) {
+            var msg = queue.pop();
+            var msg_head = msg.substring(0, 4)
+            if (msg_head == "dbg_") {
+                var parsed_msg = eval('(' + msg.substring(4) + ')');
+                // forward selected messages to visualization
+                if (parsed_msg["parameters"].length && parsed_msg["parameters"][0] == "reset") {
+                    io_vis.emit('msg', msg);
+                }
+                // forward to simulator
+                sock.write(msg + '\n');
+            } else if (msg_head == "vis_") {
+                if (msg.substring(4).lastIndexOf('INTERRUPT', 0) == 0) {
+                    // forward to simulator
+                    sock.write(msg + '\n');
+                } else {
+                    var parsed_msg = eval('(' + msg.substring(4) + ')');
+                    // forward selected messages to debugging interface
+                    if (parsed_msg["name"] == "select_instance") {
+                        io_debugging.emit('msg', msg);
+                    }
+                }
+            }
+        }
+    }, 5)
+    
+}).listen(9999, '127.0.0.1');
+
+console.log('Listening for simulator on localhost:9999');

+ 152 - 0
debugging_environment/examples_sccd_sim/client.py

@@ -0,0 +1,152 @@
+print("SCCD PythonPDEVS CLI interface")
+import sys
+import time
+sys.path.append("../pypdevs/")
+from python_runtime.statecharts_core import Event
+
+import sccd
+from model import Root
+controller = sccd.Controller(Root())
+controller.start()
+reply_port = controller.addOutputListener('reply')
+
+def set_defaults(inp, defaultlist):
+    for i, v in enumerate(defaultlist):
+        if len(inp) == i + 1:
+            inp.append(v)
+
+def get_bool(val):
+    if val.lower() in ["true", "yes", "1"]:
+        return True
+    else:
+        return False
+
+def poll_port(port):
+    while 1:
+        try:
+            print(port.fetch(-1))
+        except:
+            pass
+
+try:
+    import threading
+    thrd = threading.Thread(target=poll_port,args=[reply_port])
+    thrd.daemon = True
+    thrd.start()
+    print("READY for input")
+    print("Type 'help' for information")
+    while 1:
+        inp = raw_input().split(" ")
+        action = inp[0]
+        if inp[0] == "simulate":
+            set_defaults(inp, ['inf'])
+            params = [{"termination_time": float(inp[1])}]
+        elif inp[0] == "big_step":
+            set_defaults(inp, ['inf'])
+            params = [{"termination_time": float(inp[1])}]
+        elif inp[0] == "realtime":
+            set_defaults(inp, ['inf', 1.0])
+            params = [{"termination_time": float(inp[1]), "realtime_scale": float(inp[2])}]
+        elif inp[0] == "small_step":
+            set_defaults(inp, ['inf'])
+            params = [{"termination_time": float(inp[1])}]
+        elif inp[0] == "god_event":
+            if len(inp) != 4:
+                print("God Events require 3 parameters!")
+                continue
+            params = [{"model": inp[1], "attribute": inp[2], "value": inp[3]}]
+        elif inp[0] == "inject":
+            if len(inp) != 4:
+                print("Injects require 3 parameters!")
+                continue
+            params = [{"time": float(inp[1]), "port": inp[2], "event": inp[3]}]
+        elif inp[0] == "trace":
+            set_defaults(inp, [None])
+            params = [inp[1]]
+        elif inp[0] == "pause":
+            params = []
+        elif inp[0] == "exit" or inp[0] == "quit":
+            break
+        elif inp[0] == "add_breakpoint":
+            if len(inp) < 5:
+                print("Breakpoint removal requires 2 parameters!")
+                continue
+            # Merge together the final part again
+            inp = [inp[0], inp[1], " ".join(inp[2:-2]).replace("\\n", "\n"), get_bool(inp[-2]), get_bool(inp[-1])]
+            print("Generated parameters: " + str(inp))
+            params = inp[1:]
+        elif inp[0] == "del_breakpoint":
+            if len(inp) < 2:
+                print("Breakpoint removal requires 1 parameter!")
+                continue
+            params = [inp[1]]
+        elif inp[0] == "enable_breakpoint":
+            action = "toggle_breakpoint"
+            params = [inp[1], True]
+        elif inp[0] == "disable_breakpoint":
+            action = "toggle_breakpoint"
+            params = [inp[1], False]
+        elif inp[0] == "reset":
+            params = []
+        elif inp[0] == "backwards_step":
+            params = []
+        elif inp[0] == "help":
+            print("Supported operations:")
+            print("  simulate [termination_time]")
+            print("   --> Simulate until termination time is reached")
+            print("  big_step [termination_time]")
+            print("   --> Simulate a single step, unless termination time is reached")
+            print("  small_step [termination_time]")
+            print("   --> Simulate a single internal simulation step")
+            print("       Termination time is ONLY checked at the")
+            print("       check_termination phase")
+            print("  backwards_step")
+            print("   --> Step back to the previous time")
+            print("  realtime [termination_time [realtime_scale]]")
+            print("   --> Simulate in realtime until simulation time is reached")
+            print("       realtime_scale can speed up or slow down the pace")
+            print("  god_event model_name attribute_name new_value")
+            print("   --> Modify the internal state of an arbitrary model")
+            print("       model_name should be the fully qualified name")
+            print("       attribute_name is the name of the attribute to alter")
+            print("       new_value is the value to assign")
+            print("       new_value can only be a string due to string-only input")
+            print("  inject time port_name event")
+            print("   --> Put a user-defined event on an input port")
+            print("       port_name should be a fully qualified port name")
+            print("       event should be the event to put on it, string only")
+            print("  trace [filename]")
+            print("   --> Write out trace information to the specified file.")
+            print("       Leave empty to disable tracing.")
+            print("  add_breakpoint id function enabled disable_on_trigger")
+            print("   --> Add a breakpoint that will pause simulation when function returns True")
+            print("       the function should contain a definition of the 'breakpoint' function")
+            print("       and must take 3 parameters: time, model and transitioned")
+            print("       enabled indicates whether or not the breakpoint should be checked")
+            print("       disable_on_trigger determines if the breakpoint should auto-disable")
+            print("       after being triggered")
+            print("  del_breakpoint id")
+            print("   --> Remove a breakpoint")
+            print("  enable_breakpoint id")
+            print("   --> Enable the provided breakpoint")
+            print("  disable_breakpoint id")
+            print("   --> Disable the provided breakpoint")
+            print("  reset")
+            print("   --> Reset the simulation")
+            print("  exit")
+            print("   --> Stop the client")
+            print("  pause")
+            print("   --> Pause the simulation")
+            print("  quit")
+            print("   --> Stop the client")
+            print("")
+            print("Defaults: ")
+            print("  termination_time --> 'inf'")
+            print("  realtime_scale   --> 1.0")
+            continue
+        else:
+            print("Command not understood: " + str(inp))
+            continue
+        controller.addInput(Event(action, "request", params))
+finally:
+    controller.stop()

+ 296 - 0
debugging_environment/examples_sccd_sim/model.py

@@ -0,0 +1,296 @@
+# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at 
+# McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
+# 
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import sys
+
+# Import code for DEVS model representation:
+from DEVS import *
+from infinity import INFINITY
+
+class TrafficLightMode:
+    """
+    Encapsulates the system's state
+    """
+
+    def __init__(self, current="red"):
+        """
+        Constructor (parameterizable).
+        """
+        self.set(current)
+
+    def set(self, value="red"):
+        self.colour=value
+
+    def get(self):
+        return self.colour
+
+    def __str__(self):
+        return self.get()
+
+class TrafficLight(AtomicDEVS):
+    """
+    A traffic light 
+    """
+  
+    def __init__(self, name=None):
+        """
+        Constructor (parameterizable).
+        """
+        # Always call parent class' constructor FIRST:
+        AtomicDEVS.__init__(self, name)
+    
+        # STATE:
+        #  Define 'state' attribute (initial sate):
+        self.state = TrafficLightMode("red") 
+
+        # ELAPSED TIME:
+        #  Initialize 'elapsed time' attribute if required
+        #  (by default, value is 0.0):
+        self.elapsed = 1.5 
+        # with elapsed time initially 1.5 and initially in 
+        # state "red", which has a time advance of 60,
+        # there are 60-1.5 = 58.5time-units  remaining until the first 
+        # internal transition 
+    
+        # PORTS:
+        #  Declare as many input and output ports as desired
+        #  (usually store returned references in local variables):
+        self.INTERRUPT = self.addInPort(name="INTERRUPT")
+        self.OBSERVED = self.addOutPort(name="OBSERVED")
+
+    def extTransition(self, inputs):
+        """
+        External Transition Function.
+        """
+        # Compute the new state 'Snew' based (typically) on current
+        # State, Elapsed time parameters and calls to 'self.peek(self.IN)'.
+        input = inputs.get(self.INTERRUPT)
+
+        state = self.state.get()
+
+        if input == "toManual":
+            if state == "manual":
+                # staying in manual mode
+                return TrafficLightMode("manual")
+            elif state in ("red", "green", "yellow"):
+                return TrafficLightMode("manual")
+        elif input == "toAutonomous":
+            if state == "manual":
+                return TrafficLightMode("red")
+            elif state in ("red", "green", "yellow"):
+                # If toAutonomous is given while still autonomous, just stay in this state
+                return self.state
+        raise DEVSException(\
+            "unknown state <%s> in TrafficLight external transition function"\
+            % state) 
+
+    def intTransition(self):
+        """
+        Internal Transition Function.
+        """
+
+        state = self.state.get()
+
+        if state == "red":
+            return TrafficLightMode("green")
+        elif state == "green":
+            return TrafficLightMode("yellow")
+        elif state == "yellow":
+            return TrafficLightMode("red")
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in TrafficLight internal transition function"\
+                % state)
+  
+    def outputFnc(self):
+        """
+        Output Funtion.
+        """
+   
+        # A colourblind observer sees "grey" instead of "red" or "green".
+ 
+        # BEWARE: ouput is based on the OLD state
+        # and is produced BEFORE making the transition.
+        # We'll encode an "observation" of the state the
+        # system will transition to !
+
+        # Send messages (events) to a subset of the atomic-DEVS' 
+        # output ports by means of the 'poke' method, i.e.:
+        # The content of the messages is based (typically) on current State.
+ 
+        state = self.state.get()
+
+        if state == "red":
+            return {self.OBSERVED: "grey"}
+        elif state == "green":
+            return {self.OBSERVED: "yellow"}
+        elif state == "yellow":
+            return {self.OBSERVED: "grey"}
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in TrafficLight external transition function"\
+                % state)
+    
+    def timeAdvance(self):
+        """
+        Time-Advance Function.
+        """
+        # Compute 'ta', the time to the next scheduled internal transition,
+        # based (typically) on current State.
+        state = self.state.get()
+        if state == "red":
+            return 60 
+        elif state == "green":
+            return 50 
+        elif state == "yellow":
+            return 10 
+        elif state == "manual":
+            return INFINITY 
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in TrafficLight time advance transition function"\
+                % state)
+
+class PolicemanMode:
+    """
+    Encapsulates the Policeman's state
+    """
+    def __init__(self, current="idle"):
+        """
+        Constructor (parameterizable).
+        """
+        self.set(current)
+
+    def set(self, value="idle"):
+        self.__mode=value
+
+    def get(self):
+        return self.__mode
+
+    def __str__(self):
+        return self.get()
+
+class Policeman(AtomicDEVS):
+    """
+    A policeman producing "toManual" and "toAutonomous" events:
+    "toManual" when going from "idle" to "working" mode
+    "toAutonomous" when going from "working" to "idle" mode
+    """
+    def __init__(self, name=None):
+        """
+        Constructor (parameterizable).
+        """
+    
+        # Always call parent class' constructor FIRST:
+        AtomicDEVS.__init__(self, name)
+    
+        # STATE:
+        #  Define 'state' attribute (initial sate):
+        self.state = PolicemanMode("idle") 
+
+        # ELAPSED TIME:
+        #  Initialize 'elapsed time' attribute if required
+        #  (by default, value is 0.0):
+        self.elapsed = 0 
+    
+        # PORTS:
+        #  Declare as many input and output ports as desired
+        #  (usually store returned references in local variables):
+        self.OUT = self.addOutPort(name="OUT")
+
+    def intTransition(self):
+        """
+        Internal Transition Function.
+        The policeman works forever, so only one mode. 
+        """
+  
+        state = self.state.get()
+
+        if state == "idle":
+            return PolicemanMode("working")
+        elif state == "working":
+            return PolicemanMode("idle")
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in Policeman internal transition function"\
+                % state)
+    
+    def outputFnc(self):
+        """
+        Output Funtion.
+        """
+        # Send messages (events) to a subset of the atomic-DEVS' 
+        # output ports by means of the 'poke' method, i.e.:
+        # The content of the messages is based (typically) on current State.
+        state = self.state.get()
+        if state == "idle":
+            return {self.OUT: "toManual"}
+        elif state == "working":
+            return {self.OUT: "toAutonomous"}
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in Policeman output function"\
+                % state)
+    
+    def timeAdvance(self):
+        """
+        Time-Advance Function.
+        """
+        # Compute 'ta', the time to the next scheduled internal transition,
+        # based (typically) on current State.
+    
+        state = self.state.get()
+
+        if state == "idle":
+            return 200 
+        elif state == "working":
+            return 100 
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in Policeman time advance function"\
+                % state)
+
+class Root(CoupledDEVS):
+    def __init__(self, name="TrafficSystem"):
+        """
+        A simple traffic system consisting of a Policeman and a TrafficLight.
+        """
+        # Always call parent class' constructor FIRST:
+        CoupledDEVS.__init__(self, name)
+
+        # Declare the coupled model's output ports:
+        # Autonomous, so no output ports
+
+        # Declare the coupled model's sub-models:
+
+        # The Policeman generating interrupts 
+        self.policeman = self.addSubModel(Policeman(name="policeman"))
+
+        # The TrafficLight 
+        self.trafficLight = self.addSubModel(TrafficLight(name="trafficLight"))
+
+        # Only connect ...
+        self.connectPorts(self.policeman.OUT, self.trafficLight.INTERRUPT)
+
+    def select(self, immChildren):
+        """
+        Choose a model to transition from all possible models.
+        """
+        # Policeman has priority over the traffic light
+        if self.policeman in immChildren:
+            return self.policeman
+        else:
+            # Doesn't really matter, as they don't influence each other
+            return immChildren[0]

+ 167 - 0
debugging_environment/examples_sccd_sim/model_processor.py

@@ -0,0 +1,167 @@
+import sys
+sys.path.append("../../pypdevs/src/")
+
+from DEVS import *
+from infinity import INFINITY
+
+class GeneratorState:
+	def __init__(self, name=""):
+		self.name = name
+
+class ProcessorState:
+	def __init__(self, name="", job=None):
+		self.name = name
+		self.job = job
+
+class CollectorState:
+	def __init__(self, name="", nr_of_jobs=None):
+		self.name = name
+		self.nr_of_jobs = nr_of_jobs
+
+class Job:
+	def __init__(self, jobSize=None):
+		self.jobSize = jobSize
+
+	def __str__(self):
+		return "Job(" + str(self.jobSize) + ")"
+
+class Generator(AtomicDEVS):
+	def __init__(self, name="Generator"):
+		AtomicDEVS.__init__(self, name)
+
+		self.state = GeneratorState(name="generating")
+		self.my_ports = {"p_out": self.addOutPort("p_out")}
+
+	def timeAdvance(self):
+		if self.state.name == "generating":
+			return 1
+
+	def outputFnc(self):
+		if self.state.name == "generating":
+			return {self.my_ports[k]: v for k, v in {'p_out': [Job(0.3)]}.iteritems()}
+
+	def intTransition(self):
+		def cond_int_generating_to_generating():
+			return True
+		def action_int_generating_to_generating():
+			return {}
+		if self.state.name == "generating" and cond_int_generating_to_generating():
+			return GeneratorState(name="generating", **action_int_generating_to_generating())
+
+		else:
+			return AtomicDEVS.intTransition(self)
+
+	def extTransition(self, my_inputs):
+		inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+		return AtomicDEVS.extTransition(self, my_inputs)
+
+	def confTransition(self, my_inputs):
+		inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+		return AtomicDEVS.confTransition(self, my_inputs)
+
+class Processor(AtomicDEVS):
+	def __init__(self, name="Processor"):
+		AtomicDEVS.__init__(self, name)
+
+		self.state = ProcessorState(name="idle")
+		self.my_ports = {"p_in": self.addInPort("p_in"), "p_out": self.addOutPort("p_out")}
+
+	def timeAdvance(self):
+		if self.state.name == "idle":
+			return INFINITY
+		if self.state.name == "processing":
+			return self.state.job.jobSize
+
+	def outputFnc(self):
+		if self.state.name == "idle":
+			return {}
+		if self.state.name == "processing":
+			return {self.my_ports[k]: v for k, v in {'p_out': [self.state.job]}.iteritems()}
+
+	def intTransition(self):
+		def cond_int_processing_to_idle():
+			return True
+		def action_int_processing_to_idle():
+			return {}
+		if self.state.name == "processing" and cond_int_processing_to_idle():
+			return ProcessorState(name="idle", **action_int_processing_to_idle())
+
+		else:
+			return AtomicDEVS.intTransition(self)
+
+	def extTransition(self, my_inputs):
+		inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+		def cond_ext_idle_to_processing():
+			return True
+		def action_ext_idle_to_processing():
+			return {"job": inputs['p_in'][0]}
+		if self.state.name == "idle" and cond_ext_idle_to_processing():
+			return ProcessorState(name="processing", **action_ext_idle_to_processing())
+
+		else:
+			return AtomicDEVS.extTransition(self, my_inputs)
+
+	def confTransition(self, my_inputs):
+		inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+		return AtomicDEVS.confTransition(self, my_inputs)
+
+class Collector(AtomicDEVS):
+	def __init__(self, name="Collector"):
+		AtomicDEVS.__init__(self, name)
+
+		self.state = CollectorState(name="waiting", nr_of_jobs=0)
+		self.my_ports = {"p_in": self.addInPort("p_in")}
+
+	def timeAdvance(self):
+		if self.state.name == "waiting":
+			return INFINITY
+
+	def outputFnc(self):
+		if self.state.name == "waiting":
+			return {}
+
+	def intTransition(self):
+		return AtomicDEVS.intTransition(self)
+
+	def extTransition(self, my_inputs):
+		inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+		def cond_ext_waiting_to_waiting():
+			return True
+		def action_ext_waiting_to_waiting():
+			return {"nr_of_jobs": self.state.nr_of_jobs + 1}
+		if self.state.name == "waiting" and cond_ext_waiting_to_waiting():
+			return CollectorState(name="waiting", **action_ext_waiting_to_waiting())
+
+		else:
+			return AtomicDEVS.extTransition(self, my_inputs)
+
+	def confTransition(self, my_inputs):
+		inputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}
+		return AtomicDEVS.confTransition(self, my_inputs)
+
+class CoupledProcessor(CoupledDEVS):
+	def __init__(self, name="CoupledProcessor"):
+		CoupledDEVS.__init__(self, name)
+		self.my_ports = {"p_in": self.addInPort("p_in"), "p_out": self.addOutPort("p_out")}
+		self.submodels = {}
+		self.submodels["p1"] = self.addSubModel(Processor(name="p1"))
+		self.submodels["p2"] = self.addSubModel(Processor(name="p2"))
+
+		self.connectPorts(self.my_ports["p_in"], self.submodels["p1"].my_ports["p_in"])
+		self.connectPorts(self.submodels["p1"].my_ports["p_out"], self.submodels["p2"].my_ports["p_in"])
+		self.connectPorts(self.submodels["p2"].my_ports["p_out"], self.my_ports["p_out"])
+
+class Root(CoupledDEVS):
+	def __init__(self, name="Root"):
+		CoupledDEVS.__init__(self, name)
+		self.my_ports = {}
+		self.submodels = {}
+		self.submodels["g"] = self.addSubModel(Generator(name="g"))
+		self.submodels["cp"] = self.addSubModel(CoupledProcessor(name="cp"))
+		self.submodels["p"] = self.addSubModel(Processor(name="p"))
+		self.submodels["c"] = self.addSubModel(Collector(name="c"))
+
+		self.connectPorts(self.submodels["g"].my_ports["p_out"], self.submodels["cp"].my_ports["p_in"])
+		self.connectPorts(self.submodels["cp"].my_ports["p_out"], self.submodels["p"].my_ports["p_in"])
+		self.connectPorts(self.submodels["p"].my_ports["p_out"], self.submodels["c"].my_ports["p_in"])
+

+ 498 - 0
debugging_environment/examples_sccd_sim/particle_interaction/model.py

@@ -0,0 +1,498 @@
+from DEVS import *
+from infinity import INFINITY
+
+import random, math, sys, getopt
+
+class Canvas:
+    def __init__(self, resolution):
+        self.width = resolution[0]
+        self.height = resolution[1]
+        
+class ParticleState:
+    def __init__(self, canvas):
+        self.r = random.uniform(5.0, 30.0)
+        x = random.uniform(self.r, canvas.width - self.r)
+        y = random.uniform(self.r, canvas.height - self.r)
+        self.pos = (x, y)
+        self.vel = {'x': 50 + (random.random() * 25.0), 'y': 50 + (random.random() * 25.0)}
+        self.phase = "initializing" # phases: ('initializing', 'initialized', 'bouncing', 'spawning', 'selected', 'deleting', 'clicked')
+        self.color = "red"
+        self.prev_color = "red"
+        self.collision_detected = False
+        self.clicked = False
+        self.frames_passed = 0
+        self.frames_remaining = 0
+        self.remaining = 0
+
+class Particle(AtomicDEVS):
+    def __init__(self, particle_id, canvas, framerate, spawn_chance, die_chance):
+        AtomicDEVS.__init__(self, "Particle[%i]" % particle_id)
+        
+        self.particle_id = particle_id
+        self.canvas = canvas
+        self.framerate = framerate
+        self.spawn_chance = spawn_chance
+        self.die_chance = die_chance
+        
+        self.COLLISION_DETECT = self.addInPort("COLLISION_DETECT")
+        self.POS_OUT = self.addOutPort("POS_OUT")
+        self.SPAWNER_COMM = self.addOutPort("SPAWNER_COMM")
+        self.COLOR_OUT = self.addOutPort("COLOR_OUT")
+        
+        self.state = ParticleState(canvas)
+    
+    def timeAdvance(self):
+        return self.state.remaining
+    
+    def outputFnc(self):
+        output = {}
+        if self.state.phase in ("bouncing", "spawning", "selected") or self.state.clicked:
+            output[self.POS_OUT] = (self.particle_id, self.state.pos, self.state.r, self.state.vel)
+        if self.state.collision_detected and self.state.phase != "spawning" and random.random() < self.spawn_chance:
+            output[self.SPAWNER_COMM] = "spawn_particle"
+        if self.state.phase == "selected" and self.state.prev_color == self.state.color:
+            output[self.POS_OUT] = ("delete", self.particle_id)
+        if self.state.color != self.state.prev_color:
+            output[self.COLOR_OUT] = (self.particle_id, self.state.color)
+        if self.state.phase == "initializing":
+            output[self.POS_OUT] = ("created", self.particle_id, self.state.pos, self.state.r, self.state.vel)
+        return output
+    
+    def intTransition(self):
+        if self.state.phase == "initializing":
+            self.state.phase = "initialized"
+            self.state.remaining = 0
+        elif self.state.phase == "initialized":
+            self.state.phase = "bouncing"
+            self.state.remaining = 1
+        elif self.state.phase == "selected":
+            if self.state.prev_color == self.state.color:
+                self.state.phase = "deleting"
+                self.state.remaining = INFINITY
+            else:
+                self.state.prev_color = self.state.color
+                self.state.remaining = int(2.5 * self.framerate)
+        elif self.state.prev_color != self.state.color:
+            self.state.prev_color = self.state.color
+            self.state.remaining = 0
+        elif self.state.phase == "clicked":
+            self.state.remaining = INFINITY
+        elif random.random() < self.die_chance:
+            self.state.vel = {'x': 0, 'y': 0}
+            self.state.color = "yellow"
+            self.state.phase = "selected"
+            self.state.remaining = 0
+        else:
+            if self.state.frames_passed < self.framerate and self.state.phase in ("bouncing", "spawning") and self.state.color != "black":
+                self.state.frames_passed += 1
+            if self.state.frames_passed >= self.framerate and self.state.phase == "bouncing":
+                self.state.color = "black"
+                self.state.phase = "bouncing"
+                self.state.frames_passed = 0
+            if self.state.frames_passed >= 1 * self.framerate and self.state.phase == "spawning":
+                self.state.color = "black"
+                self.state.phase = "bouncing"
+                self.state.frames_passed = 0
+            x = self.state.pos[0]
+            y = self.state.pos[1]
+            if (x - self.state.r) <= 0 or x + self.state.r >= self.canvas.width:
+                self.state.vel['x'] = -self.state.vel['x']
+            if (y - self.state.r) <= 0 or y + self.state.r >= self.canvas.height:
+                self.state.vel['y'] = -self.state.vel['y']
+            self.state.pos = (self.state.pos[0] + (self.state.vel['x'] / self.framerate), self.state.pos[1] + (self.state.vel['y'] / self.framerate))
+            if self.state.collision_detected:
+                self.state.phase = "spawning"
+                self.state.color = "blue"
+            elif self.state.clicked:
+                self.state.vel = {'x': 0, 'y': 0}
+                self.state.phase = "clicked"
+                self.state.color = "orange"
+                self.state.clicked = False
+            self.state.remaining = 1
+        self.state.collision_detected = False
+        return self.state
+    
+    def extTransition(self, inputs):
+        if self.COLLISION_DETECT in inputs:
+            if inputs[self.COLLISION_DETECT] == "delete_if_selected":
+                if self.state.phase == "clicked":
+                    self.state.phase = "selected"
+                    self.state.remaining = 0
+            elif inputs[self.COLLISION_DETECT] == "clicked":
+                if self.state.phase == "bouncing":
+                    self.state.clicked = True
+                    self.state.remaining = 0
+            elif self.state.phase in ("bouncing", "clicked", "deleting"):
+                self.state.phase = "bouncing"
+                self.state.collision_detected = True
+                new_speed = inputs[self.COLLISION_DETECT][1]
+                self.state.vel = {'x': new_speed[0], 'y': new_speed[1]}
+                self.state.remaining = 0
+            else:
+                self.state.remaining -= self.elapsed
+        return self.state
+    
+    def modelTransition(self, passed_values):
+        if self.state.phase == "deleting":
+            passed_values['to_delete'] = self
+            return True
+        elif self.state.phase == "initialized":
+            passed_values['connect_particle'] = (self.particle_id, self.COLLISION_DETECT)
+            return True
+        return False
+        
+class ParticleSpawnerState:
+    def __init__(self):        
+        self.id_ctr = 0
+        self.new_particle = None
+        self.remaining = 0
+
+class ParticleSpawner(AtomicDEVS):
+    def __init__(self, canvas, framerate, spawn_chance, die_chance):
+        AtomicDEVS.__init__(self, "ParticleSpawner")
+        
+        self.canvas = canvas
+        self.framerate = framerate
+        self.spawn_chance = spawn_chance
+        self.die_chance = die_chance
+        
+        self.REQUEST = self.addInPort("REQUEST")
+        
+        self.state = ParticleSpawnerState()
+    
+    def timeAdvance(self):
+        return self.state.remaining
+    
+    def intTransition(self):
+        self.state.new_particle = Particle(self.state.id_ctr, self.canvas, self.framerate, self.spawn_chance, self.die_chance)
+        self.state.id_ctr += 1
+        self.state.remaining = self.framerate
+        return self.state
+    
+    def extTransition(self, inputs):
+        self.state.remaining -= self.elapsed
+        if self.REQUEST in inputs:
+            self.state.new_particle = Particle(self.state.id_ctr, self.canvas, self.framerate, self.spawn_chance, self.die_chance)
+            self.state.id_ctr += 1
+        return self.state
+    
+    def modelTransition(self, passed_values):
+        if self.state.new_particle:
+            passed_values['new_particle'] = self.state.new_particle
+            return True
+        return False
+
+class PositionManagerState:
+    def __init__(self):        
+        self.positions = {}
+        self.collisions = set([])
+        self.phase = "detecting"
+        self.clicked = None
+        self.delete_selected = False
+        self.frames = 0
+        self.remaining = 0
+        # self.PARTICLES_OUT = {}
+    
+    def __str__(self):
+        return str((self.phase, self.frames, self.remaining, len(self.PARTICLES_OUT)))
+        
+    '''    
+    def __getstate__(self):
+        odict = self.__dict__.copy()
+        del odict['PARTICLES_OUT']
+        return odict
+        
+    def __setstate__(self, dict):
+        self.__dict__.update(dict)
+        self.PARTICLES_OUT = {port.host_DEVS.particle_id: port for port in self.OPorts if port.getName().startswith('PARTICLES_OUT')} 
+    '''
+
+class PositionManager(AtomicDEVS):
+    def __init__(self, framerate):
+        AtomicDEVS.__init__(self, "PositionManager")
+        
+        self.framerate = framerate
+        
+        self.TIME_OUT = self.addOutPort("TIME_OUT")
+        self.POS_IN = self.addInPort("POS_IN")
+        self.INTERRUPT = self.addInPort("INTERRUPT")
+        
+        self.state = PositionManagerState()
+    
+    def timeAdvance(self):
+        return self.state.remaining
+    
+    def outputFnc(self):
+        output = {}
+        if self.state.collisions:
+            #output = {self.state.PARTICLES_OUT[particle_id]: ("collision_detected", deltap) for (particle_id, deltap) in self.state.collisions}
+            output = {self.ports['PARTICLES_OUT[%i]' % particle_id]: ("collision_detected", deltap) for (particle_id, deltap) in self.state.collisions}
+        if self.state.clicked is not None:
+            #if self.state.clicked in self.state.PARTICLES_OUT:
+                #output[self.state.PARTICLES_OUT[self.state.clicked]] = "clicked"
+            portname = 'PARTICLES_OUT[%i]' % particle_id
+            if portname in self.ports:
+                output[self.ports[portname]] = "clicked"
+        if self.state.delete_selected:
+            #output = {self.state.PARTICLES_OUT[particle_id]: "delete_if_selected" for particle_id in self.state.positions}
+            output = {self.ports['PARTICLES_OUT[%i]']: "delete_if_selected" for particle_id in self.state.positions}
+        output[self.TIME_OUT] = self.state.frames
+        return output
+    
+    def intTransition(self):
+        self.state.frames += self.timeAdvance()
+        if self.state.clicked is not None:
+            self.state.clicked = None
+            self.state.remaining = 1
+        elif self.state.delete_selected:
+            self.state.delete_selected = False
+            self.state.remaining = 1
+        elif self.state.phase == "detecting":
+            for k1, v1 in self.state.positions.iteritems():
+                for k2, v2 in self.state.positions.iteritems():
+                    if k1 != k2:
+                        dx = v2[0][0] - v1[0][0]
+                        dy = v2[0][1] - v1[0][1]
+                        distance = math.sqrt(dx**2 + dy**2)
+                        if (distance < (v1[1] + v2[1])) and (k1 not in self.state.collisions or k2 not in self.state.collisions):
+                            '''
+                            u = [dx / distance, dy / distance]
+                            vab = {'x': v2[2]['x'] - v1[2]['x'], 'y': v2[2]['y'] - v1[2]['y']}
+                            vu_mult = vab['x'] * u[0] + vab['y'] * u[1]
+                            vu = [u[0] * vu_mult, u[1] * vu_mult]
+                            deltap_mult = 1
+                            deltap = (vu[0] * deltap_mult, vu[1] * deltap_mult)
+                            self.state.collisions.add((k1, deltap))
+                            self.state.collisions.add((k2, (-deltap[0], -deltap[1])))
+                            '''
+                            new_speed_1 = (v2[2]['x'], v2[2]['y'])
+                            new_speed_2 = (v1[2]['x'], v1[2]['y'])
+                            self.state.collisions.add((k1, new_speed_1))
+                            self.state.collisions.add((k2, new_speed_2))
+            self.state.phase = "detected"
+            self.state.remaining = 0
+        elif self.state.phase == "detected":
+            self.state.collisions = set([])
+            self.state.phase = "detecting"
+            self.state.remaining = 1
+        return self.state
+    
+    def extTransition(self, inputs):
+        self.state.remaining -= self.elapsed
+        self.state.frames += self.elapsed
+        if self.POS_IN in inputs:
+            msg = inputs[self.POS_IN]
+            if msg[0] == "created":
+                new_particle_id = msg[1]
+                #self.state.PARTICLES_OUT[new_particle_id] = self.addOutPort("PARTICLES_OUT[%s]" % new_particle_id)
+                self.addOutPort("PARTICLES_OUT[%s]" % new_particle_id)
+                self.state.positions[new_particle_id] = (msg[2], msg[3], msg[4])
+            elif msg[0] == "delete":
+                #del self.state.PARTICLES_OUT[msg[1]]
+                del self.state.positions[msg[1]]
+            else:
+                particle_id = msg[0]
+                r = msg[2]
+                self.state.positions[particle_id] = (msg[1], msg[2], msg[3])
+        # TODO: Fix this, needs to be rounded to integer.
+        elif self.INTERRUPT in inputs:
+            msg = inputs[self.INTERRUPT][0]
+            if msg == "delete_selected":
+                self.state.delete_selected = True
+            else:
+                self.state.clicked = int(msg)
+        return self.state
+
+class Root(CoupledDEVS):
+    def __init__(self, canvas=Canvas((800, 600)), framerate=30.0, spawn_chance=0.2, die_chance=0.01):
+        CoupledDEVS.__init__(self, "Field")
+        
+        self.INTERRUPT = self.addInPort("INTERRUPT")
+        self.POS_OUT = self.addOutPort("POS_OUT")
+        self.COLOR_OUT = self.addOutPort("COLOR_OUT")
+        self.TIME_OUT = self.addOutPort("TIME_OUT")
+        
+        self.particle_spawner = self.addSubModel(ParticleSpawner(canvas, framerate, spawn_chance, die_chance))
+        self.position_manager = self.addSubModel(PositionManager(framerate))
+        self.connectPorts(self.INTERRUPT, self.position_manager.INTERRUPT)
+        self.connectPorts(self.position_manager.TIME_OUT, self.TIME_OUT)
+            
+    def modelTransition(self, passed_values):
+        if 'new_particle' in passed_values:
+            new_particle = passed_values['new_particle']
+            self.addSubModel(new_particle)
+            self.connectPorts(new_particle.POS_OUT, self.position_manager.POS_IN)
+            self.connectPorts(new_particle.POS_OUT, self.POS_OUT)
+            self.connectPorts(new_particle.COLOR_OUT, self.COLOR_OUT)
+            self.connectPorts(new_particle.SPAWNER_COMM, self.particle_spawner.REQUEST)
+            del passed_values['new_particle']
+        if 'to_delete' in passed_values:
+            self.removeSubModel(passed_values['to_delete'])
+            del passed_values['to_delete']
+        if 'connect_particle' in passed_values:
+            particle_id, COLLISION_DETECT = passed_values['connect_particle']
+            #self.connectPorts(self.position_manager.state.PARTICLES_OUT[particle_id], COLLISION_DETECT)
+            self.connectPorts(self.position_manager.ports['PARTICLES_OUT[%s]' % particle_id], COLLISION_DETECT)
+            del passed_values['connect_particle']
+        return False
+        
+    def select(self, imm_children):
+        pos_mgr, particle_spawner = [None] * 2
+        for c in imm_children:
+            if c.getModelName() == "PositionManager":
+                pos_mgr = c
+            elif c.getModelName() == "ParticleSpawner":
+                particle_spawner = c
+        if particle_spawner:
+            return particle_spawner
+        elif pos_mgr:
+            return imm_children[0] #pos_mgr
+        else:
+            return imm_children[0]
+
+'''
+class ParticleVisualization:
+    def __init__(self, particle_id, circle_id, middle_id, canvas, sim):
+        self.particle_id = particle_id
+        self.circle_id = circle_id
+        self.middle_id = middle_id
+        self.canvas = canvas
+        self.sim = sim
+        
+        self.canvas.tag_bind(self.circle_id, "<Button-1>", self.on_click)
+        self.canvas.tag_bind(self.middle_id, "<Button-1>", self.on_click)
+    
+    def on_click(self, event):
+        self.sim.realtime_interrupt("INTERRUPT %i" % self.particle_id)
+
+# TODO: Model this in SCCD
+class Visualizer(tk.Toplevel):
+    def __init__(self, root, resolution, framerate, sim):
+        tk.Toplevel.__init__(self)
+        
+        self.framerate = int((1.0 / framerate) * 1000)
+        self.sim = sim
+        self.root = root
+        
+        self.geometry('{}x{}'.format(resolution[0], resolution[1]))                
+        CANVAS_SIZE_TUPLE = (0, 0, self.winfo_screenwidth(), self.winfo_screenheight())
+        self.canvas = tk.Canvas(self, relief=tk.RIDGE, scrollregion=CANVAS_SIZE_TUPLE)
+        self.canvas.pack(expand = True, fill=tk.BOTH)
+        self.text = self.canvas.create_text(5, 5, anchor='nw', text="TIME: %s" % 0.0)  
+        self.particles = {}
+        
+        self.protocol("WM_DELETE_WINDOW", lambda: self.root.destroy())
+        self.bind("<Delete>", self.delete_pressed)
+        
+        self.after(self.framerate, self.check_output)
+    
+    def delete_pressed(self, event):
+        self.sim.realtime_interrupt("INTERRUPT delete_selected")
+    
+    def check_output(self):
+        while True:
+            try:
+                msg = self.sim.model.out_msg_queue.get(False)
+                self.canvas.itemconfig(self.text, text=msg[0][0])
+                port = msg[1]
+                if port == self.sim.model.POS_OUT:
+                    msg_contents = msg[2][0]
+                    if msg_contents[0] == "delete":
+                        particle_id = msg_contents[1]
+                        self.canvas.delete(self.particles[particle_id].circle_id)
+                        self.canvas.delete(self.particles[particle_id].middle_id)
+                        del self.particles[particle_id]
+                    elif msg_contents[0] == "created":
+                        pass
+                    else:
+                        particle_id = msg_contents[0]
+                        x = msg_contents[1][0]
+                        y = msg_contents[1][1]
+                        r = msg_contents[2]
+                        if not particle_id in self.particles:
+                            circle_id = self.canvas.create_oval(x - r, y - r, x + r, y + r, fill="red")
+                            middle_id = self.canvas.create_oval(x - 4, y - 4, x + 4, y + 4, fill="orange")
+                            self.particles[particle_id] = ParticleVisualization(particle_id, circle_id, middle_id, self.canvas, self.sim)
+                        else:
+                            circle_id = self.particles[particle_id].circle_id
+                            middle_id = self.particles[particle_id].middle_id
+                            curr_pos = self.canvas.coords(circle_id)
+                            self.canvas.move(circle_id, x - r - curr_pos[0], y - r - curr_pos[1])
+                            curr_pos_middle = self.canvas.coords(middle_id)
+                            self.canvas.move(middle_id, x - 4 - curr_pos_middle[0], y - 4 - curr_pos_middle[1])
+                elif port == self.sim.model.COLOR_OUT:
+                    msg_contents = msg[2][0]
+                    particle_id = msg_contents[0]
+                    circle_id = self.particles[particle_id].circle_id
+                    middle_id = self.particles[particle_id].middle_id
+                    color = msg_contents[1]
+                    self.canvas.itemconfig(circle_id, fill=color)
+            except Empty:
+                break
+        self.after(self.framerate, self.check_output)
+
+if __name__ == '__main__':
+    root = tk.Tk()
+    root.withdraw()
+
+    try:
+        opts, args = getopt.getopt(sys.argv[1:], "w:h:f:s:d:r:m", ["width=", "height=", "framerate=", "spawn_chance=", "die_chance=", "random_seed=", "main_loop"])
+    except getopt.GetoptError, e:
+        print e
+        sys.exit(2)
+    width, height, framerate, spawn_chance, die_chance, random_seed, ml = [None] * 7
+    for opt, arg in opts:
+        if opt in ("--width", "-w"):
+            width = int(arg)
+        elif opt in ("--height", "-h"):
+            height = int(arg)
+        elif opt in ("--framerate", "-f"):
+            framerate = int(arg)
+        elif opt in ("--spawn_chance", "-s"):
+            spawn_chance = float(arg)
+        elif opt in ("--die_chance", "-d"):
+            die_chance = float(arg)
+        elif opt in ("--random_seed", "-r"):
+            random_seed = int(arg)
+        elif opt in ("--main_loop", "-m"):
+            ml = True
+    resolution = (width or 800, height or 600)
+    framerate = framerate or 60
+    spawn_chance = 0.2 if spawn_chance is None else spawn_chance
+    die_chance = 0.01 if die_chance is None else die_chance
+    
+    if random_seed:
+        random.seed(random_seed)
+    
+    model = Field(Canvas(resolution), framerate, spawn_chance, die_chance)
+    
+    sim = Simulator(model)
+    sim.setRealTime(True)
+    sim.setRealTimeInputFile(None)
+    sim.setRealTimePorts({'INTERRUPT': model.INTERRUPT})
+    sim.setRealTimePlatformTk(root)
+    sim.setDSDEVS(True)
+    sim.setClassicDEVS(True)
+    sim.setTerminationTime(60)
+    
+    visualizer = Visualizer(root, resolution, framerate, sim)      
+    visualizer.title('ParticleInteraction %s' % ml)
+    
+    import cProfile
+    pr = cProfile.Profile()
+    pr.enable()
+    
+    sim.simulate()
+    if ml:
+        root.mainloop()
+    else:
+        while True:
+            try:
+                root.update_idletasks()
+                root.update()
+            except:
+                break
+    
+    pr.disable()
+    pr.print_stats(sort='tottime')
+'''

+ 51 - 0
debugging_environment/examples_sccd_sim/simple_dsdevs/model.py

@@ -0,0 +1,51 @@
+from DEVS import *
+from infinity import INFINITY
+
+class MyAtomicDSModel(AtomicDEVS):
+    def __init__(self, my_id):
+        AtomicDEVS.__init__(self, "MyAtomicDSModel[%s]" % my_id)
+        self.my_id = my_id
+        self.ctr = 0
+        self.remaining = 1
+        self.out_port = self.addOutPort("out_port")
+        self.in_port = self.addInPort("in_port")
+    
+    def set_sim(self, sim):
+        self.sim = sim
+
+    def timeAdvance(self):
+        return self.remaining
+    
+    def outputFnc(self):
+        print 'MyAtomicDSModel(%s) outputFnc' % id(self)
+        return {self.out_port: "MyMessage"}
+        
+    def intTransition(self):
+        self.ctr += 1
+        self.remaining = 1
+        print 'MyAtomicDSModel(%s:%s) intTransition' % (id(self), self.ctr)
+        
+    def extTransition(self, inputs):
+        self.remaining -= self.elapsed
+        print 'MyAtomicDSModel(%s) extTransition' % id(self)
+        self.ctr += 1
+    
+    def modelTransition(self, state):
+        print 'MyAtomicDSModel(%s) modelTransition %s' % (id(self), self.ctr)
+        if self.ctr % 2 == 0:
+            state[self.my_id] = "present"
+            return True
+        else:
+            return False
+
+class Root(CoupledDEVS):
+    def __init__(self):
+        CoupledDEVS.__init__(self, "CoupledDEVS")
+        
+        self.amodel = self.addSubModel(MyAtomicDSModel(0))
+        self.bmodel = self.addSubModel(MyAtomicDSModel(1))
+        self.connectPorts(self.amodel.out_port, self.bmodel.in_port)
+        self.connectPorts(self.bmodel.out_port, self.amodel.in_port)
+        
+    def modelTransition(self, state):
+        print 'MyDSModel modelTransition %s' % state

+ 104 - 0
debugging_environment/examples_sccd_sim/trace.txt

@@ -0,0 +1,104 @@
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 60.0
+  NEW STATE <green>
+  OUTPUTFNC returned {}
+  time_next: 110.0 (ta: 50.0)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 110.0
+  NEW STATE <yellow>
+  OUTPUTFNC returned {}
+  time_next: 120.0 (ta: 10.0)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 120.0
+  NEW STATE <red>
+  OUTPUTFNC returned {}
+  time_next: 180.0 (ta: 60.0)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 180.0
+  NEW STATE <green>
+  OUTPUTFNC returned {}
+  time_next: 230.0 (ta: 50.0)
+EXTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 200
+  NEW STATE <manual>
+  inputs were {}
+  time_next: inf (ta: inf)
+INTERNAL TRANSITION in <MyTrafficSystem.policeman> @ 200
+  NEW STATE <working>
+  OUTPUTFNC returned {}
+  time_next: 300 (ta: 100)
+EXTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 300
+  NEW STATE <red>
+  inputs were {}
+  time_next: 360 (ta: 60)
+INTERNAL TRANSITION in <MyTrafficSystem.policeman> @ 300
+  NEW STATE <idle>
+  OUTPUTFNC returned {}
+  time_next: 500 (ta: 200)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 360
+  NEW STATE <green>
+  OUTPUTFNC returned {}
+  time_next: 410 (ta: 50)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 410
+  NEW STATE <yellow>
+  OUTPUTFNC returned {}
+  time_next: 420 (ta: 10)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 420
+  NEW STATE <red>
+  OUTPUTFNC returned {}
+  time_next: 480 (ta: 60)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 480
+  NEW STATE <green>
+  OUTPUTFNC returned {}
+  time_next: 530 (ta: 50)
+EXTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 500
+  NEW STATE <manual>
+  inputs were {}
+  time_next: inf (ta: inf)
+INTERNAL TRANSITION in <MyTrafficSystem.policeman> @ 500
+  NEW STATE <working>
+  OUTPUTFNC returned {}
+  time_next: 600 (ta: 100)
+EXTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 600
+  NEW STATE <red>
+  inputs were {}
+  time_next: 660 (ta: 60)
+INTERNAL TRANSITION in <MyTrafficSystem.policeman> @ 600
+  NEW STATE <idle>
+  OUTPUTFNC returned {}
+  time_next: 800 (ta: 200)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 660
+  NEW STATE <green>
+  OUTPUTFNC returned {}
+  time_next: 710 (ta: 50)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 710
+  NEW STATE <yellow>
+  OUTPUTFNC returned {}
+  time_next: 720 (ta: 10)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 720
+  NEW STATE <red>
+  OUTPUTFNC returned {}
+  time_next: 780 (ta: 60)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 780
+  NEW STATE <green>
+  OUTPUTFNC returned {}
+  time_next: 830 (ta: 50)
+EXTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 800
+  NEW STATE <manual>
+  inputs were {}
+  time_next: inf (ta: inf)
+INTERNAL TRANSITION in <MyTrafficSystem.policeman> @ 800
+  NEW STATE <working>
+  OUTPUTFNC returned {}
+  time_next: 900 (ta: 100)
+EXTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 900
+  NEW STATE <red>
+  inputs were {}
+  time_next: 960 (ta: 60)
+INTERNAL TRANSITION in <MyTrafficSystem.policeman> @ 900
+  NEW STATE <idle>
+  OUTPUTFNC returned {}
+  time_next: 1100 (ta: 200)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 960
+  NEW STATE <green>
+  OUTPUTFNC returned {}
+  time_next: 1010 (ta: 50)
+INTERNAL TRANSITION in <MyTrafficSystem.trafficLight> @ 1010
+  NEW STATE <yellow>
+  OUTPUTFNC returned {}
+  time_next: 1020 (ta: 10)

+ 75 - 0
debugging_environment/examples_sccd_sim/trafficlight_classic/experiment.py

@@ -0,0 +1,75 @@
+# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at 
+# McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
+# 
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Import code for model simulation:
+from pypdevs.simulator import Simulator
+
+# Import the model to be simulated
+from model import TrafficSystem
+
+#    ======================================================================
+
+# 1. Instantiate the (Coupled or Atomic) DEVS at the root of the 
+#  hierarchical model. This effectively instantiates the whole model 
+#  thanks to the recursion in the DEVS model constructors (__init__).
+#
+trafficSystem = TrafficSystem(name="trafficSystem")
+
+#    ======================================================================
+
+# 2. Link the model to a DEVS Simulator: 
+#  i.e., create an instance of the 'Simulator' class,
+#  using the model as a parameter.
+sim = Simulator(trafficSystem)
+
+#    ======================================================================
+
+# 3. Perform all necessary configurations, the most commonly used are:
+
+# A. Termination time (or termination condition)
+#    Using a termination condition will execute a provided function at
+#    every simulation step, making it possible to check for certain states
+#    being reached.
+#    It should return True to stop simulation, or Falso to continue.
+def terminate_whenStateIsReached(clock, model):
+    return model.trafficLight.state.get() == "manual"
+sim.setTerminationCondition(terminate_whenStateIsReached)
+
+#    A termination time is prefered over a termination condition,
+#    as it is much simpler to use.
+#    e.g. to simulate until simulation time 400.0 is reached
+sim.setTerminationTime(400.0)
+
+# B. Set the use of a tracer to show what happened during the simulation run
+#    Both writing to stdout or file is possible:
+#    pass None for stdout, or a filename for writing to that file
+sim.setVerbose(None)
+
+# C. Use Classic DEVS instead of Parallel DEVS
+#    If your model uses Classic DEVS, this configuration MUST be set as
+#    otherwise errors are guaranteed to happen.
+#    Without this option, events will be remapped and the select function
+#    will never be called.
+sim.setClassicDEVS()
+
+#    ======================================================================
+
+# 4. Simulate the model
+sim.simulate()
+
+#    ======================================================================
+
+# 5. (optional) Extract data from the simulated model
+print("Simulation terminated with traffic light in state %s" % (trafficSystem.trafficLight.state.get()))

+ 296 - 0
debugging_environment/examples_sccd_sim/trafficlight_classic/model.py

@@ -0,0 +1,296 @@
+# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at 
+# McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
+# 
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import sys
+
+# Import code for DEVS model representation:
+from DEVS import *
+from infinity import INFINITY
+
+class TrafficLightMode:
+    """
+    Encapsulates the system's state
+    """
+
+    def __init__(self, current="red"):
+        """
+        Constructor (parameterizable).
+        """
+        self.set(current)
+
+    def set(self, value="red"):
+        self.colour=value
+
+    def get(self):
+        return self.colour
+
+    def __str__(self):
+        return self.get()
+
+class TrafficLight(AtomicDEVS):
+    """
+    A traffic light 
+    """
+  
+    def __init__(self, name=None):
+        """
+        Constructor (parameterizable).
+        """
+        # Always call parent class' constructor FIRST:
+        AtomicDEVS.__init__(self, name)
+    
+        # STATE:
+        #  Define 'state' attribute (initial sate):
+        self.state = TrafficLightMode("red") 
+
+        # ELAPSED TIME:
+        #  Initialize 'elapsed time' attribute if required
+        #  (by default, value is 0.0):
+        self.elapsed = 1.5 
+        # with elapsed time initially 1.5 and initially in 
+        # state "red", which has a time advance of 60,
+        # there are 60-1.5 = 58.5time-units  remaining until the first 
+        # internal transition 
+    
+        # PORTS:
+        #  Declare as many input and output ports as desired
+        #  (usually store returned references in local variables):
+        self.INTERRUPT = self.addInPort(name="INTERRUPT")
+        self.OBSERVED = self.addOutPort(name="OBSERVED")
+
+    def extTransition(self, inputs):
+        """
+        External Transition Function.
+        """
+        # Compute the new state 'Snew' based (typically) on current
+        # State, Elapsed time parameters and calls to 'self.peek(self.IN)'.
+        input = inputs.get(self.INTERRUPT)
+
+        state = self.state.get()
+
+        if input == "toManual":
+            if state == "manual":
+                # staying in manual mode
+                return TrafficLightMode("manual")
+            elif state in ("red", "green", "yellow"):
+                return TrafficLightMode("manual")
+        elif input == "toAutonomous":
+            if state == "manual":
+                return TrafficLightMode("red")
+            elif state in ("red", "green", "yellow"):
+                # If toAutonomous is given while still autonomous, just stay in this state
+                return self.state
+        raise DEVSException(\
+            "unknown state <%s> in TrafficLight external transition function"\
+            % state) 
+
+    def intTransition(self):
+        """
+        Internal Transition Function.
+        """
+
+        state = self.state.get()
+
+        if state == "red":
+            return TrafficLightMode("green")
+        elif state == "green":
+            return TrafficLightMode("yellow")
+        elif state == "yellow":
+            return TrafficLightMode("red")
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in TrafficLight internal transition function"\
+                % state)
+  
+    def outputFnc(self):
+        """
+        Output Funtion.
+        """
+   
+        # A colourblind observer sees "grey" instead of "red" or "green".
+ 
+        # BEWARE: ouput is based on the OLD state
+        # and is produced BEFORE making the transition.
+        # We'll encode an "observation" of the state the
+        # system will transition to !
+
+        # Send messages (events) to a subset of the atomic-DEVS' 
+        # output ports by means of the 'poke' method, i.e.:
+        # The content of the messages is based (typically) on current State.
+ 
+        state = self.state.get()
+
+        if state == "red":
+            return {self.OBSERVED: "grey"}
+        elif state == "green":
+            return {self.OBSERVED: "yellow"}
+        elif state == "yellow":
+            return {self.OBSERVED: "grey"}
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in TrafficLight external transition function"\
+                % state)
+    
+    def timeAdvance(self):
+        """
+        Time-Advance Function.
+        """
+        # Compute 'ta', the time to the next scheduled internal transition,
+        # based (typically) on current State.
+        state = self.state.get()
+        if state == "red":
+            return 60 
+        elif state == "green":
+            return 50 
+        elif state == "yellow":
+            return 10 
+        elif state == "manual":
+            return INFINITY 
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in TrafficLight time advance transition function"\
+                % state)
+
+class PolicemanMode:
+    """
+    Encapsulates the Policeman's state
+    """
+    def __init__(self, current="idle"):
+        """
+        Constructor (parameterizable).
+        """
+        self.set(current)
+
+    def set(self, value="idle"):
+        self.__mode=value
+
+    def get(self):
+        return self.__mode
+
+    def __str__(self):
+        return self.get()
+
+class Policeman(AtomicDEVS):
+    """
+    A policeman producing "toManual" and "toAutonomous" events:
+    "toManual" when going from "idle" to "working" mode
+    "toAutonomous" when going from "working" to "idle" mode
+    """
+    def __init__(self, name=None):
+        """
+        Constructor (parameterizable).
+        """
+    
+        # Always call parent class' constructor FIRST:
+        AtomicDEVS.__init__(self, name)
+    
+        # STATE:
+        #  Define 'state' attribute (initial sate):
+        self.state = PolicemanMode("idle") 
+
+        # ELAPSED TIME:
+        #  Initialize 'elapsed time' attribute if required
+        #  (by default, value is 0.0):
+        self.elapsed = 0 
+    
+        # PORTS:
+        #  Declare as many input and output ports as desired
+        #  (usually store returned references in local variables):
+        self.OUT = self.addOutPort(name="OUT")
+
+    def intTransition(self):
+        """
+        Internal Transition Function.
+        The policeman works forever, so only one mode. 
+        """
+  
+        state = self.state.get()
+
+        if state == "idle":
+            return PolicemanMode("working")
+        elif state == "working":
+            return PolicemanMode("idle")
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in Policeman internal transition function"\
+                % state)
+    
+    def outputFnc(self):
+        """
+        Output Funtion.
+        """
+        # Send messages (events) to a subset of the atomic-DEVS' 
+        # output ports by means of the 'poke' method, i.e.:
+        # The content of the messages is based (typically) on current State.
+        state = self.state.get()
+        if state == "idle":
+            return {self.OUT: "toManual"}
+        elif state == "working":
+            return {self.OUT: "toAutonomous"}
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in Policeman output function"\
+                % state)
+    
+    def timeAdvance(self):
+        """
+        Time-Advance Function.
+        """
+        # Compute 'ta', the time to the next scheduled internal transition,
+        # based (typically) on current State.
+    
+        state = self.state.get()
+
+        if state == "idle":
+            return 200 
+        elif state == "working":
+            return 100 
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in Policeman time advance function"\
+                % state)
+
+class Root(CoupledDEVS):
+    def __init__(self, name="TrafficSystem"):
+        """
+        A simple traffic system consisting of a Policeman and a TrafficLight.
+        """
+        # Always call parent class' constructor FIRST:
+        CoupledDEVS.__init__(self, name)
+
+        # Declare the coupled model's output ports:
+        # Autonomous, so no output ports
+
+        # Declare the coupled model's sub-models:
+
+        # The Policeman generating interrupts 
+        self.policeman = self.addSubModel(Policeman(name="policeman"))
+
+        # The TrafficLight 
+        self.trafficLight = self.addSubModel(TrafficLight(name="trafficLight"))
+
+        # Only connect ...
+        self.connectPorts(self.policeman.OUT, self.trafficLight.INTERRUPT)
+
+    def select(self, immChildren):
+        """
+        Choose a model to transition from all possible models.
+        """
+        # Policeman has priority over the traffic light
+        if self.policeman in immChildren:
+            return self.policeman
+        else:
+            # Doesn't really matter, as they don't influence each other
+            return immChildren[0]

+ 277 - 0
debugging_environment/examples_sccd_sim/trafficlight_parallel/model.py

@@ -0,0 +1,277 @@
+# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at 
+# McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
+# 
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import sys
+
+# Import code for DEVS model representation:
+from DEVS import *
+from infinity import INFINITY
+
+class TrafficLightMode:
+    """
+    Encapsulates the system's state
+    """
+
+    def __init__(self, current="red"):
+        """
+        Constructor (parameterizable).
+        """
+        self.set(current)
+
+    def set(self, value="red"):
+        self.colour=value
+
+    def get(self):
+        return self.colour
+
+    def __str__(self):
+        return self.get()
+
+class TrafficLight(AtomicDEVS):
+    """
+    A traffic light 
+    """
+  
+    def __init__(self, name=None):
+        """
+        Constructor (parameterizable).
+        """
+        # Always call parent class' constructor FIRST:
+        AtomicDEVS.__init__(self, name)
+    
+        # STATE:
+        #  Define 'state' attribute (initial sate):
+        self.state = TrafficLightMode("red") 
+        
+        # PORTS:
+        #  Declare as many input and output ports as desired
+        #  (usually store returned references in local variables):
+        self.INTERRUPT = self.addInPort(name="INTERRUPT")
+        self.OBSERVED = self.addOutPort(name="OBSERVED")
+
+    def extTransition(self, inputs):
+        """
+        External Transition Function.
+        """
+        # Compute the new state 'Snew' based (typically) on current
+        # State, Elapsed time parameters and calls to 'self.peek(self.IN)'.
+        input = inputs.get(self.INTERRUPT)[0]
+
+        state = self.state.get()
+
+        if input == "toManual":
+            if state == "manual":
+                # staying in manual mode
+                return TrafficLightMode("manual")
+            elif state in ("red", "green", "yellow"):
+                return TrafficLightMode("manual")
+        elif input == "toAutonomous":
+            if state == "manual":
+                return TrafficLightMode("red")
+            elif state in ("red", "green", "yellow"):
+                # If toAutonomous is given while still autonomous, just stay in this state
+                return self.state
+        raise DEVSException(\
+            "unknown state <%s> in TrafficLight external transition function"\
+            % state) 
+
+    def intTransition(self):
+        """
+        Internal Transition Function.
+        """
+
+        state = self.state.get()
+
+        if state == "red":
+            return TrafficLightMode("green")
+        elif state == "green":
+            return TrafficLightMode("yellow")
+        elif state == "yellow":
+            return TrafficLightMode("red")
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in TrafficLight internal transition function"\
+                % state)
+  
+    def outputFnc(self):
+        """
+        Output Funtion.
+        """
+   
+        # A colourblind observer sees "grey" instead of "red" or "green".
+ 
+        # BEWARE: ouput is based on the OLD state
+        # and is produced BEFORE making the transition.
+        # We'll encode an "observation" of the state the
+        # system will transition to !
+
+        # Send messages (events) to a subset of the atomic-DEVS' 
+        # output ports by means of the 'poke' method, i.e.:
+        # The content of the messages is based (typically) on current State.
+ 
+        state = self.state.get()
+
+        if state == "red":
+            return {self.OBSERVED: ["grey"]}
+        elif state == "green":
+            return {self.OBSERVED: ["yellow"]}
+        elif state == "yellow":
+            return {self.OBSERVED: ["grey"]}
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in TrafficLight external transition function"\
+                % state)
+    
+    def timeAdvance(self):
+        """
+        Time-Advance Function.
+        """
+        # Compute 'ta', the time to the next scheduled internal transition,
+        # based (typically) on current State.
+        state = self.state.get()
+        if state == "red":
+            return 60 
+        elif state == "green":
+            return 50 
+        elif state == "yellow":
+            return 10 
+        elif state == "manual":
+            return INFINITY 
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in TrafficLight time advance transition function"\
+                % state)
+
+class PolicemanMode:
+    """
+    Encapsulates the Policeman's state
+    """
+    def __init__(self, current="idle"):
+        """
+        Constructor (parameterizable).
+        """
+        self.set(current)
+
+    def set(self, value="idle"):
+        self.__mode=value
+
+    def get(self):
+        return self.__mode
+
+    def __str__(self):
+        return self.get()
+
+class Policeman(AtomicDEVS):
+    """
+    A policeman producing "toManual" and "toAutonomous" events:
+    "toManual" when going from "idle" to "working" mode
+    "toAutonomous" when going from "working" to "idle" mode
+    """
+    def __init__(self, name=None):
+        """
+        Constructor (parameterizable).
+        """
+    
+        # Always call parent class' constructor FIRST:
+        AtomicDEVS.__init__(self, name)
+    
+        # STATE:
+        #  Define 'state' attribute (initial sate):
+        self.state = PolicemanMode("idle") 
+
+        # ELAPSED TIME:
+        #  Initialize 'elapsed time' attribute if required
+        #  (by default, value is 0.0):
+        self.elapsed = 0 
+    
+        # PORTS:
+        #  Declare as many input and output ports as desired
+        #  (usually store returned references in local variables):
+        self.OUT = self.addOutPort(name="OUT")
+
+    def intTransition(self):
+        """
+        Internal Transition Function.
+        The policeman works forever, so only one mode. 
+        """
+  
+        state = self.state.get()
+
+        if state == "idle":
+            return PolicemanMode("working")
+        elif state == "working":
+            return PolicemanMode("idle")
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in Policeman internal transition function"\
+                % state)
+    
+    def outputFnc(self):
+        """
+        Output Funtion.
+        """
+        # Send messages (events) to a subset of the atomic-DEVS' 
+        # output ports by means of the 'poke' method, i.e.:
+        # The content of the messages is based (typically) on current State.
+        state = self.state.get()
+        if state == "idle":
+            return {self.OUT: ["toManual"]}
+        elif state == "working":
+            return {self.OUT: ["toAutonomous"]}
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in Policeman output function"\
+                % state)
+    
+    def timeAdvance(self):
+        """
+        Time-Advance Function.
+        """
+        # Compute 'ta', the time to the next scheduled internal transition,
+        # based (typically) on current State.
+    
+        state = self.state.get()
+
+        if state == "idle":
+            return 200 
+        elif state == "working":
+            return 100 
+        else:
+            raise DEVSException(\
+                "unknown state <%s> in Policeman time advance function"\
+                % state)
+
+class Root(CoupledDEVS):
+    def __init__(self, name="TrafficLight"):
+        """
+        A simple traffic system consisting of a Policeman and a TrafficLight.
+        """
+        # Always call parent class' constructor FIRST:
+        CoupledDEVS.__init__(self, name)
+
+        # Declare the coupled model's output ports:
+        # Autonomous, so no output ports
+
+        # Declare the coupled model's sub-models:
+
+        # The Policeman generating interrupts 
+        self.policeman = self.addSubModel(Policeman(name="policeman"))
+
+        # The TrafficLight 
+        self.trafficLight = self.addSubModel(TrafficLight(name="trafficLight"))
+
+        # Only connect ...
+        self.connectPorts(self.policeman.OUT, self.trafficLight.INTERRUPT)
+

BIN
debugging_environment/img/bigstep.png


BIN
debugging_environment/img/breakpoint.png


BIN
debugging_environment/img/delete-bp.png


BIN
debugging_environment/img/pause.png


BIN
debugging_environment/img/reset.png


BIN
debugging_environment/img/rubbish-bin.png


BIN
debugging_environment/img/simulate.png


+ 87 - 0
debugging_environment/img/simulate.svg

@@ -0,0 +1,87 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
+
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   version="1.1"
+   id="Capa_1"
+   x="0px"
+   y="0px"
+   width="300"
+   height="300"
+   viewBox="0 0 300 300.00001"
+   xml:space="preserve"
+   inkscape:version="0.91 r13725"
+   sodipodi:docname="simulate.svg"
+   inkscape:export-filename="D:\Documents\Unief\14-17.PhD\16.01.InternshipAutodesk\Projects\ds_debugger\debugging_environment\img\simulate.png"
+   inkscape:export-xdpi="4.8000002"
+   inkscape:export-ydpi="4.8000002"><metadata
+     id="metadata42"><rdf:RDF><cc:Work
+         rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
+     id="defs40" /><sodipodi:namedview
+     pagecolor="#ffffff"
+     bordercolor="#666666"
+     borderopacity="1"
+     objecttolerance="10"
+     gridtolerance="10"
+     guidetolerance="10"
+     inkscape:pageopacity="0"
+     inkscape:pageshadow="2"
+     inkscape:window-width="1920"
+     inkscape:window-height="1018"
+     id="namedview38"
+     showgrid="false"
+     inkscape:zoom="0.63269421"
+     inkscape:cx="-196.46504"
+     inkscape:cy="272.83865"
+     inkscape:window-x="-8"
+     inkscape:window-y="-8"
+     inkscape:window-maximized="1"
+     inkscape:current-layer="Capa_1"
+     fit-margin-top="0"
+     fit-margin-left="0"
+     fit-margin-right="0"
+     fit-margin-bottom="0" /><g
+     id="g3"
+     transform="matrix(0.65354021,0,0,1,-34.073626,-73.00775)"><g
+       id="Layer_8_16_"><path
+         d="m 62.915316,75.089208 c 3.325593,-1.386566 7.047489,-2.081458 10.774967,-2.081458 3.717431,0 7.43821,0.694892 10.778316,2.081458 L 341.35757,209.56363 c 6.65677,2.77072 10.77943,7.90037 10.77943,13.44663 0,5.54546 -4.1115,10.67431 -10.77943,13.44182 L 84.468599,370.93212 c -6.666815,2.76751 -14.885351,2.76751 -21.547701,0 C 56.252966,368.15497 52.137,363.02371 52.137,357.48146 l 0,-268.947223 c 0,-5.543048 4.109268,-10.671896 10.778316,-13.445029 z"
+         id="path6"
+         inkscape:connector-curvature="0" /></g></g><g
+     id="g8"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g10"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g12"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g14"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g16"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g18"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g20"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g22"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g24"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g26"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g28"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g30"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g32"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g34"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g36"
+     transform="translate(-52.137,-73.00775)" /></svg>

BIN
debugging_environment/img/simulatert.png


+ 99 - 0
debugging_environment/img/simulatert.svg

@@ -0,0 +1,99 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
+
+<svg
+   xmlns:dc="http://purl.org/dc/elements/1.1/"
+   xmlns:cc="http://creativecommons.org/ns#"
+   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
+   xmlns:svg="http://www.w3.org/2000/svg"
+   xmlns="http://www.w3.org/2000/svg"
+   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
+   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
+   version="1.1"
+   id="Capa_1"
+   x="0px"
+   y="0px"
+   width="300"
+   height="300"
+   viewBox="0 0 300 300.00001"
+   xml:space="preserve"
+   inkscape:version="0.91 r13725"
+   sodipodi:docname="simulatert.svg"
+   inkscape:export-filename="D:\Documents\Unief\14-17.PhD\16.01.InternshipAutodesk\Projects\ds_debugger\debugging_environment\img\simulatert.png"
+   inkscape:export-xdpi="4.8000002"
+   inkscape:export-ydpi="4.8000002"><metadata
+     id="metadata42"><rdf:RDF><cc:Work
+         rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
+           rdf:resource="http://purl.org/dc/dcmitype/StillImage" /><dc:title></dc:title></cc:Work></rdf:RDF></metadata><defs
+     id="defs40" /><sodipodi:namedview
+     pagecolor="#ffffff"
+     bordercolor="#666666"
+     borderopacity="1"
+     objecttolerance="10"
+     gridtolerance="10"
+     guidetolerance="10"
+     inkscape:pageopacity="0"
+     inkscape:pageshadow="2"
+     inkscape:window-width="1920"
+     inkscape:window-height="1018"
+     id="namedview38"
+     showgrid="false"
+     inkscape:zoom="0.63269421"
+     inkscape:cx="39.826041"
+     inkscape:cy="272.83865"
+     inkscape:window-x="-8"
+     inkscape:window-y="-8"
+     inkscape:window-maximized="1"
+     inkscape:current-layer="Capa_1"
+     fit-margin-top="0"
+     fit-margin-left="0"
+     fit-margin-right="0"
+     fit-margin-bottom="0" /><g
+     id="g3"
+     transform="matrix(0.65354021,0,0,1,-34.073626,-73.00775)"><g
+       id="Layer_8_16_"><path
+         d="m 62.915316,75.089208 c 3.325593,-1.386566 7.047489,-2.081458 10.774967,-2.081458 3.717431,0 7.43821,0.694892 10.778316,2.081458 L 341.35757,209.56363 c 6.65677,2.77072 10.77943,7.90037 10.77943,13.44663 0,5.54546 -4.1115,10.67431 -10.77943,13.44182 L 84.468599,370.93212 c -6.666815,2.76751 -14.885351,2.76751 -21.547701,0 C 56.252966,368.15497 52.137,363.02371 52.137,357.48146 l 0,-268.947223 c 0,-5.543048 4.109268,-10.671896 10.778316,-13.445029 z"
+         id="path6"
+         inkscape:connector-curvature="0" /></g></g><g
+     id="g8"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g10"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g12"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g14"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g16"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g18"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g20"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g22"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g24"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g26"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g28"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g30"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g32"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g34"
+     transform="translate(-52.137,-73.00775)" /><g
+     id="g36"
+     transform="translate(-52.137,-73.00775)" /><text
+     xml:space="preserve"
+     style="font-style:normal;font-weight:normal;font-size:22.5px;line-height:125%;font-family:sans-serif;letter-spacing:0px;word-spacing:0px;fill:#000000;fill-opacity:1;stroke:none;stroke-width:1px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:1"
+     x="139.92216"
+     y="294.10809"
+     id="text4170"
+     sodipodi:linespacing="125%"><tspan
+       sodipodi:role="line"
+       id="tspan4172"
+       x="139.92216"
+       y="294.10809"
+       style="font-weight:bold;font-size:106.25px">RT</tspan></text>
+</svg>

BIN
debugging_environment/img/smallstep.png


File diff suppressed because it is too large
+ 4 - 0
debugging_environment/javascript_runtime/libs/d3.v2.min.js


File diff suppressed because it is too large
+ 4 - 0
debugging_environment/javascript_runtime/libs/jquery.min.js


+ 132 - 0
debugging_environment/javascript_runtime/libs/old/svg.js

@@ -0,0 +1,132 @@
+/**
+ * Small framework for dynamically creating/deleting shapes on an SVG canvas and responding to events.
+ *
+ * Author: Joeri Exelmans
+ * Date: 2014/07/26
+ */
+
+svg = {};
+
+svg.__ui_element_wrapper = function(element) {
+	this.element = element;
+};
+
+svg.canvas_wrapper = function(element) {
+	svg.__ui_element_wrapper.call(this, element);
+
+	this.namespace = "http://www.w3.org/2000/svg";
+	this.width = parseInt(element.getAttribute('width'));
+	this.height = parseInt(element.getAttribute('height'));
+};
+
+svg.canvas_wrapper.prototype = new svg.__ui_element_wrapper();
+
+svg.canvas_wrapper.prototype.add_circle = function(x,y,r,style) {
+	var new_element = document.createElementNS(this.namespace, "circle");
+	new_element.setAttribute('r', r);
+	new_element.setAttribute('stroke', '#000');
+	for( var key in style )
+		new_element.setAttribute(key, style[key]);
+	this.element.appendChild(new_element);
+	var wrapper = new svg.element_wrapper(this, new_element, x, y);
+	return wrapper;
+};
+
+svg.canvas_wrapper.prototype.add_rectangle = function(x,y,w,h,style) {
+	var new_element = document.createElementNS(this.namespace, "rect");
+	new_element.setAttribute('width', w);
+	new_element.setAttribute('height', h);
+	for( var key in style )
+		new_element.setAttribute(key, style[key]);
+	this.element.appendChild(new_element);
+	var wrapper = new svg.element_wrapper(this, new_element, x, y);
+	var transl = this.element.createSVGTransform();
+	transl.setTranslate(-w/2.0, -h/2.0);
+	new_element.transform.baseVal.appendItem(transl);
+	return wrapper;
+};
+
+svg.canvas_wrapper.prototype.add_text = function(x,y,textContent,style) {
+    var new_element = document.createElementNS(this.namespace, "text");
+    var textnode = document.createTextNode(textContent);
+	new_element.setAttribute('x', x);
+	new_element.setAttribute('y', y);
+	for( var key in style )
+		new_element.setAttribute(key, style[key]);
+	this.element.appendChild(new_element);
+	new_element.appendChild(textnode);
+	var wrapper = new svg.element_wrapper(this, new_element, x, y);
+    wrapper.textnode = textnode
+	return wrapper;
+}
+
+svg.canvas_wrapper.prototype.remove_element = function(element) {
+	this.element.removeChild(element.element);
+};
+
+svg.element_wrapper = function(canvas_wrapper, element, x, y) {
+	svg.__ui_element_wrapper.call(this, element);
+	this.a = 0.0;
+
+	this.translation = canvas_wrapper.element.createSVGTransform();
+	this.rotation = canvas_wrapper.element.createSVGTransform();
+
+	this.translation.setTranslate(x,y);
+	this.rotation.setRotate(this.a, 0.0, 0.0);
+
+	/** WORKAROUND Chrome Issue 55010 (1of3) **/	
+	if( window && window.chrome && window.chrome.webstore )
+		this.__translation = {x:x, y:y};
+
+	var t = this.element.transform.baseVal;
+	t.appendItem(this.translation);
+	t.appendItem(this.rotation);
+};
+
+svg.element_wrapper.prototype = new svg.__ui_element_wrapper();
+
+svg.element_wrapper.prototype.set_position = function(x, y) {
+	/** WORKAROUND Chrome Issue 55010 (2of3) **/
+	if( window && window.chrome && window.chrome.webstore )
+	{
+		this.__translation.x = x;
+		this.__translation.y = y;
+		this.element.setAttribute('transform','translate('+this.__translation.x+' '+this.__translation.y+')');
+	}
+	else
+		this.translation.setTranslate(x,y);
+};
+
+svg.element_wrapper.prototype.get_position = function() {
+	/** WORKAROUND Chrome Issue 55010 (3of3) **/
+	if( window && window.chrome && window.chrome.webstore )
+		return {x:this.__translation.x, y:this.__translation.y};
+	else
+		return {x: this.translation.matrix.e, y: this.translation.matrix.f};
+};
+
+svg.element_wrapper.prototype.move = function(dx, dy) {
+	var pos = this.get_position();
+	this.set_position(pos.x + dx, pos.y + dy);
+};
+
+svg.element_wrapper.prototype.set_rotation = function(a) {
+	this.a = a;
+	this.rotation.setRotate(this.a, 0.0, 0.0);
+};
+
+svg.element_wrapper.prototype.rotate = function(a) {
+	this.a += a;
+	this.rotation.setRotate(this.a, 0.0, 0.0);
+};
+
+svg.element_wrapper.prototype.set_color = function(color) {
+	this.element.setAttribute('fill', color);
+};
+
+svg.element_wrapper.prototype.set_text = function(textContent) {
+	this.element.removeChild(this.textnode)
+    textnode = document.createTextNode(textContent);
+    this.element.appendChild(textnode)
+    this.textnode = textnode
+};

+ 126 - 0
debugging_environment/javascript_runtime/libs/old/ui.js

@@ -0,0 +1,126 @@
+/**
+ * *REALLY* Small framework for creating/manipulating/deleting gui elements in a browser.
+ *
+ *	TODO / TBI
+ * . finer append_*() layout control (as opposed to current append at the end of the window)
+ * . finer print control (as opposed to current append at the end of main window)
+ *	. replicate ui.EVENTS for style properties
+ *	. complete this list
+ *
+ * Author: Raphael Mannadiar
+ * Date: 2014/08/14
+ */
+
+['svg'].forEach(
+	function(dependency) {if( this[dependency] === undefined ) throw 'Missing dependency: ' + dependency;});
+
+ui = {};
+ui.window = window;
+ui.__nextWindowId = 0;
+
+ui.EVENTS = {
+	KEY_PRESS:				'keydown',
+	MOUSE_CLICK: 			'click',
+	MOUSE_MOVE: 			'mousemove',
+	MOUSE_PRESS:			'mousedown',
+	MOUSE_RELEASE:			'mouseup',
+	MOUSE_RIGHT_CLICK: 	    'contextmenu',
+	WINDOW_CLOSE: 			'unload'
+};
+
+ui.MOUSE_BUTTONS = {
+	LEFT:	 	0,
+	MIDDLE:	    1,
+	RIGHT:	    2
+};
+
+ui.KEYCODES	= {
+	DELETE: 46
+};
+
+ui.append_button = function(_window,text) {
+	var button = _window.document.createElement('button');
+	button.innerHTML = text;
+	_window.document.body.appendChild(button);
+	return ui.wrap_element(button);
+};
+
+ui.append_canvas = function(_window,width,height,style) {
+	var canvas = _window.document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+	canvas.setAttribute('width', width);
+	canvas.setAttribute('height', height);
+	for( var key in style )
+		canvas.style[key] = style[key];
+	_window.document.body.appendChild(canvas);
+	return new svg.canvas_wrapper(canvas);
+};
+
+ui.bind_event = function(source,event,target,raise_name,port,time_offset) {
+	if( port === undefined) port = "ui";
+	if( time_offset === undefined ) time_offset = 0.0;
+
+	var args = [];
+	switch(event) {
+		case ui.EVENTS.KEY_PRESS:
+			args = function(e) {return [e.keyCode, e.view]};
+			source = source.document;
+			break;
+
+		case ui.EVENTS.MOUSE_CLICK:
+		case ui.EVENTS.MOUSE_MOVE: 
+		case ui.EVENTS.MOUSE_PRESS:
+		case ui.EVENTS.MOUSE_RELEASE:
+		case ui.EVENTS.MOUSE_RIGHT_CLICK:
+			args = function(e) {return [e.clientX, e.clientY, e.button]};
+			if( source instanceof svg.element_wrapper )
+				source = source.element;
+			break;
+
+		case ui.EVENTS.WINDOW_CLOSE:
+			args = function() {return [source]};
+			break;
+
+		default:
+			throw 'Unsupported event';
+	}
+
+	source.addEventListener(
+		event, 
+		(function (target, raise_name, port, time_offset) {
+ 			 return function(e) {
+ 						 e.preventDefault();
+			 			 e.stopPropagation();
+			 			 target.addInput(new Event(raise_name, port, args(e)), time_offset);};}
+		)(target, raise_name, port, time_offset));
+};
+
+ui.close_window = function(_window) {
+	_window.close();
+};
+
+ui.log = function(value) {
+	if( typeof(value) == 'object' )
+		console.log(JSON.stringify(value));
+	else
+		console.log(value);
+};
+
+ui.new_window = function(width,height) {
+	return window.open('',ui.__nextWindowId++,'width='+width+',height='+height);
+};
+
+ui.println = function(value,target) {
+	if( target === undefined ) target = window.document.body;
+
+	if( typeof(value) == 'object' )
+		target.innerHTML += JSON.stringify(value);
+	else
+		target.innerHTML += value;
+	target.innerHTML += '<br/>'
+};
+
+ui.wrap_element = function(element) {
+	return {element:element};
+};
+
+

+ 14 - 0
debugging_environment/javascript_runtime/libs/old/utils.js

@@ -0,0 +1,14 @@
+/**
+ * *REALLY* Small set of browser-compatible utility functions 
+ *
+ * Author: Raphael Mannadiar
+ * Date: 2014/08/14
+ */
+
+utils = {};
+
+utils.random = function() {
+	return Math.random();
+};
+
+

+ 58 - 0
debugging_environment/javascript_runtime/libs/ui.js

@@ -0,0 +1,58 @@
+ui = {};
+ui.window = window;
+ui.html_elements = {};
+
+ui.__ui_element_wrapper = function(element) {
+	this.element = element;
+};
+
+ui.element_wrapper = function(element) {
+	ui.__ui_element_wrapper(element);
+    this.event_handlers = {};
+};
+
+ui.element_wrapper_html = function(parent_tb, button_id, the_default) {
+    this.parent_tb = parent_tb;
+	this.button_id = button_id;
+    this.value = the_default;
+};
+ui.element_wrapper_html.prototype.get_value = function() {
+    console.log(this.parent_tb.element.items)
+}
+
+ui.create_toolbar = function(name, tb_parent) {
+    tb_parent = typeof tb_parent !== 'undefined' ? a : $(document.body);
+    return new function(name, tb_parent) {
+        var div_parent = $('<div id="' + name + '" style="display: inline-block; margin: 5px; padding: 4px; border: 1px solid silver; border-radius: 3px"></div>').appendTo(tb_parent);
+        this.element = div_parent.w2toolbar({
+            event_handlers: {},
+            name: name,
+            items: [],
+            onClick: function(event) {
+                if (event.target in this.event_handlers) {
+                    this.event_handlers[event.target][0].addInput(new Event("mouse_press", this.event_handlers[event.target][1], []), 0);
+                }
+            }
+        });
+        // what a terribly ugly hack
+        $('#tb_' + name + '_right').hide();
+    }(name, tb_parent);
+}
+
+ui.create_button = function(button_id, caption, img, parent_tb, controller, port) {
+    var btn = parent_tb.element.add({ type: 'button', id: button_id, img: img, caption: caption });
+    parent_tb.element.event_handlers[button_id] = [controller, port];
+    return new ui.element_wrapper(btn);
+}
+
+ui.create_tb_element = function(button_id, html, the_default, parent_tb, controller, port) {
+    var btn = parent_tb.element.add({ type: 'html', id: button_id, html: html });
+    parent_tb.element.event_handlers[button_id] = [controller, port];
+    var wrapper = new ui.element_wrapper_html(parent_tb, button_id, the_default);
+    ui.html_elements[button_id] = wrapper;
+    return wrapper;
+}
+
+ui.parameter_changed = function(button_id) {
+    ui.html_elements[button_id].value = $('#' + button_id + '_input')[0].value;
+}

File diff suppressed because it is too large
+ 2 - 0
debugging_environment/javascript_runtime/libs/w2ui-1.4.3.min.css


File diff suppressed because it is too large
+ 11 - 0
debugging_environment/javascript_runtime/libs/w2ui-1.4.3.min.js


+ 719 - 0
debugging_environment/javascript_runtime/statecharts_core.js

@@ -0,0 +1,719 @@
+// Exception
+function RuntimeException(msg) {
+	this.msg = msg;
+}
+
+// InputException
+function InputException(msg) {
+	RuntimeException.call(this, msg);
+}
+
+InputException.prototype = new RuntimeException();
+
+// AssociationException
+function AssociationException(msg) {
+	RuntimeException.call(this, msg);
+}
+
+AssociationException.prototype = new RuntimeException();
+
+// AssociationReferenceException
+function AssociationReferenceException(msg) {
+	RuntimeException.call(this, msg);
+}
+
+AssociationReferenceException.prototype = new RuntimeException();
+
+// ParameterException
+function ParameterException(msg) {
+	RuntimeException.call(this, msg);
+}
+
+ParameterException.prototype = new RuntimeException();
+
+// InputException
+function InputException(msg) {
+	RuntimeException.call(this, msg);
+}
+
+InputException.prototype = new RuntimeException();
+
+// EventQueueEntry
+function EventQueueEntry(event, time_offset) {
+	this.event = event;
+	this.time_offset = time_offset;
+}
+
+EventQueueEntry.prototype.decreaseTime = function(offset) {
+	this.time_offset -= offset;
+};
+
+// EventQueue
+function EventQueue() {
+	this.event_list = new Array();
+}
+
+EventQueue.prototype.add = function(event, time_offset) {
+	var entry = new EventQueueEntry(event, time_offset);
+	var insert_index = 0;
+	var index = this.event_list.length - 1;
+	while (index >= 0) {
+		if (this.event_list[index].time_offset <= time_offset) {
+			insert_index = index + 1;
+			break;
+		}
+		index -= 1;
+	}
+	this.event_list.splice(insert_index, 0, entry);
+};
+
+EventQueue.prototype.decreaseTime = function(offset) {
+	for (var event in this.event_list) {
+		if (!this.event_list.hasOwnProperty(event)) continue;
+		this.event_list[event].decreaseTime(offset);
+	}
+};
+
+EventQueue.prototype.isEmpty = function() {
+	return this.event_list.length === 0;
+};
+
+EventQueue.prototype.getEarliestTime = function() {
+	if (this.isEmpty()) {
+		return Infinity;
+	} else {
+		return this.event_list[0].time_offset;
+	}
+};
+
+EventQueue.prototype.popDueEvents = function() {
+	if (this.isEmpty() || this.event_list[0].time_offset > 0.0) {
+		return new Array();
+	}
+	var index = 0;
+	while (index < this.event_list.length &&
+			this.event_list[index].time_offset <= 0.0)
+	{
+		index++;
+	}
+	return this.event_list.splice(0, index);
+};
+
+// Association
+function Association(to_class, min_card, max_card) {
+	this.to_class = to_class;
+	this.min_card = min_card;
+	this.max_card = max_card;
+	this.instances = new Object(); /* maps index (as string) to instance */
+	this.size = 0;
+	this.next_id = 0;
+}
+
+Association.prototype.allowedToAdd = function() {
+	return (this.max_card === -1 || this.size < this.max_card);
+};
+
+Association.prototype.addInstance = function(instance) {
+	if (this.allowedToAdd()) {
+		var id = this.next_id++;
+		this.instances[id] = instance;
+		return id;
+	} else {
+		throw new AssociationException("Not allowed to add the instance to the association.");
+	}
+};
+
+Association.prototype.getInstance = function(index) {
+	var instance = this.instances[index];
+	if (instance === undefined) {
+		throw new AssociationException("Invalid index for fetching instance(s) from association.");
+	}
+	return instance;
+};
+
+// ObjectManagerBase
+function ObjectManagerBase(controller) {
+	this.controller = controller;
+	this.events = new EventQueue();
+	this.instances = new Array();
+}
+
+ObjectManagerBase.prototype.addEvent = function(event, time_offset) {
+	if (!time_offset) time_offset = 0.0;
+	this.events.add(event, time_offset);
+};
+
+ObjectManagerBase.prototype.broadcast = function(new_event) {
+	for (var i in this.instances) {
+		if (!this.instances.hasOwnProperty(i)) continue;
+		this.instances[i].addEvent(new_event);
+	}
+};
+
+ObjectManagerBase.prototype.getWaitTime = function() {
+	var smallest_time = this.events.getEarliestTime();
+	for (var i in this.instances) {
+		if (!this.instances.hasOwnProperty(i)) continue;
+		smallest_time = Math.min(smallest_time, this.instances[i].getEarliestEventTime());
+	}
+	return smallest_time;
+};
+
+ObjectManagerBase.prototype.stepAll = function(delta) {
+	this.step(delta);
+	for (var i in this.instances) {
+		if (!this.instances.hasOwnProperty(i)) continue;
+		this.instances[i].step(delta);
+	}
+};
+
+ObjectManagerBase.prototype.step = function(delta) {
+	this.events.decreaseTime(delta);
+	var due = this.events.popDueEvents();
+	for (var e in due) {
+		this.handleEvent(due[e].event);
+	}
+};
+
+ObjectManagerBase.prototype.start = function() {
+	for (var i in this.instances) {
+		if (!this.instances.hasOwnProperty(i)) continue;
+		this.instances[i].start();
+	}
+};
+
+ObjectManagerBase.prototype.handleEvent = function(e) {
+	if (e.name === "narrow_cast") {
+		this.handleNarrowCastEvent(e.parameters);
+	} else if (e.name === "broad_cast") {
+		this.handleBroadcastEvent(e.parameters);
+	} else if (e.name === "create_instance") {
+		this.handleCreateEvent(e.parameters);
+	} else if (e.name === "associate_instance") {
+		this.handleAssociateEvent(e.parameters);
+	} else if (e.name === "start_instance") {
+		this.handleStartInstanceEvent(e.parameters);
+	} else if (e.name === "delete_instance") {
+		this.handleDeleteInstanceEvent(e.parameters);
+	}
+};
+
+ObjectManagerBase.prototype.processAssociationReference = function(input_string) {
+	//if (input_string === "") {
+		//throw new AssociationReferenceException("Empty association reference.");
+	//}
+	var regex = /^([a-zA-Z_]\w*)(?:\[(\d+)\])?$/;
+	var path_string = input_string.split('/');
+	var result = new Array();
+	if (input_string !== "") {
+		for (var p in path_string) {
+			if (!path_string.hasOwnProperty(p)) continue;
+			var m = regex.exec(path_string[p]);
+			if (m) {
+				var name = m[1];
+				var index = m[2];
+				if (!index) {
+					index = -1;
+				}
+				result.push({name:name,index:index});
+			} else {
+				throw new AssociationReferenceException("Invalid entry in association reference.");
+			}
+		}
+	}
+	return result;
+};
+
+ObjectManagerBase.prototype.handleStartInstanceEvent = function(parameters) {
+	if (parameters.length !== 2) {
+		throw new ParameterException("The start instance event needs 2 parameters.");
+	}
+	var source = parameters[0];
+	var traversal_list = this.processAssociationReference(parameters[1]);
+	var instances = this.getInstances(source, traversal_list);
+	for (var i in instances) {
+		if (!instances.hasOwnProperty(i)) continue;
+		instances[i].instance.start();
+	}
+};
+
+ObjectManagerBase.prototype.handleDeleteInstanceEvent = function(parameters) {
+	if (parameters.length !== 2) {
+		throw new ParameterException("The delete instance event needs 2 parameters.");
+	}
+	var source = parameters[0];
+	var traversal_list = this.processAssociationReference(parameters[1]);
+	var instances = this.getInstances(source, traversal_list);
+	for (var i in instances) {
+		if (!instances.hasOwnProperty(i)) continue;
+		instances[i].instance.stop();
+		if (instances[i].instance.destructor)
+			instances[i].instance.destructor();
+		// delete association from source instance
+		var association_to_remove = instances[i].ref.associations[instances[i].assoc_name];
+		if (instances[i].assoc_index === -1) {
+			/*for (var x in association_to_remove.instances) {
+				if (!association_to_remove.instances.hasOwnProperty(x)) continue;
+				association_to_remove.instances = new Object();
+				//association_to_remove.instances[x] = null;
+			}*/
+			// empty instances object
+			association_to_remove.instances = new Object();
+			//association_to_remove.instances = new Array();
+		} else {
+			//association_to_remove.instances[instances[i].assoc_index] = null;
+			// remove property from instances object
+			delete association_to_remove.instances[instances[i].assoc_index];
+		}
+		// also remove instance from OM's list of instances
+		index = this.instances.indexOf(instances[i].instance);
+		this.instances.splice(index,1);
+        
+        source.addEvent(new Event("instance_deleted", undefined, [parameters[1]]));
+	}
+};
+
+ObjectManagerBase.prototype.handleBroadcastEvent = function(parameters) {
+	if (parameters.length !== 1) {
+		throw new ParameterException("The broadcast event needs 1 parameter.");
+	}
+	this.broadcast(parameters[0]);
+};
+
+ObjectManagerBase.prototype.handleCreateEvent = function(parameters) {
+	if (parameters.length < 2) {
+		throw new ParameterException("The create event needs at least 2 parameters.");
+	}
+	var source = parameters[0];
+	var association_name = parameters[1];
+	var association = source.associations[association_name];
+	if (!association) {
+		throw new ParameterException("No such association: " + association_name);
+	}
+	if (association.allowedToAdd()) {
+		// allow subclasses to be instantiated
+		if (parameters.length === 2) {
+			var class_name = association.to_class;
+			var creation_parameters = [];
+		} else /* 3 or more parameters*/ {
+			// 3rd parameter is class name
+			var class_name = parameters[2];
+			// parameters after 3rd parameter are creation parameters
+			var creation_parameters = parameters.slice(3);
+		}
+		var new_instance = this.createInstance(class_name, creation_parameters);
+		if (new_instance === undefined) {
+			throw new ParameterException("Creating instance: no such class: " + class_name);
+		}
+		var index = association.addInstance(new_instance);
+		// add parent association to created instance
+		// if a parent association is defined in the class diagram
+		var parent_association = new_instance.associations["parent"];
+		if (parent_association !== undefined) {
+			parent_association.addInstance(source);
+		}
+		// TODO: maybe change order of Event constructor parameters such that we don't have to
+		//       explicitly set the port to 'undefined'?
+		source.addEvent(new Event("instance_created", undefined, [association_name+"["+index+"]"]));
+	} else {
+		source.addEvent(new Event("instance_creation_error", undefined, [association_name]));
+	}
+};
+
+ObjectManagerBase.prototype.handleAssociateEvent = function(parameters) {
+	if (parameters.length !== 3) {
+		throw new ParameterException("The associate_instance event needs 3 parameters.");
+	}
+	var source = parameters[0];
+	var source_list = parameters[1];
+	var traversal_list = this.processAssociationReference(source_list);
+	var to_copy_list = this.getInstances(source, traversal_list);
+	if (to_copy_list.length !== 1) {
+		throw new AssociationReferenceException("Invalid source association reference.");
+	}
+	var wrapped_to_copy_instance = to_copy_list[0].instance;
+	var dest_list = this.processAssociationReference(parameters[2]);
+	if (dest_list.length === 0) {
+		throw new AssociationReferenceException("Invalid destination association reference.");
+	}
+	var last = dest_list.pop();
+	if (last.index !== -1) {
+		throw new AssociationReferenceException("Last association name in association reference could not be accompanied by an index.");
+	}
+	var instances = this.getInstances(source, dest_list);
+	for (var i in instances) {
+		if (!instances.hasOwnProperty(i)) continue;
+		instances[i].instance.associations[last.name].addInstance(wrapped_to_copy_instance);
+	}
+};
+
+ObjectManagerBase.prototype.handleNarrowCastEvent = function(parameters) {
+	if (parameters.length !== 3) {
+		throw new ParameterException("The narrow_cast event needs 3 parameters.");
+	}
+	var source = parameters[0];
+	var traversal_list = this.processAssociationReference(parameters[1]);
+	var cast_event = parameters[2];
+	var instances = this.getInstances(source, traversal_list);
+	for (var i in instances) {
+		if (!instances.hasOwnProperty(i)) continue;
+		instances[i].instance.addEvent(cast_event);
+	}
+};
+
+ObjectManagerBase.prototype.getInstances = function(source, traversal_list) {
+	var currents = [{
+		instance : source,
+		ref : null,
+		assoc_name : null,
+		assoc_index : null
+	}];
+	for (var t in traversal_list) {
+		if (!traversal_list.hasOwnProperty(t)) continue;
+		var name = traversal_list[t].name;
+		var index = traversal_list[t].index;
+		nexts = new Array();
+		for (var c in currents) {
+			if (!currents.hasOwnProperty(c)) continue;
+			var association = currents[c].instance.associations[name];
+			if (index >= 0) {
+				nexts.push({
+					instance : association.getInstance(index),
+					ref : currents[c].instance,
+					assoc_name : name,
+					assoc_index : index
+				});
+			} else if (index === -1) {
+				for (var i in association.instances) {
+					if (!association.instances.hasOwnProperty(i)) continue;
+					nexts.push({
+						instance: association.instances[i],
+						ref: currents[c].instance,
+						assoc_name : name,
+						assoc_index : index
+					});
+				}
+				//nexts = nexts.concat(association.instances);
+			} else {
+				throw new AssociationReferenceException("Incorrect index in association reference.");
+			}
+		}
+		currents = nexts;
+	}
+	return currents;
+};
+
+ObjectManagerBase.prototype.instantiate = function(to_class, construct_params) {
+	// pure virtual
+};
+
+ObjectManagerBase.prototype.createInstance = function(to_class, construct_params) {
+	var instance = this.instantiate(to_class, construct_params);
+	this.instances.push(instance);
+	return instance;
+};
+
+// Event
+function Event(name, port, parameters) {
+	this.name = name;
+	this.port = port;
+	this.parameters = parameters;
+}
+
+// ControllerBase
+function ControllerBase(object_manager, keep_running, finished_callback) {
+	this.object_manager = object_manager;
+	this.keep_running = keep_running;
+	this.finished_callback = finished_callback;
+	this.input_ports = new Object(); /* maps port name to pair of (private name, instance) */
+	this.private_port_counter = 0;
+	this.input_queue = new EventQueue();
+	this.output_ports = new Array();
+	this.output_listeners = new Array();
+}
+
+ControllerBase.prototype.addInputPort = function(virtual_name, instance) {
+	if (instance === undefined) {
+		var port_name = virtual_name; // "public" port
+	} else {
+		var port_name = "private_" + (this.private_port_counter++) + /*"_" + instance.class_name +*/ "_" + virtual_name;
+	}
+	this.input_ports[port_name] = {
+		virtual_name: virtual_name,
+		instance: instance
+	};
+	return port_name;
+};
+
+ControllerBase.prototype.removeInputPort = function(name) {
+	delete this.input_ports[name];
+};
+
+ControllerBase.prototype.addOutputPort = function(port_name) {
+	this.output_ports.push(port_name);
+};
+
+ControllerBase.prototype.broadcast = function(new_event) {
+	this.object_manager.broadcast(new_event);
+};
+
+ControllerBase.prototype.start = function() {
+	this.object_manager.start();
+};
+
+ControllerBase.prototype.stop = function() {
+};
+
+ControllerBase.prototype.addInput = function(input_event, time_offset) {
+	if (input_event.name === "") {
+		throw new InputException("Input event can't have an empty name.");
+	}
+	var input_port = this.input_ports[input_event.port];
+	if (input_port === undefined) {
+		throw new InputException("Input port mismatch.");
+	}
+	this.input_queue.add(input_event, time_offset);
+};
+
+ControllerBase.prototype.outputEvent = function(event) {
+	for (var l in this.output_listeners) {
+		if (!this.output_listeners.hasOwnProperty(l)) continue;
+		this.output_listeners[l].add(event);
+	}
+};
+
+ControllerBase.prototype.addOutputListener = function(ports) {
+	var listener = new OutputListener(ports);
+	this.output_listeners.push(listener);
+	return listener;
+};
+
+ControllerBase.prototype.addMyOwnOutputListener = function(listener) {
+	this.output_listeners.push(listener);
+};
+
+ControllerBase.prototype.addEventList = function(event_list) {
+	for (var e in event_list) {
+		if (!event_list.hasOwnProperty(e)) continue;
+		var entry = event_list[e];
+		this.addInput(entry.event, entry.time_offset);
+	}
+};
+
+// GameLoopControllerBase
+function GameLoopControllerBase(object_manager, keep_running, finished_callback) {
+	ControllerBase.call(this, object_manager, keep_running, finished_callback);
+}
+
+GameLoopControllerBase.prototype = new ControllerBase();
+
+GameLoopControllerBase.prototype.update = function(delta) {
+	this.input_queue.decreaseTime(delta);
+	var due = this.input_queue.popDueEvents();
+	for (var e in due) {
+		if (!due.hasOwnProperty(e)) continue;
+		this.broadcast(due[e].event);
+	}
+	this.object_manager.stepAll(delta);
+};
+
+function TimeoutId(id, delay) {
+	this.id = id;
+	this.delay = delay;
+}
+
+// JsEventLoopControllerBase
+function JsEventLoopControllerBase(object_manager, keep_running, finished_callback) {
+	ControllerBase.call(this, object_manager, keep_running, finished_callback);
+	this.running = false;
+	this.next_timeout = null;
+	this.last_simulation_time = null;
+}
+
+JsEventLoopControllerBase.prototype = new ControllerBase();
+
+JsEventLoopControllerBase.prototype.handleInput = function(delta) {
+	this.input_queue.decreaseTime(delta);
+	var due = this.input_queue.popDueEvents();
+	for (var e in due) {
+		if (!due.hasOwnProperty(e)) continue;
+		var input_port = this.input_ports[due[e].event.port];
+		// rename input port
+		due[e].event.port = input_port.virtual_name;
+		var target_instance = input_port.instance;
+		if (target_instance === undefined) {
+			this.broadcast(due[e].event);
+		} else {
+			target_instance.addEvent(due[e].event);
+		}
+	}
+};
+
+JsEventLoopControllerBase.prototype.addInput = function(input_event, time_offset) {
+	if (this.last_simulation_time && this.next_timeout) {
+		var waited = (new Date).getTime() - this.last_simulation_time;
+		var remaining = this.next_timeout.delay - waited;
+	} else {
+		var waited = 0.0;
+		var remaining = 0.0;
+	}
+	var interleave = time_offset < remaining;
+	if (this.next_timeout) {
+		var additional_offset = waited;
+	} else {
+		var additional_offset = 0.0;
+	}
+	ControllerBase.prototype.addInput.call(this, input_event, time_offset + additional_offset);
+	if (this.running && (interleave || !this.next_timeout)) {
+		this.run(); // adjust timeout
+	}
+};
+
+JsEventLoopControllerBase.prototype.start = function() {
+	ControllerBase.prototype.start.call(this);
+	this.running = true;
+	this.run();
+};
+
+JsEventLoopControllerBase.prototype.stop = function() {
+	this.run(); // update timeouts
+	if (this.next_timeout) {
+		window.clearTimeout(this.next_timeout.id);
+	}
+	this.running = false;
+	ControllerBase.prototype.stop.call(this);
+};
+
+JsEventLoopControllerBase.prototype.getWaitTime = function() {
+	var wait_time = Math.min(this.object_manager.getWaitTime(), this.input_queue.getEarliestTime());
+	return wait_time;
+};
+
+JsEventLoopControllerBase.prototype.run = function() {
+		// clear previous timeout
+		if (this.next_timeout) {
+			window.clearTimeout(this.next_timeout.id);
+			this.next_timeout = null;
+		}
+		// calculate last time since simulation
+		if (this.last_simulation_time) {
+			var simulation_duration = (new Date).getTime() - this.last_simulation_time;
+		} else {
+			var simulation_duration = 0.0;
+		}
+		// simulate
+		this.handleInput(simulation_duration);
+		this.object_manager.stepAll(simulation_duration);
+		// keep time
+		this.last_simulation_time = (new Date).getTime();
+		// set next timeout
+		var wait_time = this.getWaitTime();
+		if (wait_time !== Infinity) {
+			var actual_wait_time = wait_time - ((new Date).getTime() - this.last_simulation_time);
+			if (actual_wait_time < 0.0)
+				actual_wait_time = 0.0;
+			// wait actual_wait_time
+			//console.log("waiting " + actual_wait_time + " ms");
+			this.next_timeout = new TimeoutId(window.setTimeout(this.run.bind(this), actual_wait_time), actual_wait_time);
+		} else {
+			// wait forever
+			//console.log("waiting forever");
+			this.last_simulation_time = null;
+			if (this.finished_callback) {
+				this.finished_callback();
+			}
+		}
+};
+
+// OutputListener
+function OutputListener(port_names) {
+	this.port_names = port_names;
+	this.queue = new Array(); // TODO: optimize!
+}
+
+OutputListener.prototype.add = function(event) {
+	if (this.port_names.length === 0
+		|| this.port_names.indexOf(event.port) !== -1)
+	{
+		this.queue.push(event);
+	}
+};
+
+OutputListener.prototype.fetch = function(timeout) {
+	return this.queue.shift();
+};
+
+// RuntimeClassBase
+function RuntimeClassBase() {
+	this.active = false;
+	this.state_changed = false;
+	this.events = new EventQueue();
+	this.timers = null;
+}
+
+RuntimeClassBase.prototype.addEvent = function(event, time_offset) {
+	if (!time_offset) time_offset = 0.0;
+	this.events.add(event, time_offset);
+};
+
+RuntimeClassBase.prototype.getEarliestEventTime = function() {
+	if (this.timers) {
+		var minimum = Infinity;
+		for (var t in this.timers) {
+			if (!this.timers.hasOwnProperty(t)) continue;
+			minimum = Math.min(minimum, this.timers[t]);
+		}
+		return Math.min(this.events.getEarliestTime(), minimum);
+	}
+	return this.events.getEarliestTime();
+};
+
+
+RuntimeClassBase.prototype.step = function(delta) {
+	if (!this.active) {
+		return;
+	}
+	this.events.decreaseTime(delta);
+	if (this.timers) {
+		var next_timers = new Object();
+		for (var t in this.timers) {
+			if (!this.timers.hasOwnProperty(t)) continue;
+			var time_left = this.timers[t] - delta;
+			if (time_left <= 0.0) {
+				this.addEvent(new Event("_" + t + "after"), time_left);
+			} else {
+				next_timers[t] = time_left;
+			}
+		}
+		this.timers = next_timers;
+	}
+
+	this.microstep();
+	while (this.state_changed) {
+		this.microstep();
+	}
+};
+
+RuntimeClassBase.prototype.microstep = function() {
+	var due = this.events.popDueEvents();
+	if (due.length === 0) {
+		this.transition();
+	} else {
+		for (var e in due) {
+			if (!due.hasOwnProperty(e)) continue;
+			this.transition(due[e].event);
+		}
+	}
+};
+
+RuntimeClassBase.prototype.transition = function(event) {
+	// pure virtual
+};
+
+RuntimeClassBase.prototype.start = function() {
+	this.active = true;
+};
+
+RuntimeClassBase.prototype.stop = function() {
+	this.active = false;
+};

+ 111 - 0
debugging_environment/javascript_runtime_old/libs/svg.js

@@ -0,0 +1,111 @@
+/**
+ * Small framework for dynamically creating/deleting shapes on an SVG canvas and responding to events.
+ *
+ * Author: Joeri Exelmans
+ * Date: 2014/07/26
+ */
+
+svg = {};
+
+svg.__ui_element_wrapper = function(element) {
+	this.element = element;
+};
+
+svg.canvas_wrapper = function(element) {
+	svg.__ui_element_wrapper.call(this, element);
+
+	this.namespace = "http://www.w3.org/2000/svg";
+	this.width = parseInt(element.getAttribute('width'));
+	this.height = parseInt(element.getAttribute('height'));
+};
+
+svg.canvas_wrapper.prototype = new svg.__ui_element_wrapper();
+
+svg.canvas_wrapper.prototype.add_circle = function(x,y,r,style) {
+	var new_element = document.createElementNS(this.namespace, "circle");
+	new_element.setAttribute('r', r);
+	new_element.setAttribute('stroke', '#000');
+	for( var key in style )
+		new_element.setAttribute(key, style[key]);
+	this.element.appendChild(new_element);
+	var wrapper = new svg.element_wrapper(this, new_element, x, y);
+	return wrapper;
+};
+
+svg.canvas_wrapper.prototype.add_rectangle = function(x,y,w,h,style) {
+	var new_element = document.createElementNS(this.namespace, "rect");
+	new_element.setAttribute('width', w);
+	new_element.setAttribute('height', h);
+	for( var key in style )
+		new_element.setAttribute(key, style[key]);
+	this.element.appendChild(new_element);
+	var wrapper = new svg.element_wrapper(this, new_element, x, y);
+	var transl = this.element.createSVGTransform();
+	transl.setTranslate(-w/2.0, -h/2.0);
+	new_element.transform.baseVal.appendItem(transl);
+	return wrapper;
+};
+
+svg.canvas_wrapper.prototype.remove_element = function(element) {
+	this.element.removeChild(element.element);
+};
+
+svg.element_wrapper = function(canvas_wrapper, element, x, y) {
+	svg.__ui_element_wrapper.call(this, element);
+	this.a = 0.0;
+
+	this.translation = canvas_wrapper.element.createSVGTransform();
+	this.rotation = canvas_wrapper.element.createSVGTransform();
+
+	this.translation.setTranslate(x,y);
+	this.rotation.setRotate(this.a, 0.0, 0.0);
+
+	/** WORKAROUND Chrome Issue 55010 (1of3) **/	
+	if( window && window.chrome && window.chrome.webstore )
+		this.__translation = {x:x, y:y};
+
+	var t = this.element.transform.baseVal;
+	t.appendItem(this.translation);
+	t.appendItem(this.rotation);
+};
+
+svg.element_wrapper.prototype = new svg.__ui_element_wrapper();
+
+svg.element_wrapper.prototype.set_position = function(x, y) {
+	/** WORKAROUND Chrome Issue 55010 (2of3) **/
+	if( window && window.chrome && window.chrome.webstore )
+	{
+		this.__translation.x = x;
+		this.__translation.y = y;
+		this.element.setAttribute('transform','translate('+this.__translation.x+' '+this.__translation.y+')');
+	}
+	else
+		this.translation.setTranslate(x,y);
+};
+
+svg.element_wrapper.prototype.get_position = function() {
+	/** WORKAROUND Chrome Issue 55010 (3of3) **/
+	if( window && window.chrome && window.chrome.webstore )
+		return {x:this.__translation.x, y:this.__translation.y};
+	else
+		return {x: this.translation.matrix.e, y: this.translation.matrix.f};
+};
+
+svg.element_wrapper.prototype.move = function(dx, dy) {
+	var pos = this.get_position();
+	this.set_position(pos.x + dx, pos.y + dy);
+};
+
+svg.element_wrapper.prototype.set_rotation = function(a) {
+	this.a = a;
+	this.rotation.setRotate(this.a, 0.0, 0.0);
+};
+
+svg.element_wrapper.prototype.rotate = function(a) {
+	this.a += a;
+	this.rotation.setRotate(this.a, 0.0, 0.0);
+};
+
+svg.element_wrapper.prototype.set_color = function(color) {
+	this.element.setAttribute('fill', color);
+};

+ 135 - 0
debugging_environment/javascript_runtime_old/libs/ui.js

@@ -0,0 +1,135 @@
+/**
+ * *REALLY* Small framework for creating/manipulating/deleting gui elements in a browser.
+ *
+ *	TODO / TBI
+ * . finer append_*() layout control (as opposed to current append at the end of the window)
+ * . finer print control (as opposed to current append at the end of main window)
+ *	. replicate ui.EVENTS for style properties
+ *	. complete this list
+ *
+ * Author: Raphael Mannadiar
+ * Date: 2014/08/14
+ */
+
+['svg'].forEach(
+	function(dependency) {if( this[dependency] === undefined ) throw 'Missing dependency: '+dependency;});
+
+
+ui = {};
+ui.window = window;
+ui.__nextWindowId = 0;
+
+ui.EVENTS = {
+	KEY_PRESS:				'keydown',
+	MOUSE_CLICK: 			'click',
+	MOUSE_MOVE: 			'mousemove',
+	MOUSE_PRESS:			'mousedown',
+	MOUSE_RELEASE:			'mouseup',
+	MOUSE_RIGHT_CLICK: 	'contextmenu',
+	WINDOW_CLOSE: 			'unload'
+};
+
+ui.MOUSE_BUTTONS = {
+	LEFT:	 	0,
+	MIDDLE:	1,
+	RIGHT:	2
+};
+
+ui.KEYCODES	= {
+	DELETE: 46
+};
+
+ui.append_button = function(_window,text) {
+	var button = _window.document.createElement('button');
+	button.innerHTML = text;
+	_window.document.body.appendChild(button);
+	return ui.wrap_element(button);
+};
+
+
+ui.append_canvas = function(_window,width,height,style) {
+	var canvas = _window.document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+	canvas.setAttribute('width', width);
+	canvas.setAttribute('height', height);
+	for( var key in style )
+		canvas.style[key] = style[key];
+	_window.document.body.appendChild(canvas);
+	return new svg.canvas_wrapper(canvas);
+};
+
+
+ui.bind_event = function(source,event,controller,raise_name,port,time_offset) {
+	if( port === undefined) port = "ui";
+	if( time_offset === undefined ) time_offset = 0.0;
+
+	var args = [];
+	switch(event) {
+		case ui.EVENTS.KEY_PRESS:
+			args = function(e) {return [e.keyCode, e.view]};
+			source = source.document;
+			break;
+
+		case ui.EVENTS.MOUSE_CLICK:
+		case ui.EVENTS.MOUSE_MOVE: 
+		case ui.EVENTS.MOUSE_PRESS:
+		case ui.EVENTS.MOUSE_RELEASE:
+		case ui.EVENTS.MOUSE_RIGHT_CLICK:
+			args = function(e) {return [e.clientX, e.clientY, e.button]};
+			if( source instanceof svg.element_wrapper )
+				source = source.element;
+			break;
+
+		case ui.EVENTS.WINDOW_CLOSE:
+			args = function() {return [source]};
+			break;
+
+		default:
+			throw 'Unsupported event';
+	}
+
+	source.addEventListener(
+		event, 
+		(function (controller, raise_name, port, time_offset) {
+ 			 return function(e) {
+ 						 e.preventDefault();
+			 			 e.stopPropagation();
+			 			 //console.log("adding input to port " + port);
+			 			 controller.addInput(new Event(raise_name, port, args(e)), time_offset);};}
+		)(controller, raise_name, port, time_offset));
+};
+
+
+ui.close_window = function(_window) {
+	_window.close();
+};
+
+
+ui.log = function(value) {
+	if( typeof(value) == 'object' )
+		console.log(JSON.stringify(value));
+	else
+		console.log(value);
+};
+
+
+ui.new_window = function(width,height) {
+	return window.open('',ui.__nextWindowId++,'width='+width+',height='+height);
+};
+
+
+ui.println = function(value,target) {
+	if( target === undefined ) target = window.document.body;
+
+	if( typeof(value) == 'object' )
+		target.innerHTML += JSON.stringify(value);
+	else
+		target.innerHTML += value;
+	target.innerHTML += '<br/>'
+};
+
+
+ui.wrap_element = function(element) {
+	return {element:element};
+};
+
+

+ 14 - 0
debugging_environment/javascript_runtime_old/libs/utils.js

@@ -0,0 +1,14 @@
+/**
+ * *REALLY* Small set of browser-compatible utility functions 
+ *
+ * Author: Raphael Mannadiar
+ * Date: 2014/08/14
+ */
+
+utils = {};
+
+utils.random = function() {
+	return Math.random();
+};
+
+

File diff suppressed because it is too large
+ 1204 - 0
debugging_environment/javascript_runtime_old/statecharts_core.js


+ 9 - 0
debugging_environment/package.json

@@ -0,0 +1,9 @@
+{
+  "name": "dsdevs-debuggingenv",
+  "version": "0.0.1",
+  "description": "Dynamic Structure DEVS Debugging Environment",
+  "dependencies": {
+    "express": "^4.10.2",
+    "socket.io": "^1.4.5"
+  }
+}

+ 329 - 0
debugging_environment/particle_interaction.py

@@ -0,0 +1,329 @@
+from DEVS import *
+from infinity import INFINITY
+
+import random, math, sys, getopt
+
+''' The simulation does not end. '''
+def termination_condition(time, model, transitioned):
+    time = time[0]
+    return False
+    
+class Canvas:
+    def __init__(self, resolution):
+        self.width = resolution[0]
+        self.height = resolution[1]
+        
+class ParticleState:
+    def __init__(self, canvas, particle_id):
+        self.r = random.uniform(5.0, 30.0)
+        x = random.uniform(self.r, canvas.width - self.r)
+        y = random.uniform(self.r, canvas.height - self.r)
+        self.pos = (x, y)
+        self.vel = {'x': random.uniform(-75.0, 75.0), 'y': random.uniform(-75.0, 75.0)}
+        self.phase = "initializing" # phases: ('initializing', 'initialized', 'bouncing', 'spawning', 'selected', 'deleting', 'clicked')
+        self.color = "red"
+        self.prev_color = "red"
+        self.collision_detected = False
+        self.clicked = False
+        self.frames_passed = 0
+        self.frames_remaining = 0
+        self.remaining = 0
+        self.particle_id = particle_id
+
+class Particle(AtomicDEVS):
+    def __init__(self, particle_id, canvas, framerate, spawn_chance, die_chance):
+        AtomicDEVS.__init__(self, "Particle[%i]" % particle_id)
+        
+        self.particle_id = particle_id
+        self.canvas = canvas
+        self.framerate = framerate
+        self.spawn_chance = spawn_chance
+        self.die_chance = die_chance
+        
+        self.COLLISION_DETECT = self.addInPort("COLLISION_DETECT")
+        self.POS_OUT = self.addOutPort("POS_OUT")
+        self.SPAWNER_COMM = self.addOutPort("SPAWNER_COMM")
+        self.COLOR_OUT = self.addOutPort("COLOR_OUT")
+        
+        self.state = ParticleState(canvas, particle_id)
+    
+    def timeAdvance(self):
+        return self.state.remaining
+    
+    def outputFnc(self):
+        output = {}
+        if self.state.phase in ("bouncing", "spawning", "selected") or self.state.clicked:
+            output[self.POS_OUT] = (self.particle_id, self.state.pos, self.state.r, self.state.vel)
+        if self.state.collision_detected and self.state.phase != "spawning" and random.random() < self.spawn_chance:
+            output[self.SPAWNER_COMM] = ["spawn_particle"]
+        if self.state.phase == "selected" and self.state.prev_color == self.state.color:
+            output[self.POS_OUT] = ("delete", self.particle_id)
+        if self.state.color != self.state.prev_color:
+            output[self.COLOR_OUT] = (self.particle_id, self.state.color)
+        if self.state.phase == "initializing":
+            output[self.POS_OUT] = ("created", self.particle_id, self.state.pos, self.state.r, self.state.vel)
+        return output
+    
+    def intTransition(self):
+        if self.state.phase == "initializing":
+            self.state.phase = "initialized"
+            self.state.remaining = 0
+        elif self.state.phase == "initialized":
+            self.state.phase = "bouncing"
+            self.state.remaining = 1
+        elif self.state.phase == "selected":
+            if self.state.prev_color == self.state.color:
+                self.state.phase = "deleting"
+                self.state.remaining = INFINITY
+            else:
+                self.state.prev_color = self.state.color
+                self.state.remaining = int(2.5 * self.framerate)
+        elif self.state.prev_color != self.state.color:
+            self.state.prev_color = self.state.color
+            self.state.remaining = 0
+        elif self.state.phase == "clicked":
+            self.state.remaining = INFINITY
+        elif random.random() < self.die_chance:
+            self.state.vel = {'x': 0, 'y': 0}
+            self.state.color = "yellow"
+            self.state.phase = "selected"
+            self.state.remaining = 0
+        else:
+            if self.state.frames_passed < self.framerate and self.state.phase in ("bouncing", "spawning") and self.state.color != "black":
+                self.state.frames_passed += 1
+            if self.state.frames_passed >= self.framerate and self.state.phase == "bouncing":
+                self.state.color = "black"
+                self.state.phase = "bouncing"
+                self.state.frames_passed = 0
+            if self.state.frames_passed >= 1 * self.framerate and self.state.phase == "spawning":
+                self.state.color = "black"
+                self.state.phase = "bouncing"
+                self.state.frames_passed = 0
+            x = self.state.pos[0]
+            y = self.state.pos[1]
+            if (x - self.state.r) <= 0 or x + self.state.r >= self.canvas.width:
+                self.state.vel['x'] = -self.state.vel['x']
+            if (y - self.state.r) <= 0 or y + self.state.r >= self.canvas.height:
+                self.state.vel['y'] = -self.state.vel['y']
+            self.state.pos = (self.state.pos[0] + (self.state.vel['x'] / self.framerate), self.state.pos[1] + (self.state.vel['y'] / self.framerate))
+            if self.state.collision_detected:
+                self.state.phase = "spawning"
+                self.state.color = "blue"
+            elif self.state.clicked:
+                self.state.vel = {'x': 0, 'y': 0}
+                self.state.phase = "clicked"
+                self.state.color = "orange"
+                self.state.clicked = False
+            self.state.remaining = 1
+        self.state.collision_detected = False
+        return self.state
+    
+    def extTransition(self, inputs):
+        if self.COLLISION_DETECT in inputs:
+            if inputs[self.COLLISION_DETECT] == "delete_if_selected":
+                if self.state.phase == "clicked":
+                    self.state.phase = "selected"
+                    self.state.remaining = 0
+            elif inputs[self.COLLISION_DETECT] == "clicked":
+                if self.state.phase == "bouncing":
+                    self.state.clicked = True
+                    self.state.remaining = 0
+            elif self.state.phase in ("bouncing", "clicked", "deleting"):
+                self.state.phase = "bouncing"
+                self.state.collision_detected = True
+                new_speed = inputs[self.COLLISION_DETECT][1]
+                self.state.vel = {'x': new_speed[0], 'y': new_speed[1]}
+                self.state.remaining = 0
+            #else:
+                #self.state.remaining -= self.elapsed
+        return self.state
+    
+    def modelTransition(self, passed_values):
+        if self.state.phase == "deleting":
+            passed_values['to_delete'] = self
+            return True
+        elif self.state.phase == "initialized":
+            passed_values['connect_particle'] = (self.particle_id, self.COLLISION_DETECT)
+            return True
+        return False
+        
+class ParticleSpawnerState:
+    def __init__(self):        
+        self.id_ctr = 0
+        self.new_particle = None
+        self.remaining = 0
+
+class ParticleSpawner(AtomicDEVS):
+    def __init__(self, canvas, framerate, spawn_chance, die_chance):
+        AtomicDEVS.__init__(self, "ParticleSpawner")
+        
+        self.canvas = canvas
+        self.framerate = framerate
+        self.spawn_chance = spawn_chance
+        self.die_chance = die_chance
+        
+        self.REQUEST = self.addInPort("REQUEST")
+        
+        self.state = ParticleSpawnerState()
+    
+    def timeAdvance(self):
+        return self.state.remaining
+    
+    def intTransition(self):
+        self.state.new_particle = Particle(self.state.id_ctr, self.canvas, self.framerate, self.spawn_chance, self.die_chance)
+        self.state.id_ctr += 1
+        self.state.remaining = self.framerate
+        return self.state
+    
+    def extTransition(self, inputs):
+        self.state.remaining -= self.elapsed
+        if self.REQUEST in inputs:
+            self.state.new_particle = Particle(self.state.id_ctr, self.canvas, self.framerate, self.spawn_chance, self.die_chance)
+            self.state.id_ctr += 1
+        return self.state
+    
+    def modelTransition(self, passed_values):
+        if self.state.new_particle:
+            passed_values['new_particle'] = self.state.new_particle
+            return True
+        return False
+
+class PositionManagerState:
+    def __init__(self):        
+        self.positions = {}
+        self.collisions = set([])
+        self.phase = "detecting"
+        self.clicked = None
+        self.delete_selected = False
+        self.frames = 0
+        self.remaining = 0
+    
+    def __str__(self):
+        return str((self.phase, self.frames, self.remaining))
+
+class PositionManager(AtomicDEVS):
+    def __init__(self, framerate):
+        AtomicDEVS.__init__(self, "PositionManager")
+        
+        self.framerate = framerate
+        
+        self.TIME_OUT = self.addOutPort("TIME_OUT")
+        self.POS_IN = self.addInPort("POS_IN")
+        self.INTERRUPT = self.addInPort("INTERRUPT")
+        
+        self.state = PositionManagerState()
+    
+    def timeAdvance(self):
+        return self.state.remaining
+    
+    def outputFnc(self):
+        output = {}
+        if self.state.collisions:
+            output.update({self.ports['PARTICLES_OUT[%i]' % particle_id]: ("collision_detected", deltap) for (particle_id, deltap) in self.state.collisions})
+        if self.state.clicked is not None:
+            portname = 'PARTICLES_OUT[%i]' % self.state.clicked
+            if portname in self.ports:
+                output[self.ports[portname]] = "clicked"
+        if self.state.delete_selected:
+            output.update({self.ports['PARTICLES_OUT[%i]' % particle_id]: "delete_if_selected" for particle_id in self.state.positions})
+        output[self.TIME_OUT] = self.state.frames
+        return output
+    
+    def intTransition(self):
+        self.state.frames += self.timeAdvance()
+        if self.state.clicked is not None:
+            self.state.clicked = None
+            self.state.remaining = 1
+        if self.state.delete_selected:
+            self.state.delete_selected = False
+            self.state.remaining = 1
+        elif self.state.phase == "detecting":
+            for k1, v1 in self.state.positions.iteritems():
+                for k2, v2 in self.state.positions.iteritems():
+                    if k1 > k2:
+                        dx = v2[0][0] - v1[0][0]
+                        dy = v2[0][1] - v1[0][1]
+                        distance = math.sqrt(dx**2 + dy**2)
+                        if (distance < (v1[1] + v2[1])) and (k1 not in self.state.collisions or k2 not in self.state.collisions):
+                            new_speed_1 = (v2[2]['x'], v2[2]['y'])
+                            new_speed_2 = (v1[2]['x'], v1[2]['y'])
+                            self.state.collisions.add((k1, new_speed_1))
+                            self.state.collisions.add((k2, new_speed_2))
+            if self.state.collisions:
+                self.state.phase = "detected"
+                self.state.remaining = 0
+            else:
+                self.state.phase = "detecting"
+                self.state.remaining = 1
+        elif self.state.phase == "detected":
+            self.state.collisions = set([])
+            self.state.phase = "detecting"
+            self.state.remaining = 1
+        return self.state
+    
+    def extTransition(self, inputs):
+        self.state.remaining -= self.elapsed
+        self.state.frames += self.elapsed
+        if self.POS_IN in inputs:
+            msg = inputs[self.POS_IN]
+            if msg[0] == "created":
+                new_particle_id = msg[1]
+                self.addOutPort("PARTICLES_OUT[%s]" % new_particle_id)
+                self.state.positions[new_particle_id] = (msg[2], msg[3], msg[4])
+            elif msg[0] == "delete":
+                self.removePort(self.ports["PARTICLES_OUT[%s]" % msg[1]])
+                del self.state.positions[msg[1]]
+            else:
+                particle_id = msg[0]
+                r = msg[2]
+                self.state.positions[particle_id] = (msg[1], msg[2], msg[3])
+        # TODO: Fix this, needs to be rounded to integer.
+        if self.INTERRUPT in inputs:
+            msg = inputs[self.INTERRUPT]
+            if msg == "delete_selected":
+                self.state.delete_selected = True
+            else:
+                self.state.clicked = int(msg)
+        return self.state
+
+class Root(CoupledDEVS):
+    def __init__(self, canvas=Canvas((800, 600)), framerate=30.0, spawn_chance=0.2, die_chance=0.01):
+        CoupledDEVS.__init__(self, "Field")
+        
+        self.INTERRUPT = self.addInPort("INTERRUPT")
+        self.POS_OUT = self.addOutPort("POS_OUT")
+        self.COLOR_OUT = self.addOutPort("COLOR_OUT")
+        self.TIME_OUT = self.addOutPort("TIME_OUT")
+        
+        self.particle_spawner = self.addSubModel(ParticleSpawner(canvas, framerate, spawn_chance, die_chance))
+        self.position_manager = self.addSubModel(PositionManager(framerate))
+        self.connectPorts(self.INTERRUPT, self.position_manager.INTERRUPT)
+        self.connectPorts(self.position_manager.TIME_OUT, self.TIME_OUT)
+            
+    def modelTransition(self, passed_values):
+        if 'new_particle' in passed_values:
+            new_particle = passed_values['new_particle']
+            self.addSubModel(new_particle)
+            self.connectPorts(new_particle.POS_OUT, self.position_manager.POS_IN)
+            self.connectPorts(new_particle.POS_OUT, self.POS_OUT)
+            self.connectPorts(new_particle.COLOR_OUT, self.COLOR_OUT)
+            self.connectPorts(new_particle.SPAWNER_COMM, self.particle_spawner.REQUEST)
+            del passed_values['new_particle']
+        if 'to_delete' in passed_values:
+            self.removeSubModel(passed_values['to_delete'])
+            del passed_values['to_delete']
+        if 'connect_particle' in passed_values:
+            particle_id, COLLISION_DETECT = passed_values['connect_particle']
+            self.connectPorts(self.position_manager.ports['PARTICLES_OUT[%s]' % particle_id], COLLISION_DETECT)
+            del passed_values['connect_particle']
+        return False
+        
+    def select(self, imm_children):
+        pos_mgr, particle_spawner = [None] * 2
+        for c in imm_children:
+            if c.getModelName() == "ParticleSpawner":
+                particle_spawner = c
+        if particle_spawner:
+            return particle_spawner
+        else:
+            return imm_children[0]

+ 954 - 0
debugging_environment/pypdevs/DEVS.py

@@ -0,0 +1,954 @@
+# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at 
+# McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
+# 
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+Classes and tools for DEVS model specification
+"""
+
+#from pypdevs.logger import debug, warn, info, error
+#from pypdevs.util import *
+import time
+
+class BaseDEVS(object):
+    """
+    Abstract base class for AtomicDEVS and CoupledDEVS classes.
+  
+    This class provides basic DEVS attributes and query/set methods.
+    """
+    def __init__(self, name):
+        """
+        Constructor
+
+        :param name: the name of the DEVS model
+        """
+    
+        # Prevent any attempt to instantiate this abstract class
+        if self.__class__ == BaseDEVS:
+            raise DEVSException ("Cannot instantiate abstract class '%s' ... " 
+                                 % (self.__class__.__name__))
+
+        # The parent of the current model
+        self.parent = None
+        # The local name of the model
+        self.name = name
+        self.IPorts  = []  
+        self.OPorts   = []
+        self.ports = {}
+
+        # Initialise the times
+        self.time_last = (0.0, 0)
+        self.time_next = (0.0, 1)
+
+        self.location = None
+    
+        # Variables used for optimisations
+        self.my_input = {}  
+        self.my_output = {}
+
+        # The state queue, used for time warp
+        self.old_states = []
+        # List of all memoized states, only useful in distributed simulation 
+        #   with memoization enabled
+        self.memo = []
+
+    def simSettings(self, simulator):
+        """
+        Modifies the simulation settings from within the model.
+
+        This function is called _before_ direct connection and distribution is performed, so the user can still access the complete hierarchy.
+
+        .. note:: This function is *only* called on the root model of the simulation, thus the model passed to the constructor of the Simulator object.
+
+        :param simulator: the simulator object on which settings can be configured
+        """
+        pass
+
+    def modelTransition(self, state):
+        """
+        DEFAULT function for Dynamic Structure DEVS, always returning False (thus indicating that no structural change is needed)
+
+        :param state: a dict that can be used to save some kind of state, this object is maintained by the kernel and will be passed each time
+        :returns: bool -- whether or not a structural change is necessary
+        """
+        return False
+
+    def getVCDVariables(self):
+        """
+        Fetch all the variables, suitable for VCD variable generation
+
+        :returns: list -- all variables needed for VCD tracing
+        """
+        var_list = []
+        for I in self.ports.itervalues():
+            var_list.append([self.getModelFullName(), I.getPortName()])
+        return var_list
+
+    def removePort(self, port):
+        """
+        Remove a port (either input or output) from the model, disconnecting all of its connections.
+
+        :param port: the port to remove
+        """
+        if not hasattr(self, "full_name"):
+            raise DEVSException("removePort should only be called during a simulation")
+        if port.is_input:
+            self.IPorts.remove(port)
+        else:
+            self.OPorts.remove(port)
+        del self.ports[port.port_id]
+
+        # Also remove all connections to this port
+        self.server.getSelfProxy().dsRemovePort(port)
+
+    def addPort(self, name, is_input):
+        """
+        Utility function to create a new port and add it everywhere where it is necessary
+
+        :param name: the name of the port
+        :param is_input: whether or not this is an input port
+        """
+        name = name if name is not None else "port%s" % len(self.ports)
+        port = Port(is_input=is_input, name=name) 
+        if is_input:
+            self.IPorts.append(port)
+        else:
+            self.OPorts.append(port)
+        port.port_id = port.getPortName()
+        self.ports[port.port_id] = port
+        port.host_DEVS = self
+        if hasattr(self, "full_name"):
+            self.server.getSelfProxy().dsAddPort(port)
+        return port
+      
+    def addInPort(self, name=None):
+        """
+        Add an input port to the DEVS model.
+        
+        addInPort is the only proper way to add input ports to a DEVS model. 
+        As for the CoupledDEVS.addSubModel method, calls
+        to addInPort and addOutPort can appear in any DEVS'
+        descriptive class constructor, or the methods can be used with an
+        instantiated object.
+    
+        The methods add a reference to the new port in the DEVS' IPorts 
+        attributes and set the port's hostDEVS attribute. The modeler
+        should typically save the returned reference somewhere.
+
+        :param name: the name of the port. A unique ID will be generated in case None is passed
+        :returns: port -- the generated port
+        """
+        return self.addPort(name, True)
+      
+    def addOutPort(self, name=None):
+        """Add an output port to the DEVS model.
+
+        addOutPort is the only proper way to
+        add output ports to DEVS. As for the CoupledDEVS.addSubModel method, calls
+        to addInPort and addOutPort can appear in any DEVS'
+        descriptive class constructor, or the methods can be used with an
+        instantiated object.
+    
+        The methods add a reference to the new port in the DEVS'
+        OPorts attributes and set the port's hostDEVS attribute. The modeler
+        should typically save the returned reference somewhere.
+
+        :param name: the name of the port. A unique ID will be generated in case None is passed
+        :returns: port -- the generated port
+        """
+        return self.addPort(name, False)
+    
+    def getModelName(self):
+        """
+        Get the local model name
+
+        :returns: string -- the name of the model
+        """
+        if self.name is None:
+            return str(self.model_id)
+        else:
+            return str(self.name)
+
+    def getModelFullName(self):
+        """
+        Get the full model name, including the path from the root
+
+        :returns: string -- the fully qualified name of the model
+        """
+        return self.full_name
+
+class AtomicDEVS(BaseDEVS):
+    """
+    Abstract base class for all atomic-DEVS descriptive classes.
+    """
+  
+    def __init__(self, name=None):
+        """
+        Constructor for an AtomicDEVS model
+
+        :param name: name of the model, can be None to have an automatically generated name
+        """
+        # Prevent any attempt to instantiate this abstract class
+        if self.__class__ == AtomicDEVS:
+            raise DEVSException("Cannot instantiate abstract class '%s' ... " 
+                                % (self.__class__.__name__))
+
+        # The minimal constructor shall first call the superclass
+        # (i.e., BaseDEVS) constructor.
+        BaseDEVS.__init__(self, name)
+    
+        self.elapsed = 0.0 
+        self.state = None
+        self.relocatable = True
+        self.last_read_time = (0, 0)
+
+    def setLocation(self, location, force=False):
+        """
+        Sets the location of the atomic DEVS model if it was not already set
+
+        :param location: the location to set
+        :param force: whether or not to force this location, even if another is already defined
+        """
+        if self.location is None or force:
+            self.location = location
+
+    def fetchActivity(self, time, activities):
+        """
+        Fetch the activity of the model up to a certain time
+
+        :param time: the time up to which the activity should be calculated
+        :param activities: dictionary containing all activities for the models
+        """
+        accumulator = 0.0
+        for state in self.old_states:
+            if state.time_last[0] < time:
+                accumulator += state.activity
+        activities[self.model_id] = accumulator
+        
+    def setGVT(self, gvt, activities, last_state_only):
+        """
+        Set the GVT of the model, cleaning up the states vector as required
+        for the time warp algorithm
+
+        :param gvt: the new value of the GVT
+        :param activities: dictionary containing all activities for the models
+        :param last_state_only: whether or not to only use a single state for activity
+        """
+        copy = None
+        activity = 0
+        for i in range(len(self.old_states)):
+            state = self.old_states[i]
+            if state.time_last[0] >= gvt:
+                # Possible that all elements should be kept, 
+                # in which case it will return -1 and only keep the last element
+                # So the copy element should be AT LEAST 0
+                copy = max(0, i-1)
+                break
+            elif not last_state_only:
+                activity += state.activity
+        if self.old_states == []:
+            # We have no memory, so we are normally in sequential simulation
+            self.old_states = []
+        elif copy is None:
+            self.old_states = [self.old_states[-1]]
+        else:
+            self.old_states = self.old_states[copy:]
+        if last_state_only:
+            activity = self.old_states[0].activity
+        activities[self.model_id] = activity
+
+    def revert(self, time, memorize):
+        """
+        Revert the model to the specified time. All necessary cleanup for this
+        model will be done (fossil collection).
+
+        :param time: the time up to which should be reverted
+        :param memorize: whether or not the saved states should still be kept for memoization
+        """
+        new_state = len(self.old_states) - 1
+        for state in reversed(self.old_states[1:]):
+            if state.time_last < time:
+                break
+            new_state -= 1
+
+        state = self.old_states[new_state]
+        self.time_last = state.time_last
+        self.time_next = state.time_next
+
+        self.state = state.loadState()
+        if memorize:
+            # Reverse it too
+            self.memo = self.old_states[:-len(self.old_states) + new_state - 1:-1]
+        self.old_states = self.old_states[:new_state + 1]
+
+        # Check if one of the reverted states was ever read for the termination condition
+        if self.last_read_time > time:
+            # It seems it was, so notify the main revertion algorithm of this
+            self.last_read_time = (0, 0)
+            return True
+        else:
+            return False
+
+        # NOTE clearing the myInput happens in the parent
+
+    def getState(self, request_time, first_call=True):
+        """
+        For the distributed termination condition: fetch the state of the model at a certain time
+
+        :param request_time: the time (including age!) for which the state should be fetched
+        :param first_call: whether or not this is the first call of a possible recursive call
+        :returns: state -- the state at that time
+        """
+        if self.location != MPIRedirect.local.name:
+            return getProxy(self.location).getStateAtTime(self.model_id, 
+                                                          request_time)
+        elif first_call:
+            # Shortcut if the call is local
+            return self.state
+        self.last_read_time = request_time
+        while 1:
+            for state in self.old_states:
+                if state.time_last > request_time:
+                    return state.loadState()
+            # State not yet available... wait some time before trying again...
+            time.sleep(0.01)
+
+    def extTransition(self, inputs):
+        """
+        DEFAULT External Transition Function.
+  
+        Accesses state and elapsed attributes, as well as inputs
+        through the passed dictionary. Returns the new state.
+
+        .. note:: Should only write to the *state* attribute.
+
+        :param inputs: dictionary containing all ports and their corresponding outputs
+        :returns: state -- the new state of the model
+        """
+        return self.state
+    
+    def intTransition(self):
+        """
+        DEFAULT Internal Transition Function.
+ 
+        .. note:: Should only write to the *state* attribute.
+
+        :returns: state -- the new state of the model
+
+        .. versionchanged:: 2.1 The *elapsed* attribute is no longer guaranteed to be correct as this isn't required by the DEVS formalism.
+
+        """
+        return self.state
+
+    def confTransition(self, inputs):
+        """
+        DEFAULT Confluent Transition Function.
+  
+        Accesses state and elapsed attributes, as well as inputs
+        through the passed dictionary. Returns the new state.
+
+        .. note:: Should only write to the *state* attribute.
+
+        :param inputs: dictionary containing all ports and their corresponding outputs
+        :returns: state -- the new state of the model
+        """
+        self.state = self.intTransition()
+        self.state = self.extTransition(inputs)
+        return self.state
+  
+    def outputFnc(self):
+        """
+        DEFAULT Output Function.
+  
+        Accesses only state attribute. Returns the output on the different ports as a dictionary.
+
+        .. note:: Should **not** write to any attribute.
+
+        :returns: dictionary containing output ports as keys and lists of output on that port as value
+
+        .. versionchanged:: 2.1 The *elapsed* attribute is no longer guaranteed to be correct as this isn't required by the DEVS formalism.
+
+        """
+        return {}
+  
+    def timeAdvance(self):
+        """
+        DEFAULT Time Advance Function.
+    
+        .. note:: Should ideally be deterministic, though this is not mandatory for simulation.
+
+        :returns: the time advance of the model
+
+        .. versionchanged:: 2.1 The *elapsed* attribute is no longer guaranteed to be correct as this isn't required by the DEVS formalism.
+
+        """
+        # By default, return infinity 
+        return float('inf')
+
+    def preActivityCalculation(self):
+        """
+        DEFAULT pre-transition activity fetcher. The returned value is passed to the *postActivityCalculation* function
+
+        :returns: something -- passed to the *postActivityCalculation*
+        """
+        return time.time()
+
+    def postActivityCalculation(self, prevalue):
+        """
+        DEFAULT post-transition activity fetcher. The returned value will be passed on to the relocator and MUST be an addable (e.g. integer, float, ...)
+
+        :param prevalue: the value returned from the *preActivityCalculation* method
+        :returns: addable (float, integer, ...) -- passed to the relocator
+        """
+        return time.time() - prevalue
+
+    def flattenConnections(self):
+        """
+        Flattens the pickling graph, by removing backreference from the ports.
+        """
+        # It doesn't really matter what gets written in these hostDEVS attributes,
+        # as it will never be used. Though for readability, the model_id will be used
+        # to make it possible to do some debugging when necessary.
+        for port in self.IPorts:
+            port.host_DEVS = self.model_id
+        for port in self.OPorts:
+            port.host_DEVS = self.model_id
+
+    def unflattenConnections(self):
+        """
+        Unflattens the picking graph, by reconstructing backreferences from the ports.
+        """
+        for port in self.IPorts:
+            port.host_DEVS = self
+        for port in self.OPorts:
+            port.host_DEVS = self
+
+    def finalize(self, name, model_counter, model_ids, locations, select_hierarchy):
+        """
+        Finalize the model hierarchy by doing all pre-simulation configuration
+
+        .. note:: Parameters *model_ids* and *locations* are updated by reference.
+
+        :param name: the name of the hierarchy above
+        :param model_counter: the model ID counter
+        :param model_ids: a list with all model_ids and their model
+        :param locations: dictionary of locations and where every model runs
+        :param select_hierarchy: hierarchy to perform selections in Classic DEVS
+
+        :returns: int -- the new model ID counter
+        """
+        # Give a name
+        self.full_name = name + str(self.getModelName())
+
+        # Give a unique ID to the model itself
+        self.model_id = model_counter
+        self.select_hierarchy = select_hierarchy + [self]
+
+        # Add the element to its designated place in the model_ids list
+        model_ids.append(self)
+
+        # Do a quick check, since this is vital to correct operation
+        if model_ids[self.model_id] != self:
+            raise DEVSException("Something went wrong while initializing models: IDs don't match")
+
+        locations[self.location].append(self.model_id)
+
+        # Return the unique ID counter, incremented so it stays unique
+        return model_counter + 1
+
+    def getModelLoad(self, lst):
+        """
+        Add this atomic model to the load of its location
+
+        :param lst: list containing all locations and their current load
+        :returns: int -- number of children in this subtree
+        """
+        lst[self.location] += 1
+        self.num_children = 1
+        return self.num_children
+    
+class CoupledDEVS(BaseDEVS):
+    """
+    Abstract base class for all coupled-DEVS descriptive classes.
+    """
+  
+    def __init__(self, name=None):
+        """
+        Constructor.
+
+        :param name: the name of the coupled model, can be None for an automatically generated name
+        """
+        # Prevent any attempt to instantiate this abstract class
+        if self.__class__ == CoupledDEVS:
+            raise DEVSException("Cannot instantiate abstract class '%s' ... " 
+                                % (self.__class__.__name__))
+        # The minimal constructor shall first call the superclass
+        # (i.e., BaseDEVS) constructor.
+        BaseDEVS.__init__(self, name)
+    
+        # All components of this coupled model (the submodels)
+        self.component_set = []
+
+    def forceSequential(self):
+        """
+        Force a sequential simulation
+        """
+        self.setLocation(0, force=True)
+    
+    def select(self, imm_children):
+        """
+        DEFAULT select function, only used when using Classic DEVS simulation
+
+        :param imm_children: list of all children that want to transition
+        :returns: child -- a single child that is allowed to transition
+        """
+        return imm_children[0]
+
+    def getModelLoad(self, lst):
+        """
+        Fetch the number of atomic models at this model
+
+        :param lst: list containing all locations and their current load
+        :returns: number of atomic models in this subtree, including non-local ones
+        """
+        children = 0
+        for i in self.component_set:
+            children += i.getModelLoad(lst)
+        self.num_children = children
+        return self.num_children
+        
+    def finalize(self, name, model_counter, model_ids, locations, select_hierarchy):
+        """
+        Finalize the model hierarchy by doing all pre-simulation configuration
+
+        .. note:: Parameters *model_ids* and *locations* are updated by reference.
+
+        :param name: the name of the hierarchy above
+        :param model_counter: the model ID counter
+        :param model_ids: a list with all model_ids and their model
+        :param locations: dictionary of locations and where every model runs
+        :param select_hierarchy: hierarchy to perform selections in Classic DEVS
+
+        :returns: int -- the new model ID counter
+        """
+        # Set name, even though it will never be requested
+        self.full_name = name + str(self.getModelName())
+        for i in self.component_set:
+            model_counter = i.finalize(self.full_name + ".", model_counter, 
+                    model_ids, locations, select_hierarchy + [self])
+        return model_counter
+
+    def flattenConnections(self):
+        """
+        Flattens the pickling graph, by removing backreference from the ports.
+        """
+        for i in self.component_set:
+            i.flattenConnections()
+
+    def unflattenConnections(self):
+        """
+        Unflattens the pickling graph, by reconstructing backreference from the ports.
+        """
+        for i in self.component_set:
+            i.unflattenConnections()
+
+    def addSubModel(self, model, location = None):
+        """
+        Adds a specified model to the current coupled model as its child. This
+        is the function that must be used to make distributed simulation
+        possible.
+
+        :param model: the model to be added as a child
+        :param location: the location at which the child must run
+        :returns: model -- the model that was created as a child
+
+        .. versionchanged:: 2.1.3
+           model can no longer be a string, this was previously a lot more efficient in partial distribution, though this functionality was removed together with the partial distribution functionality.
+        """
+        model.parent = self
+        if location is not None:
+            location = int(location)
+        model.location = location if location is not None else self.location
+        if model.location is not None and isinstance(model, CoupledDEVS):
+            # Set the location of all children
+            for i in model.component_set:
+                i.setLocation(model.location)
+        if hasattr(self, "full_name"):
+            # Full Name is only created when starting the simulation, so we are currently in a running simulation
+            # Dynamic Structure change
+            self.server.getSelfProxy().dsScheduleModel(model)
+        else:
+            self.component_set.append(model)        
+        return model
+
+    def removeSubModel(self, model):
+        """
+        Remove a specified model from the current coupled model, only callable while in a simulation.
+
+        :param model: the model to remove as a child
+        """
+        if not hasattr(self, "full_name"):
+            raise DEVSException("removeSubModel can only be called _during_ a simulation run")
+        self.server.getSelfProxy().dsUnscheduleModel(model)
+
+    def disconnectPorts(self, p1, p2):
+        """
+        Disconnect two ports
+        
+        .. note:: If these ports are connected multiple times, **only one** of them will be removed.
+
+        :param p1: the port at the start of the connection
+        :param p2: the port at the end of the connection
+        """
+        if not hasattr(self, "full_name"):
+            raise DEVSException("removeSubModel can only be called _during_ a simulation run")
+        new_connection = []
+        found = False
+        for p in p1.outline:
+            if p == p2 and not found:
+                found = True
+            else:
+                new_connection.append(p)
+        p1.outline = new_connection
+        new_connection = []
+        found = False
+        for p in p2.inline:
+            if p == p1 and not found:
+                found = True
+            else:
+                new_connection.append(p)
+        p2.inline = new_connection
+        self.server.getSelfProxy().dsDisconnectPorts(p1, p2)
+
+    def connectPorts(self, p1, p2, z = None):
+        """
+        Connects two ports together. The coupling is to begin at p1 and
+        to end at p2.
+
+        :param p1: the port at the start of the new connection
+        :param p2: the port at the end of the new connection
+        :param z: the translation function for the events
+                  either input-to-input, output-to-input or output-to-output.
+        """
+        # For a coupling to be valid, two requirements must be met:
+        # 1- at least one of the DEVS the ports belong to is a child of the
+        #    coupled-DEVS (i.e., self), while the other is either the
+        #    coupled-DEVS itself or another of its children. The DEVS'
+        #    'parenthood relationship' uniquely determine the type of coupling;
+        # 2- the types of the ports are consistent with the 'parenthood' of the
+        #    associated DEVS. This validates the coupling determined above.
+
+        # Internal Coupling:
+        if ((p1.host_DEVS.parent == self and p2.host_DEVS.parent == self) and
+                (p1.type() == 'OUTPORT' and p2.type() == 'INPORT')):
+            if p1.host_DEVS is p2.host_DEVS:
+                raise DEVSException(("In coupled model '%s', connecting ports" +
+                                    " '%s' and '%s' belong to the same model" +
+                                    " '%s'. " +
+                                    " Direct feedback coupling not allowed") % (
+                                    self.getModelFullName(),
+                                    p1.getPortFullName(),
+                                    p2.getPortFullName(),
+                                    p1.host_DEVS.getModelFullName()))
+            else:
+                p1.outline.append(p2)
+                p2.inline.append(p1)
+        
+        # External input couplings:
+        elif ((p1.host_DEVS == self and p2.host_DEVS.parent == self) and
+              (p1.type() == p2.type() == 'INPORT')):
+            p1.outline.append(p2)
+            p2.inline.append(p1)
+   
+        # Eternal output couplings:
+        elif ((p1.host_DEVS.parent == self and p2.host_DEVS == self) and
+              (p1.type() == p2.type() == 'OUTPORT')):
+            p1.outline.append(p2)
+            p2.inline.append(p1)
+
+        # Other cases (illegal coupling):
+        else:
+            raise DEVSException(("Illegal coupling in coupled model '%s' " +
+                                "between ports '%s' and '%s'") % (
+                                self.getModelName(), p1.getPortName(), 
+                                p2.getPortName()))
+
+        p1.z_functions[p2] = z
+        if hasattr(self, "server"):
+            # TODO modify
+            self.server.getSelfProxy().dsConnectPorts(p1, p2)
+
+    def setLocation(self, location, force=False):
+        """
+        Sets the location of this coupled model and its submodels if they don't have their own preference.
+
+        :param location: the location to set
+        :param force: whether or not to force this location, even if another is already defined
+        """
+        if self.location is None or force:
+            self.location = location
+            for child in self.component_set:
+                child.setLocation(location, force)
+
+class RootDEVS(BaseDEVS):
+    """
+    The artificial RootDEVS model is the only 'coupled' model in the simulation after direct connection is performed.
+    """
+    def __init__(self, components, models, scheduler_type):
+        """
+        Basic constructor.
+
+        :param components: the atomic DEVS models that are the cildren, only those that are ran locally should be mentioned
+        :param models: all models that have to be passed to the scheduler, thus all models, even non-local ones
+        :param scheduler_type: type of scheduler to use (string representation)
+        """
+        BaseDEVS.__init__(self, "ROOT model")
+        self.component_set = components
+        self.time_next = (float('inf'), 1)
+        self.local_model_ids = set()
+        for i in self.component_set:
+            self.local_model_ids.add(i.model_id)
+        self.models = models
+        self.scheduler_type = scheduler_type
+    
+    def redoDirectConnection(self, ports):
+        """
+        Redo direct connection for a specified port, and all ports connected to it.
+
+        :param ports: the ports that have changed.
+        """
+        # Find all changed ports and redo their direct connection
+        worklist = list(ports)
+        for outport in worklist:
+            worklist.extend(outport.inline)
+        
+        for p in set(worklist):
+            directConnectPort(p, self.listeners)
+
+    def directConnect(self):
+        """
+        Perform direct connection on the models again
+        """
+        directConnect(self.models, self.listeners)
+
+    def setScheduler(self, scheduler_type):
+        """
+        Set the scheduler to the desired type. Will overwite the previously present scheduler.
+
+        :param scheduler_type: type of scheduler to use (string representation)
+        """
+        if isinstance(scheduler_type, tuple):
+            try:
+                exec("from pypdevs.schedulers.%s import %s" % scheduler_type)
+            except:
+                exec("from %s import %s" % scheduler_type)
+            nr_models = len(self.models)
+            self.scheduler = eval("%s(self.component_set, EPSILON, nr_models)"
+                                  % scheduler_type[1])
+        else:
+            raise DEVSException("Unknown Scheduler: " + str(scheduler_type))
+
+    def setGVT(self, gvt, activities, last_state_only):
+        """
+        Sets the GVT of this coupled model
+
+        :param gvt: the time to which the GVT should be set
+        :param activities: dictionary containing all activities for the models
+        :param last_state_only: whether or not to use the last state for activity
+        """
+        for i in self.component_set:
+            i.setGVT(gvt, activities, last_state_only)
+
+    def fetchActivity(self, time, activities):
+        """
+        Fetch the activity of the model up to a certain time
+
+        :param time: the time up to which the activity should be calculated
+        :param activities: dictionary containing all activities for the models
+        """
+        for i in self.component_set:
+            i.fetchActivity(time, activities)
+
+    def revert(self, time, memorize):
+        """
+        Revert the coupled model to the specified time, all submodels will also
+        be reverted.
+
+        :param time: the time up to which revertion should happen
+        :param memorize: whether or not the saved states should still be kept for memoization
+        """
+        reschedules = set()
+        controller_revert = False
+        for child in self.component_set:
+            if child.time_last >= time:
+                controller_revert |= child.revert(time, memorize)
+                # Was reverted, so reschedule
+                reschedules.add(child)
+            # Always clear the inputs, as it is possible that there are only 
+            # partial results, which doesn't get found in the time_last >= time
+            child.my_input = {}
+        self.scheduler.massReschedule(reschedules)
+        self.setTimeNext()
+        return controller_revert
+
+    def setTimeNext(self):
+        """
+        Reset the timeNext
+        """
+        try:
+            self.time_next = self.scheduler.readFirst()
+        except IndexError:
+            # No element found in the scheduler, so put it to INFINITY
+            self.time_next = (float('inf'), 1)
+
+class Port(object):
+    """
+    Class for DEVS model ports (both input and output). This class provides basic port attributes and query methods.
+    """
+    def __init__(self, is_input, name=None):
+        """
+        Constructor. Creates an input port if isInput evaluates to True, and
+        an output port otherwise.
+
+        :param is_input: whether or not this is an input port
+        :param name: the name of the port. If None is provided, a unique ID is generated
+        """
+        self.inline = [] 
+        self.outline = []
+        self.host_DEVS = None 
+        self.msg_count = 0
+   
+        # The name of the port
+        self.name = name
+        self.is_input = is_input
+        self.z_functions = {}
+    
+    def __str__(self):
+        try:
+            return self.getPortFullName()
+        except:
+            return "%s.%s" % (self.host_DEVS.getModelName(), self.getPortName())
+
+    def getPortName(self):
+        """
+        Returns the name of the port
+
+        :returns: local name of the port
+        """
+        return self.name
+
+    def getPortFullName(self):
+        """
+        Returns the complete name of the port
+
+        :returns: fully qualified name of the port
+        """
+        return "%s.%s" % (self.host_DEVS.getModelFullName(), self.getPortName())
+
+    def type(self):
+        """
+        Returns the 'type' of the object
+
+        :returns: either 'INPORT' or 'OUTPORT'
+        """
+        if self.is_input:
+            return 'INPORT'
+        else:
+            return 'OUTPORT'
+
+def appendZ(first_z, new_z):
+    if first_z is None:
+        return new_z
+    elif new_z is None:
+        return first_z
+    else:
+        return lambda x: new_z(first_z(x))
+
+class ExternalWrapper(AtomicDEVS):
+    def __init__(self, function):
+        AtomicDEVS.__init__(self, "Fake")
+        self.f = function
+        self.model_id = None
+        self.full_name = None
+
+    def extTransition(self, inputs):
+        # Fake object is created with a single fake port, so unpack that
+        self.f(self.my_input.values()[0])
+
+def directConnectPort(outport, listeners):
+    # The new contents of the line
+    outport.routing_outline = []
+    worklist = [(p, outport.z_functions.get(p, None)) 
+                for p in outport.outline]
+    for outline, z in worklist:
+        if outline in listeners.keys():
+            # This port is being listened on, so just add it as a fake model
+            fake_port = Port(is_input=False,name="Fake")
+            fake_port.host_DEVS = ExternalWrapper(listeners[outline])
+            outport.routing_outline.append((fake_port, z))
+
+        # If it is a coupled model, we must expand this model
+        if isinstance(outline.host_DEVS, CoupledDEVS):
+            for inline in outline.outline:
+                # Add it to the current iterating list, so we can just continue
+                entry = (inline, appendZ(z, outline.z_functions.get(inline, None)))
+                worklist.append(entry)
+                # If it is a Coupled model, we should just continue 
+                # expanding it and not add it to the finished line
+                if not isinstance(inline.host_DEVS, CoupledDEVS):
+                    entry = (inline, appendZ(z, outline.z_functions.get(inline, None)))
+                    outport.routing_outline.append(entry)
+        else:
+            for ol, z in outport.routing_outline:
+                if ol == outline:
+                    break
+            else:
+                # Add to the new line if it isn't already there
+                # Note that it isn't really mandatory to check for this, 
+                # it is a lot cleaner to do so.
+                # This will greatly increase the complexity of the connector though
+                outport.routing_outline.append((outline, z))
+
+def directConnect(component_set, listeners):
+    """
+    Perform direct connection on this CoupledDEVS model
+
+    :param component_set: the iterable to direct connect
+    :returns: the direct connected component_set
+    """
+    new_list = []
+    # Search for root model
+    root = component_set[0]
+    while root.parent is not None:
+        root = root.parent
+
+    component_set = [root]
+    for i in component_set:
+        if isinstance(i, CoupledDEVS):
+            component_set.extend(i.component_set)
+        else:
+            # Found an atomic model
+            new_list.append(i)
+
+    # Also perform direct connection on all ports of the Coupled DEVS models, should injection ever be wanted
+    for i in component_set:
+        # Remap the output ports
+        for outport in i.OPorts:
+            directConnectPort(outport, listeners)
+
+        if isinstance(i, CoupledDEVS):
+            for inport in i.IPorts:
+                directConnectPort(inport, listeners)
+
+    return new_list

+ 0 - 0
debugging_environment/pypdevs/__init__.py


+ 68 - 0
debugging_environment/pypdevs/classicDEVSWrapper.py

@@ -0,0 +1,68 @@
+# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at 
+# McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
+# 
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#    http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""
+A wrapper for AtomicDEVS models that are to be interpreted as Classic DEVS models
+"""
+
+class ClassicDEVSWrapper(object):
+    """
+    Wraps around a normal AtomicDEVS model and intercepts the DEVS specific functions. All attribute read/writes need to be redirected to the model itself.
+    """
+    def __init__(self, model):
+        """
+        Constructor
+
+        :param model: the model to wrap around
+        """
+        self.model = model
+
+    def __getattr__(self, attr):
+        """
+        Fetches the attributes of the model. This is a 'magic' function.
+
+        :param attr: the attribute to fetch
+        :returns: the fetched attributed
+        """
+        return getattr(self.model, attr)
+
+    def __setattr__(self, attr, val):
+        """
+        Sets the attribute of the model. This is a 'magic' function. Only the 'model' attribute is not proxied!
+
+        :param attr: the attribute to set
+        :param val: the value to set it to
+        """
+        if attr == "model":
+            object.__setattr__(self, attr, val)
+        return setattr(self.model, attr, val)
+
+    def extTransition(self, inputs):
+        """
+        Wrap around the extTransition function by changing the input dictionary
+
+        :param inputs: the input dictionary with lists as values
+        :returns: the new state, as the normal extTransition method would do
+        """
+        return self.model.extTransition({i: inputs[i][0] for i in inputs})
+
+    def outputFnc(self):
+        """
+        Wrap around the outputFnc function by changing the returned dictionary
+
+        :returns: the changed dictionary
+        """
+        retval = self.model.outputFnc()
+        return {i: [retval[i]] for i in retval}

+ 17 - 0
debugging_environment/pypdevs/devsexception.py

@@ -0,0 +1,17 @@
+class DEVSException(Exception):
+    """
+    DEVS specific exceptions
+    """
+    def __init__(self, message="not specified in source"):
+        """
+        Constructor
+
+        :param message: error message to print
+        """
+        Exception.__init__(self, message)
+
+    def __str__(self):
+        """
+        String representation of the exception
+        """
+        return "DEVS Exception: " + str(self.message)

+ 1 - 0
debugging_environment/pypdevs/infinity.py

@@ -0,0 +1 @@
+INFINITY = float('inf')

File diff suppressed because it is too large
+ 1930 - 0
debugging_environment/pypdevs/sccd.py


File diff suppressed because it is too large
+ 1086 - 0
debugging_environment/pypdevs/sccd.xml


+ 835 - 0
debugging_environment/pypdevs/sccd_classic.xml

@@ -0,0 +1,835 @@
+<?xml version="1.0" ?>
+<diagram author="Yentl Van Tendeloo" name="DEVS simulator">
+    <description>
+        A restricted PythonPDEVS simulator modelled in SCCD for classic, dynamic structure DEVS models.
+    </description>
+    <top>
+        import cPickle as pickle
+        import time
+
+        # We basically just interface with the basesimulator
+        from scheduler import Scheduler
+        from DEVS import directConnect, CoupledDEVS, AtomicDEVS, RootDEVS
+        from classicDEVSWrapper import ClassicDEVSWrapper
+        from tracer import trace
+
+        class Breakpoint(object):
+            def __init__(self, breakpoint_id, function, enabled, disable_on_trigger):
+                self.id = breakpoint_id
+                self.function = function
+                self.enabled = enabled
+                self.disable_on_trigger = disable_on_trigger
+    </top>
+    <inport name="request"/>
+    <outport name="reply"/>
+    <class name="SCCDSimulator" default="true">
+        <!-- Define the constructor, taking the model to simulate as a parameter -->
+        <constructor>
+            <parameter name="model"/>
+            <body>
+                <![CDATA[
+                # Simulation variables
+                self.termination_time = None
+                self.termination_condition = None
+                self.simulation_time = (0.0, 0)
+                self.model = model
+                self.listeners = {}
+                self.root_model = model
+                self.realtime_scale = 1.0
+
+                # Values to be set during simulation
+                self.realtime_starttime = None
+                self.inject_queue = []
+
+                # Model initialization
+                self.model_ids = []
+                self.model.finalize(name="", model_counter=0, model_ids=self.model_ids, locations={None: []}, select_hierarchy=[])
+
+                # Direct connection
+                if isinstance(self.model, CoupledDEVS):
+                    self.model.component_set = directConnect(self.model.component_set, self.listeners)
+                    self.model = RootDEVS(self.model.component_set, self.model.component_set, None)
+                    for m in self.model.component_set:
+                        m.timeLast = (-m.elapsed, 1)
+                        ta = m.timeAdvance()
+                        m.time_next = (m.timeLast[0] + ta, 1)
+                        m.old_states = [(m.timeLast, pickle.dumps(m.state))]
+                elif isinstance(self.model, AtomicDEVS):
+                    for p in self.model.IPorts:
+                        p.routing_inline = []
+                        p.routing_outline = []
+                    for p in self.model.OPorts:
+                        p.routing_inline = []
+                        p.routing_outline = []
+                    self.model = RootDEVS([self.model], [self.model], None)
+                    self.model.timeLast = (-self.model.elapsed, 1)
+                    ta = self.model.timeAdvance()
+                    self.model.time_next = (self.model.timeLast[0] + ta, 1)
+
+                # Fixed configuration options
+                self.model.scheduler = Scheduler(self.model.component_set, 1e-6, len(self.model.component_set))
+                self.time_next = self.model.scheduler.readFirst()
+
+                # Cached values
+                self.imminents = None
+                self.outbag = None
+                self.inbags = None
+                self.transitioning = None
+                self.new_states = None
+                self.new_tn = None
+
+                # Verbose trace file
+                self.trace_file = None
+
+                # Breakpoint management
+                self.breakpoints = []
+
+                # For a reset
+                self.save_model = {model: (model.elapsed, pickle.dumps(model.state, pickle.HIGHEST_PROTOCOL)) for model in self.model.component_set}
+                self.transition_times = []
+
+                ]]>
+            </body>
+        </constructor>
+        <!-- Serialize the output values in something human-readable instead of internal objects.
+             Note that this doesn't alter the internal structure, as that is still used for simulation. -->
+        <method name="serialize">
+            <parameter name="type"/>
+            <parameter name="object"/>
+            <body>
+                <![CDATA[
+                if type == "imminents":
+                    return [m.getModelFullName() for m in object]
+                elif type == "imminent":
+                    return object.getModelFullName()
+                elif type == "inbags" or type == "outbag":
+                    return {m.getPortFullName(): object[m] for m in object}
+                elif type == "new_tn" or type == "new_states":
+                    return {m.getModelFullName(): object[m] for m in object}
+                elif type == "transitioning":
+                    return {m.getModelFullName(): {1: "INTERNAL", 2: "EXTERNAL"}[object[m]] for m in object}
+                ]]>
+            </body>
+        </method>
+        <!-- Find a port based on a fully qualified name. -->
+        <method name="find_port_with_name">
+            <parameter name="name"/>
+            <body>
+                <![CDATA[
+                for model in self.model.component_set:
+                    if name.startswith(model.getModelFullName()):
+                        # Found a potential model
+                        # We can't simply check for equality, as portnames might contain dots too
+                        for port in model.IPorts:
+                            if port.getPortFullName() == name:
+                                # Now everything matches
+                                return port
+                # Nothing found
+                return None
+                ]]>
+            </body>
+        </method>
+        <!-- Find a model based on a fully qualified name. -->
+        <method name="find_model_with_name">
+            <parameter name="name"/>
+            <body>
+                <![CDATA[
+                for model in self.model.component_set:
+                    if name == model.getModelFullName():
+                        # Found exact match
+                        return model
+                return None
+                ]]>
+            </body>
+        </method>
+        <!-- Calculate the time to wait before triggering the next transition.
+             This method is also called in non-realtime simulation, so make sure that it returns infinity in that case. -->
+        <method name="calculate_after">
+            <body>
+                <![CDATA[
+                try:
+                    # Process in parts of 100 milliseconds to repeatedly check the termination condition
+                    nexttime = (self.time_next[0] - (time.time() - self.realtime_starttime) / self.realtime_scale) * self.realtime_scale
+                    x =  min(0.1, nexttime)
+                    return x
+                except TypeError, AttributeError:
+                    # We are probably not simulating in realtime...
+                    return float('inf')
+                ]]>
+            </body>
+        </method>
+        <!-- Parse a list of options that can be passed together with the request -->
+        <method name="parse_options">
+            <parameter name="configuration"/>
+            <body>
+                <![CDATA[
+                self.termination_condition = None if "termination_condition" not in configuration else configuration["termination_condition"]
+                self.termination_time = None if "termination_time" not in configuration else configuration["termination_time"]
+                self.realtime_scale = 1.0 if "realtime_scale" not in configuration else 1.0/configuration["realtime_scale"]
+                # Subtract the current simulation time to allow for pausing
+                self.realtime_starttime = (time.time() - self.simulation_time[0]*self.realtime_scale)
+                # Reset the time used in the waiting, as it might not get recomputed
+                self.the_time = 0.00001
+                ]]>
+            </body>
+        </method>
+        <!-- Utility function to determine whether or not simulation is finished. -->
+        <method name="should_terminate">
+            <parameter name="realtime"/>
+            <body>
+                <![CDATA[
+                # Now that it includes breakpoints, results are to be interpretted as follows:
+                # -2 --> continue simulation
+                # -1 --> termination condition
+                # else --> breakpoint
+
+                if realtime:
+                    check_time = self.simulation_time
+                else:
+                    self.compute_timeNext()
+                    check_time = self.time_next
+
+                # Just access the 'transitioned' dictionary
+                # Kind of dirty though...
+                if self.transitioning is None:
+                    transitioned = set()
+                else:
+                    transitioned = set(self.transitioning.keys())
+
+                if check_time[0] == float('inf'):
+                    # Always terminate if we have reached infinity
+                    terminate = True
+                elif self.termination_condition is not None:
+                    terminate = self.termination_condition(check_time, self.root_model, transitioned)
+                else:
+                    terminate = self.termination_time < check_time[0]
+
+                if terminate:
+                    # Always terminate, so don't check breakpoints
+                    return -1
+                else:
+                    # Have to check breakpoints for termination
+                    for bp in self.breakpoints:
+                        if not bp.enabled:
+                            continue
+                        # Include the function in the scope
+                        exec(bp.function)
+                        # And execute it, note that the breakpoint thus has to start with "def breakpoint("
+                        if breakpoint(check_time, self.root_model, transitioned):
+                            # Triggered!
+                            return bp.id
+                        else:
+                            # Not triggered, so continue
+                            continue
+                    return -2
+                ]]>
+            </body>
+        </method>
+        <!-- Compute all models of which the internal transition function has to be triggered. -->
+        <method name="find_internal_imminents">
+            <body>
+                <![CDATA[
+                self.imminents = self.model.scheduler.getImminent(self.simulation_time)
+                self.reschedule = set(self.imminents)
+                self.transition_times.append(self.simulation_time)
+                for model in self.imminents:
+                    model.time_next = (model.time_next[0], model.time_next[1] + 1)
+                ]]>
+            </body>
+        </method>
+        <!-- Select one of the imminent components -->
+        <method name="select_imminent">
+            <body>
+                <![CDATA[
+                self.imminent = None
+                if len(self.imminents) > 1:
+                    # Perform all selects
+                    self.imminents.sort()
+                    pending = self.imminents
+                    level = 1
+                    while len(pending) > 1:
+                        # Take the model each time, as we need to make sure that the selectHierarchy is valid everywhere
+                        model = pending[0]
+                        # Make a set first to remove duplicates
+                        colliding = list(set([m.select_hierarchy[level] for m in pending]))
+                        chosen = model.select_hierarchy[level-1].select(
+                                sorted(colliding, key=lambda i:i.getModelFullName()))
+                        pending = [m for m in pending 
+                                     if m.select_hierarchy[level] == chosen]
+                        level += 1
+                    self.imminent = pending[0]
+                else:
+                    self.imminent = self.imminents[0]
+                self.imminent.time_next = (self.imminent.time_next[0], self.imminent.time_next[1] - 1)
+                ]]>
+            </body>
+        </method>
+        <!-- Trigger all output functions of imminent models. -->
+        <method name="compute_outputfunction">
+            <body>
+                <![CDATA[
+                self.outbag = ClassicDEVSWrapper(self.imminent).outputFnc()
+                ]]>
+            </body>
+        </method>
+        <!-- Route all messages and apply the required transfer functions. -->
+        <method name="route_messages">
+            <body>
+                <![CDATA[
+                self.inbags = {}
+                for outport in self.outbag:
+                    payload = self.outbag[outport]
+                    for inport, z in outport.routing_outline:
+                        if z is not None:
+                            payload = [z(pickle.loads(pickle.dumps(m))) for m in payload]
+                        self.inbags.setdefault(inport, []).extend(payload)
+                ]]>
+            </body>
+        </method>
+        <!-- Process the injects on the inject_queue.
+             TODO: What about events injected on a port which already has an event, or on a time at which a transition was scheduled? Should this be seen as a separate component that needs priority? -->
+        <method name="process_injects">
+            <body>
+                <![CDATA[
+                while self.inject_queue:
+                    if self.inject_queue[0]["time"] > self.simulation_time:
+                        break
+                    config = self.inject_queue.pop(0)
+                    portname = config["port"]
+                    event = config["event"]
+                    port = self.find_port_with_name(portname)
+                    self.inbags.setdefault(port, []).append(event)
+                ]]>
+            </body>
+        </method>
+        <!-- Combine the information from the routed messages to determine the external, internal and confluent transition functions to trigger. -->
+        <method name="find_all_imminents">
+            <body>
+                <![CDATA[
+                # Internal codes:
+                #   1 --> internal transition
+                #   2 --> external transition
+                #   3 --> confluent transition
+                # These codes are a legacy of efficient PyPDEVS, but is kept here for consistency
+                self.transitioning = {self.imminent: 1}
+                for inport in self.inbags:
+                    aDEVS = inport.host_DEVS
+                    aDEVS.my_input[inport] = self.inbags[inport]
+                    self.transitioning[aDEVS] = 2
+                    self.reschedule.add(aDEVS)
+                self.transitioning = {ClassicDEVSWrapper(m): self.transitioning[m] 
+                                      for m in self.transitioning}
+                ]]>
+            </body>
+        </method>
+        <!-- Trigger all transition functions. -->
+        <method name="compute_transitions">
+            <body>
+                <![CDATA[
+                self.new_states = {}
+                for aDEVS in self.transitioning:
+                    aDEVS.my_input = {key: pickle.loads(pickle.dumps(aDEVS.my_input[key], pickle.HIGHEST_PROTOCOL)) for key in aDEVS.my_input}
+                    if self.transitioning[aDEVS] == 1:
+                        aDEVS.state = aDEVS.intTransition()
+                    elif self.transitioning[aDEVS] == 2:
+                        aDEVS.elapsed = self.simulation_time[0] - aDEVS.timeLast[0]
+                        aDEVS.state = aDEVS.extTransition(aDEVS.my_input)
+                    aDEVS.old_states.append((self.simulation_time, pickle.dumps(aDEVS.state)))
+                    aDEVS.my_input = {}
+                    self.new_states[aDEVS] = aDEVS.state
+                ]]>
+            </body>
+        </method>
+        <!-- Trigger all timeAdvance functions. -->
+        <method name="compute_ta">
+            <body>
+                <![CDATA[
+                self.new_tn = {}
+                t, age = self.simulation_time
+                for aDEVS in self.transitioning:
+                    ta = aDEVS.timeAdvance()
+                    aDEVS.timeLast = self.simulation_time
+                    aDEVS.time_next = (t + ta, 1 if ta else (age + 1))
+                    self.new_tn[aDEVS] = aDEVS.time_next
+                    trace(self.trace_file, self.transitioning[aDEVS], aDEVS)
+                self.model.scheduler.massReschedule(self.reschedule)
+                self.time_next = self.model.scheduler.readFirst()
+                ]]>
+            </body>
+        </method>
+        <method name="flush_file">
+            <body>
+                <![CDATA[
+                if self.trace_file is not None:
+                    self.trace_file.flush()
+                ]]>
+            </body>
+        </method>
+        <method name="process_breakpoints">
+            <parameter name="realtime"/>
+            <body>
+                <![CDATA[
+                breakpoint_id = self.should_terminate(realtime)
+                for breakpoint in self.breakpoints:
+                    if breakpoint.id == breakpoint_id:
+                        if breakpoint.disable_on_trigger:
+                            breakpoint.enabled = False
+                        return breakpoint_id
+                ]]>
+            </body>
+        </method>
+        <method name="compute_timeNext">
+            <body>
+                <![CDATA[
+                model_timeNext = self.model.scheduler.readFirst()
+                if len(self.inject_queue) > 0:
+                    self.time_next = min(model_timeNext, self.inject_queue[0]["time"])
+                else:
+                    self.time_next = model_timeNext
+                ]]>
+            </body>
+        </method>
+        <method name="rollback_step">
+            <body>
+                <![CDATA[
+                    if len(self.transition_times) == 0:
+                        return
+                    new_time = self.transition_times.pop()
+                    for model in self.model.component_set:
+                        if model.old_states[-1][0] == new_time:
+                            # Remove the current state
+                            del model.old_states[-1]
+                            # Set the new (old...) state
+                            new_state = model.old_states[-1]
+                            model.state = pickle.loads(new_state[1])
+                            model.timeLast = new_state[0]
+                            ta = model.timeAdvance()
+                            model.time_next = (model.timeLast[0] + ta, model.timeLast[1] + 1 if ta == 0 else 0)
+                            self.model.scheduler.massReschedule([model])
+                    self.simulation_time = self.transition_times[-1] if len(self.transition_times) > 0 else (0.0, 0)
+                ]]>
+            </body>
+        </method>
+        <scxml initial="main">
+            <!-- Parallel states: one of them controls the simulation flow, the other the type of simulation being performed. -->
+            <parallel id="main">
+                <!-- When an injection is received, just append it to the list of pending injections.
+                     These will be processed as soon as the current simulation step is finished.
+                     Afterwards, return to the previous state, as there was no change of state. -->
+                <state id="injection_monitor">
+                    <state id="inject">
+                        <transition port="request" event="inject" target=".">
+                            <parameter name="configuration"/>
+                            <script>
+                                configuration["time"] = (configuration["time"], 1)
+                                self.inject_queue.append(configuration)
+                                self.inject_queue.sort(key=lambda i: i["time"])
+                            </script>
+                            <raise scope="output" port="reply" event="inject_ok"/>
+                        </transition>
+                    </state>
+                </state>
+                <state id="tracer_monitor">
+                    <state id="trace">
+                        <transition port="request" event="trace" target=".">
+                            <parameter name="filename"/>
+                            <script>
+                                if filename is not None:
+                                    self.trace_file = open(filename, 'w')
+                                else:
+                                    self.trace_file = None
+                            </script>
+                            <raise scope="output" port="reply" event="trace_config_ok"/>
+                        </transition>
+                    </state>
+                </state>
+                <!-- The main parallel component: the simulation flow. -->
+                <state id="simulation_flow" initial="initialize">
+                    <state id="initialize">
+                        <transition target="../check_termination">
+                            <raise scope="output" port="reply" event="all_states">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="{m.getModelFullName(): (m.time_next, m.state) for m in self.model.component_set}"/>
+                            </raise>
+                        </transition>
+                    </state>
+                    <state id="check_termination" initial="workaround">
+                        <onexit>
+                            <script>
+                                self.simulation_time = self.time_next
+                            </script>
+                        </onexit>
+
+                        <state id="workaround">
+                            <transition after="0" target="../check_termination"/>
+                        </state>
+
+                        <state id="wait">
+                            <onexit>
+                                <script>
+                                    diff = time.time() - self.realtime_starttime
+                                    self.simulation_time = (diff / self.realtime_scale, 1)
+                                </script>
+                            </onexit>
+                            <transition after="self.calculate_after()" target="../check_termination"/>
+                            <transition cond="INSTATE('../../../simulation_state/paused')" target="../check_termination"/>
+                        </state>
+
+                        <state id="small_step_check">
+                            <transition cond="self.should_terminate(False) == -2" target="../../do_simulation"/>
+                            <transition cond="self.should_terminate(False) == -1" target="../check_termination">
+                                <raise event="termination_condition"/>
+                            </transition>
+                            <transition cond="self.should_terminate(False) &gt; -1" target="../check_termination">
+                                <script>
+                                    breakpoint_id = self.process_breakpoints(False)
+                                </script>
+                                <raise scope="output" port="reply" event="breakpoint_triggered">
+                                    <parameter expr="breakpoint_id"/>
+                                </raise>
+                                <raise event="termination_condition"/>
+                            </transition>
+                        </state>
+
+                        <state id="check_termination">
+                            <onentry>
+                                <script>
+                                    self.compute_timeNext()
+                                    self.the_time = self.calculate_after()
+                                </script>
+                            </onentry>
+                            <!-- Continue simulation -->
+                            <transition cond="INSTATE('../../../simulation_state/continuous') and (self.should_terminate(False) == -2)" target="../../do_simulation"/>
+                            <transition cond="INSTATE('../../../simulation_state/big_step') and (self.should_terminate(False) == -2)" target="../../do_simulation"/>
+
+                            <!-- Realtime and didn't reach the required time_next yet -->
+                            <transition cond="INSTATE('../../../simulation_state/realtime') and (self.should_terminate(True) == -2) and (self.the_time &gt; 0.0)" target="../wait"/>
+
+                            <transition cond="INSTATE('../../../simulation_state/realtime') and (self.should_terminate(True) == -2) and (self.the_time &lt;= 0.0)" target="../../do_simulation"/>
+
+                            <transition port="request" event="small_step" target="../small_step_check">
+                                <parameter name="configuration" type="dict" default="{}"/>
+                                <script>
+                                    self.parse_options(configuration)
+                                </script>
+                            </transition>
+
+                            <!-- Pause simulation -->
+                            <transition cond="(not INSTATE('../../../simulation_state/paused') and INSTATE('../../../simulation_state/realtime') and (self.should_terminate(True) == -1))" target="../workaround">
+                                <raise event="termination_condition"/>
+                            </transition>
+                            <transition cond="(not INSTATE('../../../simulation_state/paused') and not INSTATE('../../../simulation_state/realtime') and (self.should_terminate(False) == -1))" target="../workaround">
+                                <raise event="termination_condition"/>
+                            </transition>
+                            <transition cond="(not INSTATE('../../../simulation_state/paused')) and INSTATE('../../../simulation_state/realtime') and (self.should_terminate(True) &gt; -1)" target="../workaround">
+                                <script>
+                                    breakpoint_id = self.process_breakpoints(True)
+                                </script>
+                                <raise scope="output" port="reply" event="breakpoint_triggered">
+                                    <parameter expr="breakpoint_id"/>
+                                </raise>
+                                <raise event="termination_condition"/>
+                            </transition>
+                            <transition cond="(not INSTATE('../../../simulation_state/paused')) and not INSTATE('../../../simulation_state/realtime') and (self.should_terminate(False) &gt; -1)" target="../workaround">
+                                <script>
+                                    breakpoint_id = self.process_breakpoints(False)
+                                </script>
+                                <raise scope="output" port="reply" event="breakpoint_triggered">
+                                    <parameter expr="breakpoint_id"/>
+                                </raise>
+                                <raise event="termination_condition"/>
+                            </transition>
+
+                            <!-- Process god event -->
+                            <transition cond="INSTATE('../../../simulation_state/paused')" port="request" event="god_event" target="../workaround">
+                                <parameter name="configuration"/>
+                                <script>
+                                    modelname = configuration["model"]
+                                    state_attribute = configuration["attribute"]
+                                    new_value = configuration["value"]
+                                    model = self.find_model_with_name(modelname)
+                                    setattr(model.state, state_attribute, new_value)
+                                    # Call the timeadvance method again and compute new ta
+                                    ta = model.timeAdvance()
+                                    model.time_next = (model.timeLast[0] + ta, 1 if ta else (model.timeLast[1] + 1))
+                                    self.model.scheduler.massReschedule([model])
+                                    # self.simulation_time = self.model.scheduler.readFirst()
+                                </script>
+                                <raise scope="output" port="reply" event="god_event_ok">
+                                    <parameter expr="{model.getModelFullName(): str(model.state)}"/>
+                                </raise>
+                                <raise scope="output" port="reply" event="new_tn">
+									<parameter expr="self.simulation_time"/>
+                                    <parameter expr="{model.getModelFullName(): model.time_next}"/>
+                                </raise>
+                            </transition>
+
+                            <!-- Omniscient debugging -->
+                            <transition cond="INSTATE('../../../simulation_state/paused')" port="request" event="backwards_step" target="../workaround">
+                                <script>
+                                    self.rollback_step()
+                                </script>
+                                <raise scope="output" port="reply" event="all_states">
+                                    <parameter expr="self.simulation_time"/>
+                                    <parameter expr="{m.getModelFullName(): (m.time_next, m.state) for m in self.model.component_set}"/>
+                                </raise>
+                            </transition>
+
+                        </state>
+                    </state>
+
+                    <state id="do_simulation" initial="init">
+                    <state id="init">
+                        <onexit>
+                            <script>
+                                self.find_internal_imminents()
+                            </script>
+                        </onexit>
+                        <transition cond="not INSTATE('../../../simulation_state/paused')" target="../found_internal_imminents"/>
+                        <!-- Always output this if paused, as we only got here because a small step was fired previously -->
+                        <transition cond="INSTATE('../../../simulation_state/paused')" target="../found_internal_imminents">
+                            <raise scope="output" port="reply" event="imminents">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('imminents', self.imminents)"/>
+                            </raise>
+                        </transition>
+                    </state>
+
+                    <state id="found_internal_imminents">
+                        <onexit>
+                            <script>
+                                self.select_imminent()
+                            </script>
+                        </onexit>
+                        <transition cond="not INSTATE('../../../simulation_state/paused')" target="../selected_imminent"/>
+                        <transition port="request" event="small_step" target="../selected_imminent">
+                            <raise scope="output" port="reply" event="selected_imminent">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('imminent', self.imminent)"/>
+                            </raise>
+                        </transition>
+                    </state>
+
+                    <state id="selected_imminent">
+                        <onexit>
+                            <script>
+                                self.compute_outputfunction()
+                            </script>
+                        </onexit>
+                        <transition cond="not INSTATE('../../../simulation_state/paused')" target="../computed_outputfunction"/>
+                        <transition port="request" event="small_step" target="../computed_outputfunction">
+                            <raise scope="output" port="reply" event="outbag">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('outbag', self.outbag)"/>
+                            </raise>
+                        </transition>
+                    </state>
+
+                    <state id="computed_outputfunction">
+                        <onexit>
+                            <script>
+                                self.route_messages()
+                                self.process_injects()
+                            </script>
+                        </onexit>
+                        <transition cond="not INSTATE('../../../simulation_state/paused')" target="../routed_messages">
+                        </transition>
+                        <transition port="request" event="small_step" target="../routed_messages">
+                            <raise scope="output" port="reply" event="inbags">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('inbags', self.inbags)"/>
+                            </raise>
+                        </transition>
+                    </state>
+
+                    <state id="routed_messages">
+                        <onexit>
+                            <script>
+                                self.find_all_imminents()
+                            </script>
+                        </onexit>
+                        <transition cond="not INSTATE('../../../simulation_state/paused')" target="../found_all_imminents">
+                        </transition>
+                        <transition port="request" event="small_step" target="../found_all_imminents">
+                            <raise scope="output" port="reply" event="transitioning">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('transitioning', self.transitioning)"/>
+                            </raise>
+                        </transition>
+                    </state>
+
+                    <state id="found_all_imminents">
+                        <onexit>
+                            <script>
+                                self.compute_transitions()
+                            </script>
+                        </onexit>
+                        <transition cond="not INSTATE('../../../simulation_state/paused')" target="../computed_transitions"/>
+                        <transition port="request" event="small_step" target="../computed_transitions">
+                            <raise scope="output" port="reply" event="new_states">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('new_states', self.new_states)"/>
+                            </raise>
+                        </transition>
+                    </state>
+
+                    <state id="computed_transitions">
+                        <onexit>
+                            <script>
+                                self.compute_ta()
+                            </script>
+                        </onexit>
+                        <transition cond="INSTATE('../../../simulation_state/continuous')" target="../../check_termination"/>
+                        <transition port="request" event="small_step" target="../../check_termination">
+                            <raise scope="output" port="reply" event="new_tn">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('new_tn', self.new_tn)"/>
+                            </raise>
+                        </transition>
+                        <transition cond="INSTATE('../../../simulation_state/realtime') or INSTATE('../../../simulation_state/big_step')" target="../../check_termination">
+                            <raise event="big_step_done"/>
+                            <raise scope="output" port="reply" event="new_states">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('new_states', self.new_states)"/>
+                            </raise>
+                            <raise scope="output" port="reply" event="new_tn">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('new_tn', self.new_tn)"/>
+                            </raise>
+                        </transition>
+                    </state>
+                    </state>
+                </state>
+
+                <state id="simulation_state" initial="paused">
+                    <state id="paused">
+                        <transition port="request" event="simulate" target="../continuous">
+                            <parameter name="configuration" type="dict" default="{}"/>
+                            <script>
+                                self.parse_options(configuration)
+                            </script>
+                        </transition>
+                        <transition port="request" event="realtime" target="../realtime">
+                            <parameter name="configuration" type="dict" default="{}"/>
+                            <script>
+                                self.parse_options(configuration)
+                            </script>
+                        </transition>
+                        <transition port="request" event="big_step" target="../big_step">
+                            <parameter name="configuration" type="dict" default="{}"/>
+                            <script>
+                                self.parse_options(configuration)
+                            </script>
+                        </transition>
+                    </state>
+                    <state id="continuous">
+                            <transition port="request" event="pause" target=".">
+                                <script>
+                                    # Just override termination condition
+                                    self.termination_condition = lambda i, j, k : True
+                                    self.termination_time = None
+                                </script>
+                            </transition>
+                            <transition event="termination_condition" target="../paused">
+                                <raise port="reply" event="terminate">
+                                    <parameter expr="self.simulation_time"/>
+                                </raise>
+                                <script>
+                                    self.flush_file()
+                                </script>
+                                <raise scope="output" port="reply" event="all_states">
+                                    <parameter expr="self.simulation_time"/>
+                                    <parameter expr="{m.getModelFullName(): (m.time_next, m.state) for m in self.model.component_set}"/>
+                                </raise>
+                            </transition>
+                    </state>
+                    <state id="realtime">
+                            <transition port="request" event="pause" target=".">
+                                <script>
+                                    # Just override termination condition
+                                    self.termination_condition = lambda i, j, k : True
+                                    self.termination_time = None
+
+                                    # Don't forget to correctly set the simulation time
+                                    diff = time.time() - self.realtime_starttime
+                                    self.simulation_time = (diff / self.realtime_scale, 1)
+                                </script>
+                            </transition>
+                            <transition event="termination_condition" target="../paused">
+                                <raise port="reply" event="terminate">
+                                    <parameter expr="self.simulation_time"/>
+                                </raise>
+                                <script>
+                                    self.flush_file()
+                                </script>
+                            </transition>
+                    </state>
+                    <state id="big_step">
+                            <transition event="big_step_done" target="../paused"/>
+                            <transition event="termination_condition" target="../paused">
+                                <raise port="reply" event="terminate">
+                                    <parameter expr="self.simulation_time"/>
+                                </raise>
+                                <script>
+                                    self.flush_file()
+                                </script>
+                            </transition>
+                    </state>
+                </state>
+                <state id="breakpoint_manager">
+                    <state id="breakpoint_manage">
+                        <transition port="request" event="add_breakpoint" target=".">
+                            <parameter name="breakpoint_id"/>
+                            <parameter name="function"/>
+                            <parameter name="enabled"/>
+                            <parameter name="disable_on_trigger"/>
+                            <script>
+                                self.breakpoints.append(Breakpoint(breakpoint_id, function, enabled, disable_on_trigger))
+                            </script>
+                        </transition>
+                        <transition port="request" event="del_breakpoint" target=".">
+                            <parameter name="del_breakpoint_id"/>
+                            <script>
+                                self.breakpoints = [breakpoint for breakpoint in self.breakpoints if breakpoint.id != del_breakpoint_id]
+                            </script>
+                        </transition>
+                        <transition port="request" event="toggle_breakpoint" target=".">
+                            <parameter name="breakpoint_id"/>
+                            <parameter name="enabled"/>
+                            <script>
+                                for breakpoint in self.breakpoints:
+                                    if breakpoint.id == breakpoint_id:
+                                        breakpoint.enabled = enabled
+                                        break
+                            </script>
+                        </transition>
+                    </state>
+                </state>
+                <state id="reset">
+                    <state id="reset">
+                        <transition port="request" event="reset" target=".">
+                            <script>
+                                for model in self.model.component_set:
+                                    model.state = pickle.loads(self.save_model[model][1])
+                                    model.elapsed = self.save_model[model][0]
+                                    model.timeLast = (-model.elapsed, 1)
+                                    ta = model.timeAdvance()
+                                    model.time_next = (model.timeLast[0] + ta, 1)
+                                self.simulation_time = (0.0, 0)
+                                self.model.scheduler.massReschedule(self.model.component_set)
+
+                                # Reset trace file
+                                if self.trace_file is not None:
+                                    self.trace_file = open(self.trace_file.name, 'w')
+                            </script>
+                            <raise scope="output" port="reply" event="all_states">
+                                <parameter expr="(0.0, 0)"/>
+                                <parameter expr="{m.getModelFullName(): (m.time_next, m.state) for m in self.model.component_set}"/>
+                            </raise>
+                        </transition>
+                    </state>
+                </state>
+            </parallel>
+        </scxml>
+    </class>
+</diagram>

File diff suppressed because it is too large
+ 1082 - 0
debugging_environment/pypdevs/sccd_fixed_reset.xml


+ 791 - 0
debugging_environment/pypdevs/sccd_parallel.xml

@@ -0,0 +1,791 @@
+<?xml version="1.0" ?>
+<diagram author="Yentl Van Tendeloo" name="DEVS simulator">
+    <description>
+        A restricted PythonPDEVS simulator modelled in SCCD for classic, dynamic structure DEVS models.
+    </description>
+    <top>
+        import cPickle as pickle
+        import time
+
+        # We basically just interface with the basesimulator
+        from scheduler import Scheduler
+        from DEVS import directConnect, CoupledDEVS, AtomicDEVS, RootDEVS
+        from tracer import trace
+
+        class Breakpoint(object):
+            def __init__(self, breakpoint_id, function, enabled, disable_on_trigger):
+                self.id = breakpoint_id
+                self.function = function
+                self.enabled = enabled
+                self.disable_on_trigger = disable_on_trigger
+    </top>
+    <inport name="request"/>
+    <outport name="reply"/>
+    <class name="SCCDSimulator" default="true">
+        <!-- Define the constructor, taking the model to simulate as a parameter -->
+        <constructor>
+            <parameter name="model"/>
+            <body>
+                <![CDATA[
+                # Simulation variables
+                self.termination_time = None
+                self.termination_condition = None
+                self.simulation_time = (0.0, 0)
+                self.model = model
+                self.listeners = {}
+                self.root_model = model
+                self.realtime_scale = 1.0
+
+                # Values to be set during simulation
+                self.realtime_starttime = None
+                self.inject_queue = []
+
+                # Model initialization
+                self.model_ids = []
+                self.model.finalize(name="", model_counter=0, model_ids=self.model_ids, locations={None: []}, select_hierarchy=[])
+
+                # Direct connection
+                if isinstance(self.model, CoupledDEVS):
+                    self.model.component_set = directConnect(self.model.component_set, self.listeners)
+                    self.model = RootDEVS(self.model.component_set, self.model.component_set, None)
+                    for m in self.model.component_set:
+                        m.timeLast = (-m.elapsed, 1)
+                        ta = m.timeAdvance()
+                        m.time_next = (m.timeLast[0] + ta, 1)
+                        m.old_states = [(m.timeLast, pickle.dumps(m.state))]
+                elif isinstance(self.model, AtomicDEVS):
+                    for p in self.model.IPorts:
+                        p.routing_inline = []
+                        p.routing_outline = []
+                    for p in self.model.OPorts:
+                        p.routing_inline = []
+                        p.routing_outline = []
+                    self.model = RootDEVS([self.model], [self.model], None)
+                    self.model.timeLast = (-self.model.elapsed, 1)
+                    ta = self.model.timeAdvance()
+                    self.model.time_next = (self.model.timeLast[0] + ta, 1)
+
+                # Fixed configuration options
+                self.model.scheduler = Scheduler(self.model.component_set, 1e-6, len(self.model.component_set))
+                self.time_next = self.model.scheduler.readFirst()
+
+                # Cached values
+                self.imminents = None
+                self.outbags = None
+                self.inbags = None
+                self.transitioning = None
+                self.new_states = None
+                self.new_tn = None
+
+                # Verbose trace file
+                self.trace_file = None
+
+                # Breakpoint management
+                self.breakpoints = []
+
+                # For a reset
+                self.save_model = {model: (model.elapsed, pickle.dumps(model.state, pickle.HIGHEST_PROTOCOL)) for model in self.model.component_set}
+                self.transition_times = []
+
+                ]]>
+            </body>
+        </constructor>
+        <!-- Serialize the output values in something human-readable instead of internal objects.
+             Note that this doesn't alter the internal structure, as that is still used for simulation. -->
+        <method name="serialize">
+            <parameter name="type"/>
+            <parameter name="object"/>
+            <body>
+                <![CDATA[
+                if type == "imminents":
+                    return [m.getModelFullName() for m in object]
+                elif type == "inbags" or type == "outbags":
+                    return {m.getPortFullName(): object[m] for m in object}
+                elif type == "new_tn" or type == "new_states":
+                    return {m.getModelFullName(): object[m] for m in object}
+                elif type == "transitioning":
+                    return {m.getModelFullName(): {1: "INTERNAL", 2: "EXTERNAL", 3: "CONFLUENT"}[object[m]] for m in object}
+                ]]>
+            </body>
+        </method>
+        <!-- Find a port based on a fully qualified name. -->
+        <method name="find_port_with_name">
+            <parameter name="name"/>
+            <body>
+                <![CDATA[
+                for model in self.model.component_set:
+                    if name.startswith(model.getModelFullName()):
+                        # Found a potential model
+                        # We can't simply check for equality, as portnames might contain dots too
+                        for port in model.IPorts:
+                            if port.getPortFullName() == name:
+                                # Now everything matches
+                                return port
+                # Nothing found
+                return None
+                ]]>
+            </body>
+        </method>
+        <!-- Find a model based on a fully qualified name. -->
+        <method name="find_model_with_name">
+            <parameter name="name"/>
+            <body>
+                <![CDATA[
+                for model in self.model.component_set:
+                    if name == model.getModelFullName():
+                        # Found exact match
+                        return model
+                return None
+                ]]>
+            </body>
+        </method>
+        <!-- Calculate the time to wait before triggering the next transition.
+             This method is also called in non-realtime simulation, so make sure that it returns infinity in that case. -->
+        <method name="calculate_after">
+            <body>
+                <![CDATA[
+                try:
+                    # Process in parts of 100 milliseconds to repeatedly check the termination condition
+                    nexttime = (self.time_next[0] - (time.time() - self.realtime_starttime) / self.realtime_scale) * self.realtime_scale
+                    x =  min(0.1, nexttime)
+                    return x
+                except TypeError, AttributeError:
+                    # We are probably not simulating in realtime...
+                    return float('inf')
+                ]]>
+            </body>
+        </method>
+        <!-- Parse a list of options that can be passed together with the request -->
+        <method name="parse_options">
+            <parameter name="configuration"/>
+            <body>
+                <![CDATA[
+                self.termination_condition = None if "termination_condition" not in configuration else configuration["termination_condition"]
+                self.termination_time = None if "termination_time" not in configuration else configuration["termination_time"]
+                self.realtime_scale = 1.0 if "realtime_scale" not in configuration else 1.0/configuration["realtime_scale"]
+                # Subtract the current simulation time to allow for pausing
+                self.realtime_starttime = (time.time() - self.simulation_time[0]*self.realtime_scale)
+                # Reset the time used in the waiting, as it might not get recomputed
+                self.the_time = 0.00001
+                ]]>
+            </body>
+        </method>
+        <!-- Utility function to determine whether or not simulation is finished. -->
+        <method name="should_terminate">
+            <parameter name="realtime"/>
+            <body>
+                <![CDATA[
+                # Now that it includes breakpoints, results are to be interpretted as follows:
+                # -2 --> continue simulation
+                # -1 --> termination condition
+                # else --> breakpoint
+
+                if realtime:
+                    check_time = self.simulation_time
+                else:
+                    self.compute_timeNext()
+                    check_time = self.time_next
+
+                # Just access the 'transitioned' dictionary
+                # Kind of dirty though...
+                if self.transitioning is None:
+                    transitioned = set()
+                else:
+                    transitioned = set(self.transitioning.keys())
+
+                if check_time[0] == float('inf'):
+                    # Always terminate if we have reached infinity
+                    terminate = True
+                elif self.termination_condition is not None:
+                    terminate = self.termination_condition(check_time, self.root_model, transitioned)
+                else:
+                    terminate = self.termination_time < check_time[0]
+
+                if terminate:
+                    # Always terminate, so don't check breakpoints
+                    return -1
+                else:
+                    # Have to check breakpoints for termination
+                    for bp in self.breakpoints:
+                        if not bp.enabled:
+                            continue
+                        # Include the function in the scope
+                        exec(bp.function)
+                        # And execute it, note that the breakpoint thus has to start with "def breakpoint("
+                        if breakpoint(check_time, self.root_model, transitioned):
+                            # Triggered!
+                            return bp.id
+                        else:
+                            # Not triggered, so continue
+                            continue
+                    return -2
+                ]]>
+            </body>
+        </method>
+        <!-- Compute all models of which the internal transition function has to be triggered. -->
+        <method name="find_internal_imminents">
+            <body>
+                <![CDATA[
+                self.imminents = self.model.scheduler.getImminent(self.simulation_time)
+                self.transition_times.append(self.simulation_time)
+                ]]>
+            </body>
+        </method>
+        <!-- Trigger all output functions of imminent models. -->
+        <method name="compute_outputfunction">
+            <body>
+                <![CDATA[
+                self.outbags = {}
+                for model in self.imminents:
+                    self.outbags.update(model.outputFnc())
+                ]]>
+            </body>
+        </method>
+        <!-- Route all messages and apply the required transfer functions. -->
+        <method name="route_messages">
+            <body>
+                <![CDATA[
+                self.inbags = {}
+                for outport in self.outbags:
+                    payload = self.outbags[outport]
+                    for inport, z in outport.routing_outline:
+                        if z is not None:
+                            payload = [z(pickle.loads(pickle.dumps(m))) for m in payload]
+                        self.inbags.setdefault(inport, []).extend(payload)
+                ]]>
+            </body>
+        </method>
+        <!-- Process the injects on the inject_queue. -->
+        <method name="process_injects">
+            <body>
+                <![CDATA[
+                while self.inject_queue:
+                    if self.inject_queue[0]["time"] > self.simulation_time:
+                        break
+                    config = self.inject_queue.pop(0)
+                    portname = config["port"]
+                    event = config["event"]
+                    port = self.find_port_with_name(portname)
+                    self.inbags.setdefault(port, []).append(event)
+                ]]>
+            </body>
+        </method>
+        <!-- Combine the information from the routed messages to determine the external, internal and confluent transition functions to trigger. -->
+        <method name="find_all_imminents">
+            <body>
+                <![CDATA[
+                # Internal codes:
+                #   1 --> internal transition
+                #   2 --> external transition
+                #   3 --> confluent transition
+                # These codes are a legacy of efficient PyPDEVS, but is kept here for consistency
+                self.transitioning = {model: 1 for model in self.imminents}
+                for inport in self.inbags:
+                    aDEVS = inport.host_DEVS
+                    aDEVS.my_input[inport] = self.inbags[inport]
+                    if aDEVS in self.transitioning:
+                        self.transitioning[aDEVS] = 3
+                    else:
+                        self.transitioning[aDEVS] = 2
+                ]]>
+            </body>
+        </method>
+        <!-- Trigger all transition functions. -->
+        <method name="compute_transitions">
+            <body>
+                <![CDATA[
+                self.new_states = {}
+                for aDEVS in self.transitioning:
+                    aDEVS.my_input = {key: pickle.loads(pickle.dumps(aDEVS.my_input[key], pickle.HIGHEST_PROTOCOL)) for key in aDEVS.my_input}
+                    if self.transitioning[aDEVS] == 1:
+                        aDEVS.state = aDEVS.intTransition()
+                    elif self.transitioning[aDEVS] == 2:
+                        aDEVS.elapsed = self.simulation_time[0] - aDEVS.timeLast[0]
+                        aDEVS.state = aDEVS.extTransition(aDEVS.my_input)
+                    elif self.transitioning[aDEVS] == 3:
+                        aDEVS.elapsed = 0.
+                        aDEVS.state = aDEVS.confTransition(aDEVS.my_input)
+                    aDEVS.old_states.append((self.simulation_time, pickle.dumps(aDEVS.state)))
+                    aDEVS.my_input = {}
+                    self.new_states[aDEVS] = aDEVS.state
+                ]]>
+            </body>
+        </method>
+        <!-- Trigger all timeAdvance functions. -->
+        <method name="compute_ta">
+            <body>
+                <![CDATA[
+                self.new_tn = {}
+                t, age = self.simulation_time
+                for aDEVS in self.transitioning:
+                    ta = aDEVS.timeAdvance()
+                    aDEVS.timeLast = self.simulation_time
+                    aDEVS.time_next = (t + ta, 1 if ta else (age + 1))
+                    self.new_tn[aDEVS] = aDEVS.time_next
+                    trace(self.trace_file, self.transitioning[aDEVS], aDEVS)
+                self.model.scheduler.massReschedule(self.transitioning)
+                self.time_next = self.model.scheduler.readFirst()
+                ]]>
+            </body>
+        </method>
+        <method name="flush_file">
+            <body>
+                <![CDATA[
+                if self.trace_file is not None:
+                    self.trace_file.flush()
+                ]]>
+            </body>
+        </method>
+        <method name="process_breakpoints">
+            <parameter name="realtime"/>
+            <body>
+                <![CDATA[
+                breakpoint_id = self.should_terminate(realtime)
+                for breakpoint in self.breakpoints:
+                    if breakpoint.id == breakpoint_id:
+                        if breakpoint.disable_on_trigger:
+                            breakpoint.enabled = False
+                        return breakpoint_id
+                ]]>
+            </body>
+        </method>
+        <method name="compute_timeNext">
+            <body>
+                <![CDATA[
+                model_timeNext = self.model.scheduler.readFirst()
+                if len(self.inject_queue) > 0:
+                    self.time_next = min(model_timeNext, self.inject_queue[0]["time"])
+                else:
+                    self.time_next = model_timeNext
+                ]]>
+            </body>
+        </method>
+        <method name="rollback_step">
+            <body>
+                <![CDATA[
+                    if len(self.transition_times) == 0:
+                        return
+                    new_time = self.transition_times.pop()
+                    for model in self.model.component_set:
+                        if model.old_states[-1][0] == new_time:
+                            # Remove the current state
+                            del model.old_states[-1]
+                            # Set the new (old...) state
+                            new_state = model.old_states[-1]
+                            model.state = pickle.loads(new_state[1])
+                            model.timeLast = new_state[0]
+                            ta = model.timeAdvance()
+                            model.time_next = (model.timeLast[0] + ta, model.timeLast[1] + 1 if ta == 0 else 0)
+                            self.model.scheduler.massReschedule([model])
+                    self.simulation_time = self.transition_times[-1] if len(self.transition_times) > 0 else (0.0, 0)
+                ]]>
+            </body>
+        </method>
+        <scxml initial="main">
+            <!-- Parallel states: one of them controls the simulation flow, the other the type of simulation being performed. -->
+            <parallel id="main">
+                <!-- When an injection is received, just append it to the list of pending injections.
+                     These will be processed as soon as the current simulation step is finished.
+                     Afterwards, return to the previous state, as there was no change of state. -->
+                <state id="injection_monitor">
+                    <state id="inject">
+                        <transition port="request" event="inject" target=".">
+                            <parameter name="configuration"/>
+                            <script>
+                                configuration["time"] = (configuration["time"], 1)
+                                self.inject_queue.append(configuration)
+                                self.inject_queue.sort(key=lambda i: i["time"])
+                            </script>
+                            <raise scope="output" port="reply" event="inject_ok"/>
+                        </transition>
+                    </state>
+                </state>
+                <state id="tracer_monitor">
+                    <state id="trace">
+                        <transition port="request" event="trace" target=".">
+                            <parameter name="filename"/>
+                            <script>
+                                if filename is not None:
+                                    self.trace_file = open(filename, 'w')
+                                else:
+                                    self.trace_file = None
+                            </script>
+                            <raise scope="output" port="reply" event="trace_config_ok"/>
+                        </transition>
+                    </state>
+                </state>
+                <!-- The main parallel component: the simulation flow. -->
+                <state id="simulation_flow" initial="initialize">
+                    <state id="initialize">
+                        <transition target="../check_termination">
+                            <raise scope="output" port="reply" event="all_states">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="{m.getModelFullName(): (m.time_next, m.state) for m in self.model.component_set}"/>
+                            </raise>
+                        </transition>
+                    </state>
+                    <state id="check_termination" initial="workaround">
+                        <onexit>
+                            <script>
+                                self.simulation_time = self.time_next
+                            </script>
+                        </onexit>
+
+                        <state id="workaround">
+                            <transition after="0" target="../check_termination"/>
+                        </state>
+
+                        <state id="wait">
+                            <onexit>
+                                <script>
+                                    diff = time.time() - self.realtime_starttime
+                                    self.simulation_time = (diff / self.realtime_scale, 1)
+                                </script>
+                            </onexit>
+                            <transition after="self.calculate_after()" target="../check_termination"/>
+                            <transition cond="INSTATE('../../../simulation_state/paused')" target="../check_termination"/>
+                        </state>
+
+                        <state id="small_step_check">
+                            <transition cond="self.should_terminate(False) == -2" target="../../do_simulation"/>
+                            <transition cond="self.should_terminate(False) == -1" target="../check_termination">
+                                <raise event="termination_condition"/>
+                            </transition>
+                            <transition cond="self.should_terminate(False) &gt; -1" target="../check_termination">
+                                <script>
+                                    breakpoint_id = self.process_breakpoints(False)
+                                </script>
+                                <raise scope="output" port="reply" event="breakpoint_triggered">
+                                    <parameter expr="breakpoint_id"/>
+                                </raise>
+                                <raise event="termination_condition"/>
+                            </transition>
+                        </state>
+
+                        <state id="check_termination">
+                            <onentry>
+                                <script>
+                                    self.compute_timeNext()
+                                    self.the_time = self.calculate_after()
+                                </script>
+                            </onentry>
+                            <!-- Continue simulation -->
+                            <transition cond="INSTATE('../../../simulation_state/continuous') and (self.should_terminate(False) == -2)" target="../../do_simulation"/>
+                            <transition cond="INSTATE('../../../simulation_state/big_step') and (self.should_terminate(False) == -2)" target="../../do_simulation"/>
+
+                            <!-- Realtime and didn't reach the required time_next yet -->
+                            <transition cond="INSTATE('../../../simulation_state/realtime') and (self.should_terminate(True) == -2) and (self.the_time &gt; 0.0)" target="../wait"/>
+
+                            <transition cond="INSTATE('../../../simulation_state/realtime') and (self.should_terminate(True) == -2) and (self.the_time &lt;= 0.0)" target="../../do_simulation"/>
+
+                            <transition port="request" event="small_step" target="../small_step_check">
+                                <parameter name="configuration" type="dict" default="{}"/>
+                                <script>
+                                    self.parse_options(configuration)
+                                </script>
+                            </transition>
+
+                            <!-- Pause simulation -->
+                            <transition cond="(not INSTATE('../../../simulation_state/paused') and INSTATE('../../../simulation_state/realtime') and (self.should_terminate(True) == -1))" target="../workaround">
+                                <raise event="termination_condition"/>
+                            </transition>
+                            <transition cond="(not INSTATE('../../../simulation_state/paused') and not INSTATE('../../../simulation_state/realtime') and (self.should_terminate(False) == -1))" target="../workaround">
+                                <raise event="termination_condition"/>
+                            </transition>
+                            <transition cond="(not INSTATE('../../../simulation_state/paused')) and INSTATE('../../../simulation_state/realtime') and (self.should_terminate(True) &gt; -1)" target="../workaround">
+                                <script>
+                                    breakpoint_id = self.process_breakpoints(True)
+                                </script>
+                                <raise scope="output" port="reply" event="breakpoint_triggered">
+                                    <parameter expr="breakpoint_id"/>
+                                </raise>
+                                <raise event="termination_condition"/>
+                            </transition>
+                            <transition cond="(not INSTATE('../../../simulation_state/paused')) and not INSTATE('../../../simulation_state/realtime') and (self.should_terminate(False) &gt; -1)" target="../workaround">
+                                <script>
+                                    breakpoint_id = self.process_breakpoints(False)
+                                </script>
+                                <raise scope="output" port="reply" event="breakpoint_triggered">
+                                    <parameter expr="breakpoint_id"/>
+                                </raise>
+                                <raise event="termination_condition"/>
+                            </transition>
+
+                            <!-- Process god event -->
+                            <transition cond="INSTATE('../../../simulation_state/paused')" port="request" event="god_event" target="../workaround">
+                                <parameter name="configuration"/>
+                                <script>
+                                    modelname = configuration["model"]
+                                    state_attribute = configuration["attribute"]
+                                    new_value = configuration["value"]
+                                    model = self.find_model_with_name(modelname)
+                                    setattr(model.state, state_attribute, new_value)
+                                    # Call the timeadvance method again and compute new ta
+                                    ta = model.timeAdvance()
+                                    model.time_next = (model.timeLast[0] + ta, 1 if ta else (model.timeLast[1] + 1))
+                                    self.model.scheduler.massReschedule([model])
+                                    # self.simulation_time = self.model.scheduler.readFirst()
+                                </script>
+                                <raise scope="output" port="reply" event="god_event_ok">
+                                    <parameter expr="{model.getModelFullName(): str(model.state)}"/>
+                                </raise>
+                                <raise scope="output" port="reply" event="new_tn">
+									<parameter expr="self.simulation_time"/>
+                                    <parameter expr="{model.getModelFullName(): model.time_next}"/>
+                                </raise>
+                            </transition>
+
+                            <!-- Omniscient debugging -->
+                            <transition cond="INSTATE('../../../simulation_state/paused')" port="request" event="backwards_step" target="../workaround">
+                                <script>
+                                    self.rollback_step()
+                                </script>
+                                <raise scope="output" port="reply" event="all_states">
+                                    <parameter expr="self.simulation_time"/>
+                                    <parameter expr="{m.getModelFullName(): (m.time_next, m.state) for m in self.model.component_set}"/>
+                                </raise>
+                            </transition>
+
+                        </state>
+                    </state>
+
+                    <state id="do_simulation" initial="init">
+                    <state id="init">
+                        <onexit>
+                            <script>
+                                self.find_internal_imminents()
+                            </script>
+                        </onexit>
+                        <transition cond="not INSTATE('../../../simulation_state/paused')" target="../found_internal_imminents"/>
+                        <!-- Always output this if paused, as we only got here because a small step was fired previously -->
+                        <transition cond="INSTATE('../../../simulation_state/paused')" target="../found_internal_imminents">
+                            <raise scope="output" port="reply" event="imminents">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('imminents', self.imminents)"/>
+                            </raise>
+                        </transition>
+                    </state>
+
+                    <state id="found_internal_imminents">
+                        <onexit>
+                            <script>
+                                self.compute_outputfunction()
+                            </script>
+                        </onexit>
+                        <transition cond="not INSTATE('../../../simulation_state/paused')" target="../computed_outputfunction"/>
+                        <transition port="request" event="small_step" target="../computed_outputfunction">
+                            <raise scope="output" port="reply" event="outbags">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('outbags', self.outbags)"/>
+                            </raise>
+                        </transition>
+                    </state>
+
+                    <state id="computed_outputfunction">
+                        <onexit>
+                            <script>
+                                self.route_messages()
+                                self.process_injects()
+                            </script>
+                        </onexit>
+                        <transition cond="not INSTATE('../../../simulation_state/paused')" target="../routed_messages">
+                        </transition>
+                        <transition port="request" event="small_step" target="../routed_messages">
+                            <raise scope="output" port="reply" event="inbags">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('inbags', self.inbags)"/>
+                            </raise>
+                        </transition>
+                    </state>
+
+                    <state id="routed_messages">
+                        <onexit>
+                            <script>
+                                self.find_all_imminents()
+                            </script>
+                        </onexit>
+                        <transition cond="not INSTATE('../../../simulation_state/paused')" target="../found_all_imminents">
+                        </transition>
+                        <transition port="request" event="small_step" target="../found_all_imminents">
+                            <raise scope="output" port="reply" event="transitioning">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('transitioning', self.transitioning)"/>
+                            </raise>
+                        </transition>
+                    </state>
+
+                    <state id="found_all_imminents">
+                        <onexit>
+                            <script>
+                                self.compute_transitions()
+                            </script>
+                        </onexit>
+                        <transition cond="not INSTATE('../../../simulation_state/paused')" target="../computed_transitions"/>
+                        <transition port="request" event="small_step" target="../computed_transitions">
+                            <raise scope="output" port="reply" event="new_states">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('new_states', self.new_states)"/>
+                            </raise>
+                        </transition>
+                    </state>
+
+                    <state id="computed_transitions">
+                        <onexit>
+                            <script>
+                                self.compute_ta()
+                            </script>
+                        </onexit>
+                        <transition cond="INSTATE('../../../simulation_state/continuous')" target="../../check_termination"/>
+                        <transition port="request" event="small_step" target="../../check_termination">
+                            <raise scope="output" port="reply" event="new_tn">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('new_tn', self.new_tn)"/>
+                            </raise>
+                        </transition>
+                        <transition cond="INSTATE('../../../simulation_state/realtime') or INSTATE('../../../simulation_state/big_step')" target="../../check_termination">
+                            <raise event="big_step_done"/>
+                            <raise scope="output" port="reply" event="new_states">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('new_states', self.new_states)"/>
+                            </raise>
+                            <raise scope="output" port="reply" event="new_tn">
+                                <parameter expr="self.simulation_time"/>
+                                <parameter expr="self.serialize('new_tn', self.new_tn)"/>
+                            </raise>
+                        </transition>
+                    </state>
+                    </state>
+                </state>
+
+                <state id="simulation_state" initial="paused">
+                    <state id="paused">
+                        <transition port="request" event="simulate" target="../continuous">
+                            <parameter name="configuration" type="dict" default="{}"/>
+                            <script>
+                                self.parse_options(configuration)
+                            </script>
+                        </transition>
+                        <transition port="request" event="realtime" target="../realtime">
+                            <parameter name="configuration" type="dict" default="{}"/>
+                            <script>
+                                self.parse_options(configuration)
+                            </script>
+                        </transition>
+                        <transition port="request" event="big_step" target="../big_step">
+                            <parameter name="configuration" type="dict" default="{}"/>
+                            <script>
+                                self.parse_options(configuration)
+                            </script>
+                        </transition>
+                    </state>
+                    <state id="continuous">
+                            <transition port="request" event="pause" target=".">
+                                <script>
+                                    # Just override termination condition
+                                    self.termination_condition = lambda i, j, k : True
+                                    self.termination_time = None
+                                </script>
+                            </transition>
+                            <transition event="termination_condition" target="../paused">
+                                <raise port="reply" event="terminate">
+                                    <parameter expr="self.simulation_time"/>
+                                </raise>
+                                <script>
+                                    self.flush_file()
+                                </script>
+                                <raise scope="output" port="reply" event="all_states">
+                                    <parameter expr="self.simulation_time"/>
+                                    <parameter expr="{m.getModelFullName(): (m.time_next, m.state) for m in self.model.component_set}"/>
+                                </raise>
+                            </transition>
+                    </state>
+                    <state id="realtime">
+                            <transition port="request" event="pause" target=".">
+                                <script>
+                                    # Just override termination condition
+                                    self.termination_condition = lambda i, j, k : True
+                                    self.termination_time = None
+
+                                    # Don't forget to correctly set the simulation time
+                                    diff = time.time() - self.realtime_starttime
+                                    self.simulation_time = (diff / self.realtime_scale, 1)
+                                </script>
+                            </transition>
+                            <transition event="termination_condition" target="../paused">
+                                <raise port="reply" event="terminate">
+                                    <parameter expr="self.simulation_time"/>
+                                </raise>
+                                <script>
+                                    self.flush_file()
+                                </script>
+                            </transition>
+                    </state>
+                    <state id="big_step">
+                            <transition event="big_step_done" target="../paused"/>
+                            <transition event="termination_condition" target="../paused">
+                                <raise port="reply" event="terminate">
+                                    <parameter expr="self.simulation_time"/>
+                                </raise>
+                                <script>
+                                    self.flush_file()
+                                </script>
+                            </transition>
+                    </state>
+                </state>
+                <state id="breakpoint_manager">
+                    <state id="breakpoint_manage">
+                        <transition port="request" event="add_breakpoint" target=".">
+                            <parameter name="breakpoint_id"/>
+                            <parameter name="function"/>
+                            <parameter name="enabled"/>
+                            <parameter name="disable_on_trigger"/>
+                            <script>
+                                self.breakpoints.append(Breakpoint(breakpoint_id, function, enabled, disable_on_trigger))
+                            </script>
+                        </transition>
+                        <transition port="request" event="del_breakpoint" target=".">
+                            <parameter name="del_breakpoint_id"/>
+                            <script>
+                                self.breakpoints = [breakpoint for breakpoint in self.breakpoints if breakpoint.id != del_breakpoint_id]
+                            </script>
+                        </transition>
+                        <transition port="request" event="toggle_breakpoint" target=".">
+                            <parameter name="breakpoint_id"/>
+                            <parameter name="enabled"/>
+                            <script>
+                                for breakpoint in self.breakpoints:
+                                    if breakpoint.id == breakpoint_id:
+                                        breakpoint.enabled = enabled
+                                        break
+                            </script>
+                        </transition>
+                    </state>
+                </state>
+                <state id="reset">
+                    <state id="reset">
+                        <transition port="request" event="reset" target=".">
+                            <script>
+                                for model in self.model.component_set:
+                                    model.state = pickle.loads(self.save_model[model][1])
+                                    model.elapsed = self.save_model[model][0]
+                                    model.timeLast = (-model.elapsed, 1)
+                                    ta = model.timeAdvance()
+                                    model.time_next = (model.timeLast[0] + ta, 1)
+                                self.simulation_time = (0.0, 0)
+                                self.model.scheduler.massReschedule(self.model.component_set)
+
+                                # Reset trace file
+                                if self.trace_file is not None:
+                                    self.trace_file = open(self.trace_file.name, 'w')
+                            </script>
+                            <raise scope="output" port="reply" event="all_states">
+                                <parameter expr="(0.0, 0)"/>
+                                <parameter expr="{m.getModelFullName(): (m.time_next, m.state) for m in self.model.component_set}"/>
+                            </raise>
+                        </transition>
+                    </state>
+                </state>
+            </parallel>
+        </scxml>
+    </class>
+</diagram>

+ 178 - 0
debugging_environment/pypdevs/scheduler.py

@@ -0,0 +1,178 @@
+# -*- coding: Latin-1 -*-
+"""
+The Activity Heap is based on a heap, though allows for reschedules. 
+
+To allow reschedules to happen, a model is accompagnied by a flag to 
+indicate whether or not it is still valid. 
+As soon as a model is rescheduled, the flag of the previously scheduled 
+time is set and another entry is added. This causes the heap to become *dirty*, 
+requiring a check for the flag as soon as the first element is requested.
+
+Due to the possibility for a dirty heap, the heap will be cleaned up as 
+soon as the number of invalid elements becomes too high. 
+This cleanup method has O(n) complexity and is therefore only 
+ran when the heap becomes way too dirty.
+
+Another problem is that it might consume more memory than other schedulers, 
+due to invalid elements being kept in memory. 
+However, the actual model and states are not duplicated as they are references. 
+The additional memory requirement should not be a problem in most situations.
+
+The 'activity' part from the name stems from the fact that only models where 
+the *time_next* attribute is smaller than infinity will be scheduled. 
+Since these elements are not added to the heap, they aren't taken into account 
+in the complexity. This allows for severe optimisations in situations where 
+a lot of models can be scheduled for infinity.
+
+Of all provided schedulers, this one is the most mature due to it being the 
+oldest and also the default scheduler. It is also applicable in every situation 
+and it offers sufficient performance in most cases.
+
+This scheduler is ideal in situations where (nearly) no reschedules happen 
+and where most models transition at a different time.
+
+It results in slow behaviour in situations requiring lots of rescheduling, 
+and thus lots of dirty elements.
+
+This method is also applied in the VLE simulator and is the common approach 
+to heap schedulers that require invalidation. It varies from the scheduler in 
+ADEVS due to the heap from the heapq library being used, which doesn't offer 
+functions to restructure the heap. 
+Reimplementing these methods in pure Python would be unnecessarily slow.
+"""
+from heapq import heappush, heappop, heapify
+
+class Scheduler(object):
+    """
+    Scheduler class itself
+    """
+    def __init__(self, models, epsilon, totalModels):
+        """
+        Constructor
+
+        :param models: all models in the simulation
+        """
+        self.heap = []
+        self.id_fetch = [None] * totalModels
+        for model in models:
+            if model.time_next[0] != float('inf'):
+                self.id_fetch[model.model_id] = [model.time_next, model.model_id, True, model]
+                heappush(self.heap, self.id_fetch[model.model_id])
+            else:
+                self.id_fetch[model.model_id] = [model.time_next, model.model_id, False, model]
+        
+        self.invalids = 0
+        self.maxInvalids = len(models)*2
+        self.epsilon = epsilon
+
+    def schedule(self, model):
+        """
+        Schedule a model
+
+        :param model: the model to schedule
+        """
+        # Create the entry, as we have accepted the model
+        elem = [model.time_next, model.model_id, False, model]
+        try:
+            self.id_fetch[model.model_id] = elem
+        except IndexError:
+            # A completely new model
+            self.id_fetch.append(elem)
+            self.maxInvalids += 2
+        # Check if it requires to be scheduled
+        if model.time_next[0] != float('inf'):
+            self.id_fetch[model.model_id][2] = True
+            heappush(self.heap, self.id_fetch[model.model_id])
+
+    def unschedule(self, model):
+        """
+        Unschedule a model
+
+        :param model: model to unschedule
+        """
+        if model.time_next != float('inf'):
+            self.invalids += 1
+        # Update the referece still in the heap
+        self.id_fetch[model.model_id][2] = False
+        # Remove the reference in our id_fetch
+        self.id_fetch[model.model_id] = None
+        self.maxInvalids -= 2
+
+    def massReschedule(self, reschedule_set):
+        """
+        Reschedule all models provided. 
+        Equivalent to calling unschedule(model); schedule(model) on every element in the iterable.
+
+        :param reschedule_set: iterable containing all models to reschedule
+        """
+        #NOTE rather dirty, though a lot faster for huge models
+        inf = float('inf')
+        for model in reschedule_set:
+            if model.model_id is None:
+                continue
+            event = self.id_fetch[model.model_id]
+            if event[2]:
+                if model.time_next == event[0]:
+                    continue
+                elif event[0][0] != inf:
+                    self.invalids += 1
+                event[2] = False
+            if model.time_next[0] != inf:
+                self.id_fetch[model.model_id] = [model.time_next, model.model_id, True, model]
+                heappush(self.heap, self.id_fetch[model.model_id])
+        if self.invalids >= self.maxInvalids:
+            self.heap = [i for i in self.heap if i[2] and (i[0][0] != inf)]
+            heapify(self.heap)
+            self.invalids = 0
+
+    def readFirst(self):
+        """
+        Returns the time of the first model that has to transition
+
+        :returns: timestamp of the first model
+        """
+        self.cleanFirst()
+        return self.heap[0][0]
+
+    def cleanFirst(self):
+        """
+        Clean up the invalid elements in front of the list
+        """
+        try:
+            while not self.heap[0][2]:
+                heappop(self.heap)
+                self.invalids -= 1
+        except IndexError:
+            # Nothing left, so it as clean as can be
+            pass
+
+    def getImminent(self, time):
+        """
+        Returns a list of all models that transition at the provided time, with a specified epsilon deviation allowed.
+
+        :param time: timestamp to check for models
+
+        .. warning:: For efficiency, this method only checks the **first** elements, so trying to invoke this function with a timestamp higher than the value provided with the *readFirst* method, will **always** return an empty set.
+        """
+        immChildren = []
+        t, age = time
+        try:
+            # Age must be exactly the same
+            first = self.heap[0]
+            while (first[0][0] <= t) and (first[0][1] == age):
+                # Check if the found event is actually still active
+                if(first[2]):
+                    # Active, so event is imminent
+                    immChildren.append(first[3])
+                    first[2] = False
+                else:
+                    # Wasn't active, but we will have to pop this to get the next
+                    # So we can lower the number of invalids
+                    self.invalids -= 1
+
+                # Advance the while loop
+                heappop(self.heap)
+                first = self.heap[0]
+        except IndexError:
+            pass
+        return immChildren

+ 11 - 0
debugging_environment/pypdevs/tracer.py

@@ -0,0 +1,11 @@
+def trace(trace_file, type, model):
+    type_map = {1: "INTERNAL", 2: "EXTERNAL", 3: "CONFLUENT"}
+    type = type_map[type]
+    if trace_file is not None:
+        trace_file.write("%s TRANSITION in <%s> @ %s\n" % (type, model.getModelFullName(), model.timeLast[0]))
+        trace_file.write("  NEW STATE <%s>\n" % (model.state))
+        if type != "EXTERNAL":
+            trace_file.write("  OUTPUTFNC returned %s\n" % model.my_output)
+        elif type != "INTERNAL":
+            trace_file.write("  inputs were %s\n" % model.my_input)
+        trace_file.write("  time_next: %s (ta: %s)\n" % (model.time_next[0], model.time_next[0] - model.timeLast[0]))

+ 11 - 0
debugging_environment/pypdevs/verbose_tracing.xml

@@ -0,0 +1,11 @@
+
+                type_map = {1: "INTERNAL", 2: "EXTERNAL", 3: "CONFLUENT"}
+                type = type_map[type]
+                if self.trace_file is not None:
+                    self.trace_file.write("%s TRANSITION in <%s> @ %s\n" % (type, model.getModelFullName(), model.timeLast[0]))
+                    self.trace_file.write("  NEW STATE <%s>\n" % (model.state))
+                    if type != "EXTERNAL":
+                        self.trace_file.write("  OUTPUTFNC returned %s\n" % model.myOutput)
+                    elif type != "INTERNAL":
+                        self.trace_file.write("  inputs were %s\n" % model.my_input)
+                    self.trace_file.write("  time_next: %s (ta: %s)\n" % (model.time_next[0], model.time_next[0] - model.timeLast[0]))

+ 61 - 0
debugging_environment/python_sccd_compiler/code_generation.py

@@ -0,0 +1,61 @@
+from visitor import Visitor
+from utils import FileOutputer
+from utils import Enum
+from utils import Logger
+from compiler_exceptions import CodeBlockException
+
+NOT_SET = 0
+SPACES_USED = 1
+TABS_USED = 2
+
+Languages = Enum("Python","CSharp","Javascript") 
+Platforms = Enum("Threads","GameLoop") 
+
+class CodeGenerator(Visitor):
+    def __init__(self):
+        self.supported_platforms = []
+        
+    def generate(self, class_diagram, output_file, platform):
+        self.platform = platform
+        if self.platform not in self.supported_platforms :
+            Logger.showError("Unsupported platform.")
+            return False
+        try :
+            self.fOut = FileOutputer(output_file)
+            class_diagram.accept(self)
+        finally :
+            self.fOut.close()
+        return True
+    
+    def writeCodeCorrectIndent(self, body):
+        lines = body.split('\n')
+        while( len(lines) > 0 and lines[-1].strip() == "") :
+            del(lines[-1])
+    
+        index = 0;
+        while( len(lines) > index and lines[index].strip() == "") :       
+            index += 1
+            
+        if index >= len(lines) :
+            return
+        #first index where valid code is present
+        to_strip_index = len(lines[index].rstrip()) - len(lines[index].strip()) 
+        indent_type = NOT_SET;
+            
+        while index < len(lines):
+            strip_part = lines[index][:to_strip_index]
+            
+            if( ('\t' in strip_part and ' ' in strip_part) or
+                (indent_type == SPACES_USED and '\t' in strip_part) or
+                (indent_type == TABS_USED and ' ' in strip_part)
+            ) :
+                raise CodeBlockException("Mixed tab and space indentation!")
+            
+            if indent_type == NOT_SET :
+                if ' ' in strip_part :
+                    indent_type = SPACES_USED
+                elif '\t' in strip_part :
+                    indent_type = TABS_USED
+                    
+            self.fOut.write(lines[index][to_strip_index:])
+            index += 1

+ 14 - 0
debugging_environment/python_sccd_compiler/compiler_exceptions.py

@@ -0,0 +1,14 @@
+class CompilerException(Exception):
+    def __init__(self, message):
+        self.message = message
+    def __str__(self):
+        return repr(self.message)
+    
+class TransitionException(CompilerException):
+    pass
+
+class UnprocessedException(CompilerException):
+    pass
+
+class CodeBlockException(CompilerException):
+    pass

+ 994 - 0
debugging_environment/python_sccd_compiler/constructs.py

@@ -0,0 +1,994 @@
+import abc
+import re
+import xml.etree.ElementTree as ET
+import os.path
+from utils import Logger
+from visitor import Visitable
+from compiler_exceptions import CompilerException, TransitionException, UnprocessedException
+from lexer import Lexer, Token, TokenType
+
+# http://docs.python.org/2/library/xml.etree.elementtree.html
+
+# list of reserved words
+reserved = ["__init__", "__del__", "init", "transition", "microstep", "step", "inState", "event", "addEvent", 
+			"broadcast", "getEarliestEvent", "__str__", "controller", 
+			"current_state", "timers", "eventQueue", "Controller", "state_changed", "history_state",
+			"root", "narrowcast", "object_manager", "update"]
+
+SELF_REFERENCE_SEQ = 'SELF'
+INSTATE_SEQ = 'INSTATE'
+
+##################################
+
+class StateReference(Visitable):
+	def __init__(self, input_string):
+		self.path_string = input_string
+		self.target_nodes = None #calculated in state linker
+		
+	def getNodes(self):
+		#if no target nodes are set, it means that the visitor corresponding for that hasn't visited yet
+		if self.target_nodes is None:
+			raise UnprocessedException("State reference not resolved yet.")
+		return self.target_nodes
+   
+##################################
+class ExpressionPart(Visitable):
+	__metaclass__  = abc.ABCMeta
+	
+class ExpressionPartString(ExpressionPart):
+	def __init__(self, string):
+		self.string = string
+	
+class SelfReference(ExpressionPart):		
+	pass
+	
+class InStateCall(ExpressionPart):
+	def __init__(self, state_string):
+		self.target = StateReference(state_string)
+
+##################################
+
+	
+class Expression(Visitable):
+	lexer = Lexer(False, True)
+	
+	def __init__(self, input):
+		if not input :
+			raise CompilerException("Empty Expression.")
+		self.parse(input)
+		
+	def parse(self, input, dont_parse = []):
+		self.expression_parts = []
+		self.lexer.input(input)
+		processed_bare_expression = ""
+		
+		for token in self.lexer.tokens() :
+			created_object = None
+			
+			if token.type == TokenType.WORD :
+				if token.val in dont_parse :
+					raise CompilerException("Macro \"" + token.val + "\" not allowed here.")
+				elif token.val == SELF_REFERENCE_SEQ :
+					created_object = SelfReference()
+				elif token.val == INSTATE_SEQ :
+					created_object = self.parseInStateCall()
+					if created_object is None :
+						raise CompilerException("Illegal use of \"" + INSTATE_SEQ + "\" macro.")
+					
+			if created_object is None:
+				processed_bare_expression += token.val
+			else :	
+				if processed_bare_expression != "" :
+					self.expression_parts.append(ExpressionPartString(processed_bare_expression))
+					processed_bare_expression = ""
+				self.expression_parts.append(created_object)  
+		
+		#Process part of input after the last created macro object
+		if processed_bare_expression != "" :
+			self.expression_parts.append(ExpressionPartString(processed_bare_expression))
+			
+	def parseInStateCall(self):
+		token = self.lexer.nextToken()
+		if token is None or token.type != TokenType.LBRACKET :
+			return None
+		token = self.lexer.nextToken()
+		if token is None or token.type != TokenType.QUOTED :
+			return None
+		else :
+			created_object = InStateCall(token.val[1:-1])
+		token = self.lexer.nextToken()
+		if token is None or token.type != TokenType.RBRACKET :
+			return None
+		else :
+			return created_object
+		  
+	def accept(self, visitor):
+		for expression_part in self.expression_parts :
+			expression_part.accept(visitor)
+
+class LValue(Expression):
+	def __init__(self, input):
+		if not input :
+			raise CompilerException("Empty LValue.")
+		self.parse(input, [INSTATE_SEQ])
+		#do some validation, provide parameters to processString to make the function more efficient
+	 
+##################################	 
+	 
+class FormalEventParameter(Visitable):
+	def __init__(self, name, ptype = ""):
+		self.name = name
+		self.type = ptype
+		
+	def getName(self):
+		return self.name
+	
+	def getType(self):
+		return self.type
+	
+##################################
+class TriggerEvent:
+	def __init__(self, xml_element):
+		self.is_uc = False;
+		self.is_after = False
+		self.after_index = -1
+		self.params = []
+		
+		self.event = xml_element.get("event", "").strip()
+		self.after = xml_element.get("after", "").strip()
+		self.port = xml_element.get("port", "").strip()
+		if self.event and self.after :
+			raise CompilerException("Cannot have both the event and after attribute set for a transition.")
+		
+		if not self.event and self.port:
+			raise CompilerException("A transition without event can not have a port.")
+
+		if self.after :
+			if self.port :
+				raise CompilerException("After event can not have a port.")
+			self.is_after = True
+			self.after = Expression(self.after)
+			return
+		elif not self.event :
+			self.is_uc = True
+			return
+			
+		self.params = []
+		parameters = xml_element.findall('parameter')	
+		for p in parameters :
+			name = p.get("name","")
+			if not name :
+				raise CompilerException("Parameter without name detected.")
+			self.params.append(FormalEventParameter(name, p.get("type","")))
+			
+	def getEvent(self):	
+		return self.event
+	
+	def setEvent(self, event):
+		self.event = event
+	
+	def getParameters(self):	
+		return self.params
+	
+	def getPort(self):
+		return self.port
+		
+	def isUC(self):
+		return self.is_uc;
+	
+	def isAfter(self):
+		return self.is_after
+	
+	def getAfterIndex(self):
+		return self.after_index
+	
+	def setAfterIndex(self, after):
+		self.after_index = after
+		
+
+##################################
+
+class SubAction(Visitable):
+	__metaclass__  = abc.ABCMeta
+	
+	@abc.abstractmethod
+	def check(self):
+		pass
+	
+	@classmethod
+	def create(cls, xml_element):
+		for subcls in cls.__subclasses__():
+			tag = xml_element.tag.lower()
+			if subcls.check(tag):
+				return subcls(xml_element)
+		raise CompilerException("Invalid subaction.")
+	
+##################################
+"""
+	Is a possible subaction; generates an event.
+"""
+
+class RaiseEvent(SubAction):
+	tag = "raise"
+	LOCAL_SCOPE = 1
+	BROAD_SCOPE = 2
+	OUTPUT_SCOPE = 3
+	NARROW_SCOPE = 4
+	CD_SCOPE = 5
+	
+	
+	def __init__(self, xml_element):
+		self.event = xml_element.get("event","").strip()
+		scope_string = xml_element.get("scope","").strip().lower()
+		self.target = xml_element.get("target","").strip()
+		self.port = xml_element.get("port","").strip()
+		
+		if scope_string == "local" :
+			self.scope = self.LOCAL_SCOPE
+		elif scope_string == "broad" :
+			self.scope = self.BROAD_SCOPE
+		elif scope_string == "output" :
+			self.scope = self.OUTPUT_SCOPE
+		elif scope_string == "narrow" :
+			self.scope = self.NARROW_SCOPE
+		elif scope_string == "cd" :
+			self.scope = self.CD_SCOPE
+		elif scope_string == "" :
+			#Calculate scope depending on present attributes
+			if self.target and self.port :
+				raise CompilerException("Both target and port attribute detected without a scope defined.")
+			elif self.port :
+				self.scope = self.OUTPUT_SCOPE
+			elif self.target :
+				self.scope = self.NARROW_SCOPE
+			else :
+				self.scope = self.LOCAL_SCOPE  
+			
+		else :
+			raise CompilerException("Illegal scope attribute; needs to be one of the following : local, broad, narrow, output, cd or nothing.");  
+				
+		if self.scope == self.LOCAL_SCOPE or self.scope == self.BROAD_SCOPE or self.scope == self.CD_SCOPE:
+			if self.target :
+				Logger.showWarning("Raise event target detected, not matching with scope. Ignored.")
+				self.target = ""
+			if self.port :
+				Logger.showWarning("Raise event port detected, not matching with scope. Ignored.")
+				self.port = ""
+		if self.scope == self.NARROW_SCOPE and self.port :
+			Logger.showWarning("Raise event port detected, not matching with scope. Ignored.")
+			self.port = ""
+		if self.scope == self.OUTPUT_SCOPE and self.target :
+			Logger.showWarning("Raise event target detected, not matching with scope. Ignored.")
+			self.target = ""
+				
+		self.params = []
+		parameters = xml_element.findall('parameter')	
+		for p in parameters :
+			value = p.get("expr","")
+			if not value :
+				raise CompilerException("Parameter without value detected.")
+			self.params.append(Expression(value))
+	
+	@staticmethod
+	def check(tag):
+		return tag == RaiseEvent.tag
+	
+	def getPort(self):
+		return self.port
+			
+	def isLocal(self):
+		return self.scope == self.LOCAL_SCOPE
+	
+	def isNarrow(self):
+		return self.scope == self.NARROW_SCOPE
+	
+	def isBroad(self):
+		return self.scope == self.BROAD_SCOPE
+	
+	def isOutput(self):
+		return self.scope == self.OUTPUT_SCOPE
+	
+	def isCD(self):
+		return self.scope == self.CD_SCOPE
+	
+	def getTarget(self):
+		return self.target
+	
+	def getEventName(self):
+		return self.event
+	
+	def getParameters(self):	
+		return self.params
+	
+	def getScope(self):
+		return self.scope
+			
+class Script(SubAction):
+	tag = "script"
+	def __init__(self, xml_element):
+		self.code = xml_element.text
+		
+	@staticmethod
+	def check(tag):
+		return tag == Script.tag
+			
+class Log(SubAction):
+	tag = "log"
+	def __init__(self, xml_element):
+		self.message = xml_element.text.strip()
+		
+	@staticmethod
+	def check(tag):
+		return tag == Log.tag
+
+class Assign(SubAction):
+	tag = "assign"
+	def __init__(self, xml_element):
+		self.lvalue = LValue(xml_element.get("ident",""))
+		self.expression = Expression(xml_element.get("expr",""))
+	
+	@staticmethod   
+	def check(tag):
+		return tag == Assign.tag
+  
+##################################
+
+"""
+	Exists out of multiple subactions
+"""
+class Action(Visitable):
+	def __init__(self, xml_element):
+		self.sub_actions = []
+		for subaction in list(xml_element) :
+			if subaction.tag not in ["parameter"] :	  
+				self.sub_actions.append(SubAction.create(subaction))
+			
+	def accept(self, visitor):
+		for subaction in self.sub_actions :
+			subaction.accept(visitor)
+		
+##################################
+
+class StateChartTransition(Visitable):
+	def __init__(self,xml_element,parent):
+		self.xml = xml_element
+		self.parent_node = parent
+		self.trigger = TriggerEvent(self.xml)
+		guard_string = self.xml.get("cond","").strip()
+		if guard_string != "" : 
+			self.guard = Expression(guard_string)
+		else :
+			self.guard = None
+		target_string = self.xml.get("target","").strip()
+		if target_string == "" :
+			raise CompilerException("Transition from <" + self.parent_node.full_name + "> has empty target.")
+		self.target = StateReference(target_string)
+		
+		self.action = Action(self.xml)
+		
+		self.enter_nodes = None #Ordered list of nodes to be entered upon taking the transition, set by the path calculator
+		self.exit_nodes = None #Ordered list of nodes to be exited upon taking the transition, set by the path calculator
+		
+	def getEnterNodes(self):
+		if self.enter_nodes is None :
+			raise UnprocessedException("Enter path not calculated yet.")
+		return self.enter_nodes
+	
+	def getExitNodes(self):
+		if self.exit_nodes is None :
+			raise UnprocessedException("Exit path not calculated yet.")
+		return self.exit_nodes
+		
+	def isUCTransition(self):
+		""" Returns true iff is an unconditional transition (i.e. no trigger)
+		"""
+		return self.trigger.isUC()
+	
+	def getParentNode(self):
+		return self.parent_node
+		
+	def getTrigger(self):
+		return self.trigger
+		
+	def getGuard(self):
+		return self.guard
+		
+	def getTargetNodes(self):
+		return self.target.getNodes()
+
+	def hasGuard(self):
+		return self.guard != None
+	
+	def getAction(self):
+		return self.action		
+
+##################################  
+
+class EnterExitAction(Visitable):
+	def __init__(self, parent_node, xml_element = None):
+		self.parent_node = parent_node
+		if xml_element is not None:
+			self.action = Action(xml_element)
+		else :
+			self.action = None
+		
+class EnterAction(EnterExitAction):
+	def __init__(self, parent_node, xml_element = None):
+		EnterExitAction.__init__(self, parent_node, xml_element)
+		
+class ExitAction(EnterExitAction):
+	def __init__(self, parent_node, xml_element = None):
+		EnterExitAction.__init__(self, parent_node, xml_element)
+		
+##################################  
+
+class StateChartNode(Visitable):
+	def __init__(self, statechart, xml_element, parent = None):
+		self.statechart = statechart
+		self.parent = parent
+		self.children = []
+
+		self.is_root = False
+		self.is_basic = False
+		self.is_composite = False
+		self.is_history = False
+		self.is_history_deep = False
+		self.is_parallel_state = False
+		self.save_state_on_exit = False
+			
+		if xml_element.tag == "scxml" : 
+			self.is_root = True
+			self.is_composite = True
+		elif xml_element.tag == "parallel" : 
+			self.is_composite = True
+			self.is_parallel_state = True
+		elif xml_element.tag == "state" :
+			if len(xml_element.findall("state")) > 0 or (len(xml_element.findall("parallel")) > 0) :
+				self.is_composite = True
+			else :
+				self.is_basic = True
+			if  self.parent.is_parallel_state :
+				if (self.is_basic) :
+					raise CompilerException("Orthogonal nodes (nodes that are immediate children of parallel nodes) can't be basic.")
+		elif xml_element.tag == "history" :
+			history_type = xml_element.get("type","shallow")
+			if history_type == "deep" :
+				self.is_history_deep = True
+			elif history_type != "shallow" :
+				raise CompilerException("Invalid history type.") 
+			self.is_history = True			
+		else :
+			return
+							
+		self.resolveName(xml_element)
+		self.parseConflictAttribute(xml_element)
+		self.parseEnterActions(xml_element)
+		self.parseExitActions(xml_element)
+		
+		#transitions
+		self.transitions = []
+		for transition_xml in xml_element.findall("transition"):
+			self.transitions.append(StateChartTransition(transition_xml,self))
+			
+		self.optimizeTransitions()
+		self.generateChildren(xml_element)	
+		self.calculateDefaults(xml_element)
+			
+	def resolveName(self, xml):
+		if self.is_root :
+			self.name = "Root"
+			self.full_name = "Root"
+		else :
+			self.name = xml.get("id","")
+			self.full_name = self.parent.full_name + "_" + self.name
+	
+	def parseConflictAttribute(self, xml):
+		conflict = xml.get("conflict","")
+		if conflict == "outer" :
+			self.solves_conflict_outer = True
+		elif conflict == "inner" :
+			self.solves_conflict_outer = False
+		else :	
+			if not (conflict == "" or conflict == "inherit") :
+				raise CompilerException("Unknown conflict attribute for " + self.full_name + ".")
+			#Do our default inherit action
+			if self.is_root or self.parent.solves_conflict_outer: 
+				self.solves_conflict_outer = True
+			else :
+				self.solves_conflict_outer = False
+				
+	def parseEnterActions(self, xml):
+		on_entries = xml.findall("onentry")
+		if on_entries :
+			if len(on_entries) > 1:
+				raise CompilerException("Multiple <onentry> tags detected for "+ self.full_name + ", only 1 allowed.")
+			self.enter_action = EnterAction(self, on_entries[0])
+		else :
+			self.enter_action = EnterAction(self)
+			
+	def parseExitActions(self, xml):
+		on_exits = xml.findall("onexit")
+		if on_exits :
+			if len(on_exits) > 1:
+				raise CompilerException("Multiple <onexit> tags detected for "+ self.full_name + ", only 1 allowed.")
+			self.exit_action = ExitAction(self, on_exits[0])	
+		else :
+			self.exit_action = ExitAction(self)
+			
+	def optimizeTransitions(self):
+		"""If a transition with no trigger and no guard is found then it is considered as the only transition.
+		Otherwise the list is ordered by placing transitions having guards only first."""
+		onlyguards = []
+		withtriggers = []
+		optimized = []
+		for transition in self.transitions:
+			if transition.isUCTransition():
+				if not transition.hasGuard():
+					if optimized :
+						raise TransitionException("More than one transition found at a single node, that has no trigger and no guard.")
+					optimized.append(transition)
+				else:
+					onlyguards.append(transition)
+			else:
+				withtriggers.append(transition)
+		if not optimized :		
+			optimized = onlyguards + withtriggers
+		self.transitions = optimized
+	
+	def generateChildren(self, xml):
+		children_names = []
+		for child_xml in list(xml) :
+			child = StateChartNode(self.statechart, child_xml, self)
+			if not (child.is_composite or child.is_basic or child.is_history) :
+				continue
+			self.children.append(child)
+			
+			#Check if the name of the child is valid
+			child_name = child.name
+			if child_name == "" :
+				raise CompilerException("Found state with no id")
+			if child_name in children_names :
+				raise CompilerException("Found 2 equivalent id's : " + child_name + ".")
+			children_names.append(child_name)
+			
+	def calculateDefaults(self, xml):
+		initial_state = xml.get("initial","")	 
+		
+		if self.is_parallel_state :
+			self.defaults = [child for child in self.children if not child.is_history]
+			if initial_state != "" : 
+				raise CompilerException("Component <" + self.full_name + ">  contains an initial state while being parallel.")	
+		elif initial_state == "" :
+			if self.is_basic or self.is_history:
+				pass
+			elif len(self.children) == 1 :
+				self.defaults = self.children
+			else :
+				raise CompilerException("Component <" + self.full_name + "> contains no default state.") 
+		else :
+			if self.is_basic :
+				raise CompilerException("Component <" + self.full_name + "> contains a default state while being a basic state.")
+			self.defaults = []
+			for child in self.children :
+				if child.name == initial_state :
+					self.defaults.append(child)
+			if len(self.defaults) < 1 :
+				raise CompilerException("Initial state '"+ initial_state + "' referred to, is missing in " + self.full_name)
+			elif len(self.defaults) > 1 :
+				raise CompilerException("Multiple states with the name '" + initial_state + " found in " + self.full_name + " which is referred to as initial state.")
+	
+	def getAncestors(self):
+		""" Returns a list representing the containment hierarchy of node.
+			node is always the first element, and its outermost parent is the last.
+		"""
+		current = self
+		while not current.is_root :
+			current = current.parent
+			yield current
+	
+	def isDescendantOf(self, anc):
+		current = self
+		while not current.is_root :
+			current = current.parent
+			if current == anc :
+				return True
+		return False
+		
+	def isDescendantOrAncestorOf(self, node):
+		return self.isDescendantOf(node) or node.isDescendantOf(self)
+  
+		
+##################################
+
+class StateChart(Visitable):
+
+	def __init__(self, class_obj, statechart_xml):
+		""" Gives the module information on the statechart by listing its basic, orthogonal,
+			composite and history states as well as mapping triggers to names making the
+			appropriate conversion from AFTER() triggers to event names
+		"""
+		
+		self.class_obj = class_obj
+		self.root = StateChartNode(self, statechart_xml); #creates the whole statechart structure recursively
+
+		self.basics = []
+		self.composites = []
+		self.histories = []
+		self.nr_of_after_transitions = 0
+		
+		self.extractFromHierarchy(self.root) #recursively extracts the basics, composites, histories and nr_of_after_transitions
+			
+		# Calculate the history that needs to be taken care of.
+		self.shallow_history_parents = []
+		self.deep_history_parents = []
+		self.combined_history_parents = [] #All nodes that need state saved on leaving
+		for node in self.histories:
+			self.calculateHistory(node.parent, node.is_history_deep)
+			
+	def extractFromHierarchy(self, node):
+		# For each AFTER event, give it a name so that it can be triggered.
+		for transition in node.transitions:
+			trigger = transition.trigger
+			if trigger.isAfter() :
+				trigger.setAfterIndex(self.nr_of_after_transitions)
+				value = "_" + str(trigger.getAfterIndex()) + "after"
+				trigger.setEvent(value)
+				self.nr_of_after_transitions += 1
+				
+		if node.is_basic : 
+			self.basics.append(node)
+		elif node.is_composite : 
+			self.composites.append(node)
+		elif node.is_history : 
+			self.histories.append(node)
+			
+		for child in node.children :
+			self.extractFromHierarchy(child)
+
+	def calculateHistory(self, parent, is_deep):
+		""" Figures out which components need to be kept track of for history.
+		"""
+		if parent == self.root:
+			raise CompilerException("Root component cannot contain a history state.")
+		if parent not in self.combined_history_parents:
+			self.combined_history_parents.append(parent)
+			parent.save_state_on_exit = True
+		if is_deep :
+			if parent not in self.deep_history_parents:
+				self.deep_history_parents.append(parent)
+		else :
+			if parent not in self.shallow_history_parents:
+				self.shallow_history_parents.append(parent)
+		if parent.is_parallel_state or is_deep :
+			for i in parent.children:
+				if i.is_composite :
+					self.calculateHistory(i, is_deep)
+	
+###################################
+
+class Association(Visitable):
+	def __init__(self, to_class, min_card, max_card, name):
+		self.min = min_card
+		self.max = max_card #N is represented as -1
+		self.to_class = to_class
+		self.name = name
+		
+###################################
+class FormalParameter(Visitable):
+	def __init__(self, param_ident, param_type, default = None):
+		self.param_type = param_type
+		self.identifier = param_ident
+		self.default = default  
+			
+	def getType(self):
+		return self.param_type
+			
+	def getIdent(self):
+		return self.identifier
+	
+	def hasDefault(self):
+		return self.default is not None
+	
+	def getDefault(self):
+		return self.default
+	
+#slight hack because of lacking multiple constructors
+class XMLFormalParameter(FormalParameter):
+	def __init__(self, xml):
+		self.param_type = xml.get("type", "")
+		self.identifier = xml.get("name","")
+		self.default = xml.get("default",None)
+	
+###################################
+class Method(Visitable):
+	def __init__(self, xml, parent_class):
+		self.name = xml.get("name", "")
+		self.access = xml.get("access", "public")
+		parameters = xml.findall("parameter")
+		self.parameters = []
+		for p in parameters:
+			self.parameters.append(XMLFormalParameter(p))
+		bodies = xml.findall("body")
+		if len(bodies) != 1 : 
+			raise CompilerException("Method needs one and only one body element.")
+		self.body = bodies[0].text
+		self.parent_class = parent_class
+		self.return_type = xml.get('type',"")
+		
+	def getParams(self):
+		return self.parameters
+		
+###################################		
+class Constructor(Method):
+	def __init__(self, xml, parent_class):
+		if xml is None :
+			self.body = ""
+			self.name = ""
+			self.access = "public"			
+			self.parent_class = parent_class
+			self.return_type = ""
+			self.parameters = []
+		else :
+			Method.__init__(self, xml, parent_class)	  
+		
+class Destructor(Method):
+	def __init__(self, xml, parent_class):
+		Method.__init__(self, xml, parent_class)  
+		
+###################################		 
+class Attribute(Visitable):
+	def __init__(self, xml):
+		self.name = xml.get('name',"")
+		self.type = xml.get('type',"")
+		self.init_value = xml.get("init-value", None)
+		
+	def getIdent(self):
+		return self.name
+	
+	def getType(self):
+		return self.type
+	
+	def getInit(self):
+		return self.init_value
+		
+###################################
+
+class Class(Visitable):
+	def __init__(self, xml):
+
+		self.xml = xml
+		self.name = xml.get("name", "")
+		
+		self.constructors = []
+		self.destructors = []
+		self.methods = []
+		self.statechart = None
+
+		self.inports = []
+		self.outports = []
+		self.attributes = []
+		self.associations = []
+		self.super_classes = []
+		
+		self.process()
+		
+	def getName(self):
+		return self.name
+		
+	def processMethod(self, method_xml) :
+		name = method_xml.get("name", "")
+		if name == self.name :
+			self.constructors.append(Constructor(method_xml, self))
+		elif name == '~' + self.name:
+			self.destructors.append(Destructor(method_xml, self))
+		else :
+			if name in reserved:
+				raise CompilerException("Reserved word \"" + name + "\" used as method in class <" + self.name + ">.")
+			self.methods.append( Method(method_xml, self))
+
+	def processAttribute(self, attribute_xml):
+		attribute = Attribute(attribute_xml)
+		if attribute.name in reserved:
+			raise CompilerException("Reserved word \"" + attribute.name + "\" used as variable in class <" + self.name + ">.")
+
+		self.attributes.append(attribute)
+	
+	def processInheritances(self, inheritances):
+		# process each inheritance, stores a dict with each subclass as the key
+		# and a list of tuples (superclass, priority) as the value. The priority
+		# tells us which class to inherit from first for multiple inheritance. Gives
+		# a WARNING with a given inheritance order if two priorities are the same
+		for i in inheritances :
+			self.super_classes.append((i.get("class",""),i.get("priority",1)))
+			
+		self.super_classes.sort(lambda a, b: cmp(a[1], b[1]))
+		priorityChecker = {}
+		for super_class, priority in self.super_classes:
+			if priority in priorityChecker:
+				checkIt = priorityChecker[priority]
+			else:
+				checkIt = []
+			if super_class not in checkIt:
+				checkIt.append(super_class)
+			priorityChecker[priority] = checkIt
+		for priority, checkIt in priorityChecker.iteritems():
+			if len(checkIt) > 1:
+				Logger.showWarning("Class <" + self.name + "> inherits from classes <" + ", ".join(checkIt) + "> with same priority <" + str(priority) + ">. Given inheritance order is chosen.")
+				
+		self.super_classes = [entry[0] for entry in self.super_classes]		
+		
+	def processAssociations(self, associations):
+		for a in associations :
+			class_name = a.get("class","")
+			if not class_name :
+				raise CompilerException("Faulty association.")
+			card_min_string = a.get("min","0")
+			try :
+				card_min = int(card_min_string)
+				if card_min < 0 :
+					raise ValueError()
+			except ValueError :
+				raise CompilerException("Faulty card-min value in association.")
+			card_max_string = a.get("max","N")
+			if card_max_string == "N" :
+				card_max = -1
+			else :
+				try :
+					card_max = int(card_max_string)
+					if card_max < card_min :
+						raise ValueError()
+				except ValueError :
+					raise CompilerException("Faulty card-max value in association.") 
+			
+			association_name = a.get("name","")
+			if not association_name :
+				raise CompilerException("Faulty association. No name.")
+			if association_name in reserved : 
+				raise CompilerException("Reserved word \"" + association_name + "\" used as association name in class <" + self.name + ">.")
+			self.associations.append(
+				Association(class_name, card_min, card_max, association_name)
+			)
+			
+
+	def process(self):
+		inports = self.xml.findall("inport")
+		for i in inports:
+			name = i.get("name")
+			if name in self.inports:
+				raise CompilerException("Found 2 inports with the same name : " + name + ".")
+			self.inports.append(name)
+
+		outports = self.xml.findall("outport")
+		for i in outports:
+			name = i.get("name")
+			if name in self.outports:
+				raise CompilerException("Found 2 outports with the same name : " + name + ".")
+			self.outports.append(name)
+
+		attributes = self.xml.findall("attribute")
+		for a in attributes:
+			self.processAttribute(a)
+
+		methods = self.xml.findall("method")
+		for m in methods:
+			self.processMethod(m)
+		
+		if len(self.destructors) > 1 :
+			raise CompilerException("Multiple destructors defined for class <" + self.name + ">.")
+		
+		if len(self.constructors) < 1 :
+			#add a default constructor
+			self.constructors.append(Constructor(None,self))
+
+		associations = []
+		inheritances = []
+		relationships = self.xml.findall("relationships")
+		for relationship_wrapper in relationships :
+			associations.extend(relationship_wrapper.findall("association"))
+			inheritances.extend(relationship_wrapper.findall("inheritance"))
+			
+		self.processAssociations(associations)
+		self.processInheritances(inheritances)
+
+		statecharts = self.xml.findall("scxml")
+		if len(statecharts) > 1 :
+			raise CompilerException("Multiple statecharts found in class <" + self.name + ">.")
+		if len(statecharts) == 1 :
+			self.statechart = StateChart(self, statecharts[0])
+			
+###################################
+class ClassDiagram(Visitable):
+	def __init__(self, input_file):
+		diagram_dir = os.path.dirname(input_file)
+		tree = ET.parse(input_file)
+		self.root = tree.getroot()
+		self.name = self.root.get("name", "")
+		self.author = self.root.get("author", "")
+		descriptions = self.root.findall("description")
+		if descriptions : 
+			self.description = descriptions[0].text
+		else :
+			self.description = ""
+
+		xml_classes = self.root.findall("class")
+		# make sure at least one class is given
+		if not xml_classes :
+			raise CompilerException("Found no classes to compile.")
+
+		# check if class diagram is valid
+		# unique class names
+		self.class_names = []
+		substituted_xml_classes = []
+		for xml_class in xml_classes :
+			class_src = xml_class.get("src", "")
+			class_default = xml_class.get("default", "")
+			if class_src != "":
+				if not os.path.isabs(class_src):
+					class_src = os.path.join(diagram_dir, class_src)
+				substituted_xml_class = ET.parse(class_src).getroot()
+			else:
+				substituted_xml_class = xml_class
+			substituted_xml_class.is_default = (class_default.lower() == "true")
+			name = substituted_xml_class.get("name", "")
+			if name == "" :
+				raise CompilerException("Missing or emtpy class name.")
+			if name in self.class_names :
+				raise CompilerException("Found 2 classes with the same name : " + name + ".")
+			self.class_names.append(name)
+			substituted_xml_classes.append(substituted_xml_class)
+	
+		# process in and output ports
+		inports = self.root.findall("inport")
+		names = []
+		for xml_inport in inports :
+			name = xml_inport.get("name", "")
+			if name in names :
+				raise CompilerException("Found 2 INPorts with the same name : " + name + ".")
+			names.append(name)
+		self.inports = names
+		
+		outports = self.root.findall("outport")
+		names = []
+		for xml_outport in outports :
+			name = xml_outport.get("name", "")
+			if name in names :
+				raise CompilerException("Found 2 OUTPorts with the same name : " + name + ".")
+			names.append(name)
+		self.outports = names
+			
+		
+		# any inital import code that has to come at the top of the generate file
+		tops = self.root.findall("top")
+		self.includes = []
+		if len(tops) == 1 :
+			self.top = tops[0].text
+		elif len(tops) > 1 : 
+			raise CompilerException("Class diagram can only have one <top> element.")
+		else :
+			self.top = ""
+		
+		# process each class in diagram
+		self.classes = []
+		default_classes = []
+	
+		for xml_class in substituted_xml_classes:
+			processed_class = None
+			try :
+				processed_class = Class(xml_class)
+			except CompilerException as e :
+				e.message = "Class <" + xml_class.get("name", "") + "> failed compilation. " + e.message
+				raise e
+	
+			# let user know this class was successfully loaded
+			Logger.showInfo("Class <" + processed_class.name + "> has been successfully loaded.")
+			self.classes.append(processed_class)
+			if xml_class.is_default :
+				default_classes.append(processed_class)
+			
+		if not default_classes or len(default_classes) > 1:
+			if len(self.classes) == 1 :
+				Logger.showInfo("Only one class given. Using <" + self.classes[0].getName() + "> as the default class.")
+				default_classes.append(self.classes[0])
+			else :
+				raise CompilerException("Provide one and only one default class to instantiate on start up.")
+		self.default_class = default_classes[0]

+ 701 - 0
debugging_environment/python_sccd_compiler/csharp_generator.py

@@ -0,0 +1,701 @@
+"""Generates C#"""
+
+import time
+from constructs import FormalParameter
+from code_generation import CodeGenerator, Platforms
+
+class CSharpGenerator(CodeGenerator):
+    
+    def __init__(self):
+        self.supported_platforms = [Platforms.Threads, Platforms.GameLoop]
+                
+    def visit_ClassDiagram(self, class_diagram):
+        self.fOut.write("/*")
+        self.fOut.indent()
+        self.fOut.write("Statecharts + Class Diagram compiler by Glenn De Jonghe")
+        self.fOut.write()
+        self.fOut.write("Date:   " + time.asctime())
+        if class_diagram.name or class_diagram.author or class_diagram.description:
+            self.fOut.write()
+        if class_diagram.author:
+            self.fOut.write("Model author: " + class_diagram.author)
+        if class_diagram.name:
+            self.fOut.write("Model name:   " + class_diagram.name)
+        if class_diagram.description.strip():
+            self.fOut.write("Model description:")
+            self.fOut.write()
+            self.fOut.indent()
+            self.fOut.write(class_diagram.description.strip())
+            self.fOut.dedent()
+        self.fOut.dedent()
+        self.fOut.write('*/')
+        self.fOut.write()
+        
+        #Namespace using declarations by the user
+        self.fOut.write('using System;')
+        self.fOut.write('using System.Collections.Generic;')
+        self.fOut.write('using sccdlib;')
+
+        #User imports
+        if class_diagram.top.strip():
+            self.writeCodeCorrectIndent(class_diagram.top)
+        self.fOut.write()
+        
+        #visit children
+        for c in class_diagram.classes :
+            c.accept(self)
+         
+        #writing out ObjectManager
+        self.fOut.write('public class ObjectManager : ObjectManagerBase')
+        self.fOut.write('{')
+        self.fOut.indent()
+        self.fOut.write('public ObjectManager(ControllerBase controller): base(controller)')
+        self.fOut.write("{")
+        self.fOut.write("}")
+        self.fOut.write()
+        
+        self.fOut.write('protected override InstanceWrapper instantiate(string class_name, object[] construct_params)')
+        self.fOut.write('{')
+        self.fOut.indent()
+        self.fOut.write("RuntimeClassBase instance = null;")
+        self.fOut.write("List<Association> associations = new List<Association>();")
+        for index, c in enumerate(class_diagram.classes) :
+            if index == 0 :
+                self.fOut.write()
+            else :
+                self.fOut.write('}else ')
+            self.fOut.extendWrite('if (class_name == "' + c.name + '" ){')
+            self.fOut.indent()
+            self.fOut.write('object[] new_parameters = new object[construct_params.Length + 1];')
+            self.fOut.write('new_parameters[0] = this.controller;')
+            self.fOut.write('Array.Copy(construct_params, 0, new_parameters, 1, construct_params.Length);')
+            self.fOut.write('instance = (RuntimeClassBase) Activator.CreateInstance(typeof(' + c.name + '), new_parameters);')
+            for a in c.associations :
+                a.accept(self)
+            self.fOut.dedent()
+            if index == len(class_diagram.classes)-1 :
+                self.fOut.write('}')
+            
+        self.fOut.write('if (instance != null) {')
+        self.fOut.indent()
+        self.fOut.write('return new InstanceWrapper(instance, associations);')
+        self.fOut.dedent()
+        self.fOut.write('}')
+        self.fOut.write('return null;')
+        self.fOut.dedent()
+        self.fOut.write('}')
+        self.fOut.dedent()
+        self.fOut.write('}')
+        
+        # write out controller
+        self.fOut.write()
+        if self.platform == Platforms.Threads :
+            controller_sub_class = "ThreadsControllerBase"
+        elif self.platform == Platforms.GameLoop :
+            controller_sub_class = "GameLoopControllerBase"
+        self.fOut.write("public class Controller : " + controller_sub_class)
+        self.fOut.write("{")
+        self.fOut.indent()
+    
+        # write out constructor(s)
+        if class_diagram.default_class.constructors :
+            for constructor in class_diagram.default_class.constructors :
+                self.writeControllerConstructor(class_diagram, constructor.parameters)
+        else :
+            self.writeControllerConstructor(class_diagram)
+        
+        self.fOut.write("public static void Main()")
+        self.fOut.write("{")
+        self.fOut.indent()
+        self.fOut.write("Controller controller = new Controller();")
+        self.fOut.write("controller.start();")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        
+        self.fOut.dedent()
+        self.fOut.write("}")
+        
+    #helper method
+    def writeControllerConstructor(self, class_diagram, parameters = []):
+        self.fOut.write('public Controller(')
+        self.writeFormalParameters(parameters + [FormalParameter("keep_running", "bool", "true")])
+        self.fOut.extendWrite(") : base(keep_running)")
+        self.fOut.write('{')
+        self.fOut.indent()
+        
+        for p in class_diagram.inports:
+            self.fOut.write('this.addInputPort("' + p + '");')
+        for p in class_diagram.outports:
+            self.fOut.write('this.addOutputPort("' + p + '");')
+        self.fOut.write('this.object_manager = new ObjectManager(this);')
+        actual_parameters = [p.getIdent() for p in parameters]
+        self.fOut.write('this.object_manager.createInstance("'+ class_diagram.default_class.name +'", new object[]{' +  ', '.join(actual_parameters)+ '});')
+        self.fOut.dedent()
+        self.fOut.write('}')
+
+    def visit_Class(self, class_node):
+        """
+        Generate code for Class construct
+        """
+        self.fOut.write()
+        self.fOut.write("public class " + class_node.name )
+        # Take care of inheritance
+        if len(class_node.super_classes) > 1 :
+            raise Exception("C# doesn't allow multiple inheritance.");
+        elif len(class_node.super_classes) == 1 :
+            self.fOut.extendWrite(" : " + class_node.super_classes[0])
+        else :
+            self.fOut.extendWrite(" : " + "RuntimeClassBase")
+        self.fOut.write("{")
+        self.fOut.indent()
+        self.fOut.write()
+        
+        if class_node.statechart is not None:
+            # assign each node a unique ID
+            self.fOut.write("/// <summary>")
+            self.fOut.write("/// Enum uniquely representing all statechart nodes.")
+            self.fOut.write("/// </summary>")
+            self.fOut.write("public enum Node {")
+            self.fOut.indent()
+            for node in class_node.statechart.composites + class_node.statechart.basics:
+                self.fOut.write(node.full_name + ",");
+            self.fOut.dedent();
+            self.fOut.write("};")
+            self.fOut.write()
+            self.fOut.write("Dictionary<Node,List<Node>> current_state = new Dictionary<Node,List<Node>>();");
+            if len(class_node.statechart.histories) > 0 :
+                self.fOut.write("Dictionary<Node,List<Node>> history_state = new Dictionary<Node,List<Node>>();");
+            self.fOut.write();
+            
+        #User defined attributes
+        if class_node.attributes:
+            self.fOut.write("//User defined attributes")
+            for attribute in class_node.attributes:
+                self.fOut.write(attribute.type + " " + attribute.name)
+                if attribute.init_value is not None :
+                    self.fOut.write(" = " + attribute.init_value);
+                self.fOut.extendWrite(";")     
+            self.fOut.write()
+
+        if class_node.statechart is not None:  
+            self.fOut.write("/// <summary>")
+            self.fOut.write("/// Constructor part that is common for all constructors.")
+            self.fOut.write("/// </summary>")
+            self.fOut.write("private void commonConstructor(ControllerBase controller = null)")
+            self.fOut.write("{")
+            self.fOut.indent() 
+            self.fOut.write("this.controller = controller;")
+            self.fOut.write("this.object_manager = controller.getObjectManager();")
+            if class_node.statechart.nr_of_after_transitions != 0:
+                self.fOut.write("this.timers = new Dictionary<int,double>();")
+
+            self.fOut.write()
+            self.fOut.write("//Initialize statechart :")
+            self.fOut.write()
+
+            if class_node.statechart.histories:
+                for node in class_node.statechart.combined_history_parents:
+                    self.fOut.write("this.history_state[Node." + node.full_name + "] = new List<Node>();")
+                self.fOut.write()
+
+            for node in class_node.statechart.composites :
+                self.fOut.write("this.current_state[Node." + node.full_name + "] = new List<Node>();")
+                
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+        
+        self.fOut.write("public override void start()")
+        self.fOut.write("{")
+        
+        self.fOut.indent()
+        self.fOut.write("base.start();")
+        for default_node in class_node.statechart.root.defaults:
+            if default_node.is_composite:
+                self.fOut.write("this.enterDefault_" + default_node.full_name + "();")
+            elif default_node.is_basic:
+                self.fOut.write("this.enter_" + default_node.full_name + "();")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+        
+        #visit children
+        for i in class_node.constructors :
+            i.accept(self)
+        for i in class_node.destructors :
+            i.accept(self)
+        for i in class_node.methods :
+            i.accept(self)
+        if class_node.statechart is not None:
+            class_node.statechart.accept(self)
+          
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+
+    def writeFormalParameters(self, parameters = []):
+        """Helper method that writes a correct comma separated list of formal parameters"""    
+        first = True       
+        for param in parameters :
+            if first :
+                first = False
+            else :
+                self.fOut.extendWrite(', ')
+            param.accept(self)
+        
+    def visit_FormalParameter(self, formal_parameter):
+        self.fOut.extendWrite(formal_parameter.getType() + " " + formal_parameter.getIdent())
+        if formal_parameter.hasDefault() :
+            self.fOut.extendWrite(" = " + formal_parameter.getDefault())
+                    
+    def visit_Constructor(self, constructor):
+
+        self.fOut.write(constructor.access + " " + constructor.parent_class.name + "(")
+        self.writeFormalParameters([FormalParameter("controller", "ControllerBase", None)] + constructor.getParams())
+        self.fOut.extendWrite(")")
+        self.fOut.write("{")
+        self.fOut.indent()
+        self.fOut.write("this.commonConstructor(controller);")
+        if constructor.body :
+            self.fOut.write()
+            self.fOut.write("//constructor body (user-defined)")
+            self.writeCodeCorrectIndent(constructor.body)
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+        
+    def visit_Destructor(self, destructor):
+        self.fOut.write("~" + destructor.parent_class.name + "()")
+        self.fOut.write("{")
+        if destructor.body :
+            self.fOut.indent()
+            self.writeCodeCorrectIndent(destructor.body)
+            self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+        
+    def visit_Method(self, method):
+        self.fOut.write(method.access + " " + method.return_type + " " + method.name + "(")
+        self.writeFormalParameters(method.getParams())
+        self.fOut.extendWrite(")")
+        self.fOut.write("{")
+        self.fOut.indent()
+        if method.body :
+            self.fOut.indent()
+            self.writeCodeCorrectIndent(method.body)
+            self.fOut.dedent()
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+        
+    def visit_Association(self, association):
+        self.fOut.write('associations.Add(new Association("' + association.name + '", "' + association.to_class + '", ' + str(association.min) + ', ' + str(association.max) + '));')
+        
+    #helper method
+    def writeTransitionsRecursively(self, current_node):
+        self.fOut.write("private bool transition_" + current_node.full_name + "(Event e)")
+        self.fOut.write("{")
+        self.fOut.indent()
+        
+        valid_children = []
+        for child in current_node.children :
+            if child.is_composite or child.is_basic :
+                valid_children.append(child)  
+         
+        self.fOut.write("bool catched = false;")
+        do_dedent = False
+        if current_node.solves_conflict_outer :
+            self.writeFromTransitions(current_node)
+            if current_node.is_parallel_state or current_node.is_composite :
+                self.fOut.write("if (!catched){")
+                self.fOut.indent()
+                do_dedent = True
+            
+        if current_node.is_parallel_state:
+            for child in valid_children :     
+                self.fOut.write("catched = this.transition_" + child.full_name + "(e) || catched;")
+        elif current_node.is_composite:
+            self.fOut.write()
+            for i, child in enumerate(valid_children) :
+                if i > 0 :
+                    self.fOut.extendWrite(" else ")
+                self.fOut.extendWrite("if (this.current_state[Node." + current_node.full_name + "][0] == Node." + child.full_name + "){")
+                self.fOut.indent()
+                self.fOut.write("catched = this.transition_" + child.full_name + "(e);")
+                self.fOut.dedent()
+                self.fOut.write("}")
+                
+        if current_node.solves_conflict_outer :
+            if do_dedent :
+                self.fOut.dedent()
+                self.fOut.write("}")
+        elif len(current_node.transitions) > 0 :
+                self.fOut.write("if (!catched) {")
+                self.fOut.indent()
+                self.writeFromTransitions(current_node)
+                self.fOut.dedent()
+                self.fOut.write("}")
+            
+        self.fOut.write("return catched;")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write();
+        
+        for child in valid_children :
+            self.writeTransitionsRecursively(child)
+                
+    #helper method
+    def writeFromTransitions(self, current_node): 
+        # get all transition out of this state
+        out_transitions = current_node.transitions
+        if len(out_transitions) == 0 :
+            return
+        
+        self.fOut.write('List<int> enableds = new List<int>();')
+        for index, transition in enumerate(out_transitions):
+            self.writeTransitionCondition(transition, index)
+            
+        self.fOut.write("if (enableds.Count > 1){")
+        self.fOut.indent()
+        self.fOut.write('Console.WriteLine("Runtime warning : indeterminism detected in a transition from node ' +  current_node.full_name+ '. Only the first in document order enabled transition is executed.");')
+        self.fOut.dedent()
+        self.fOut.write('}')
+        self.fOut.write("if (enableds.Count > 0){")
+        self.fOut.indent()
+        self.fOut.write('int enabled = enableds[0];')
+        self.fOut.write()      
+              
+        for index, transition in enumerate(out_transitions):
+            self.writeTransitionAction(transition, index)
+        
+        self.fOut.write('catched = true;')   
+        self.fOut.dedent()
+        self.fOut.write('}')         
+        self.fOut.write()
+        
+    def visit_FormalEventParameter(self, formal_event_parameter):
+        self.fOut.extendWrite(formal_event_parameter.getType() + " " + formal_event_parameter.name)
+        
+    def writeFormalEventParameters(self, transition):
+        parameters = transition.getTrigger().getParameters()
+        if(len(parameters) > 0) :
+            self.fOut.write('object[] parameters = e.getParameters();')
+            for index, parameter in enumerate(parameters):
+                self.fOut.write()
+                parameter.accept(self)
+                self.fOut.extendWrite(' = (' + parameter.getType() + ')parameters[' + str(index) + '];')
+        
+    def writeTransitionAction(self, transition, index):
+        if index > 1 :
+            self.fOut.extendWrite(" else ")
+        else :
+            self.fOut.write()
+        self.fOut.extendWrite("if (enabled == " + str(index) + "){")
+        self.fOut.indent()
+
+        # handle parameters to actually use them             
+        self.writeFormalEventParameters(transition)
+        
+        exits = transition.getExitNodes()
+        
+        # write out exit actions
+        if not exits[-1].is_basic:
+            self.fOut.write("this.exit_" + exits[-1].full_name + "();")
+        else:
+            for node in exits:
+                if node.is_basic:
+                    self.fOut.write("this.exit_" + node.full_name + "();")
+                    
+        # write out trigger actions
+        transition.getAction().accept(self)
+        
+        for (entering_node, is_ending_node) in transition.getEnterNodes() : 
+            if is_ending_node :
+                if entering_node.is_composite:
+                    self.fOut.write("this.enterDefault_" + entering_node.full_name + "();")
+                elif entering_node.is_history:
+                    if (entering_node.is_history_deep) :
+                        self.fOut.write("this.enterHistoryDeep_" + entering_node.parent.full_name + "();")
+                    else :
+                        self.fOut.write("this.enterHistoryShallow_" + entering_node.parent.full_name + "();")
+                else:
+                    self.fOut.write("this.enter_" + entering_node.full_name + "();")
+            else :
+                if entering_node.is_composite:
+                    self.fOut.write("this.enter_" + entering_node.full_name + "();")
+
+        self.fOut.dedent()
+        self.fOut.write('}')
+                        
+    def writeTransitionCondition(self, transition, index):
+        trigger = transition.getTrigger()
+        if not trigger.isUC():  
+            self.fOut.write('if (e.getName() == "' + trigger.getEvent() + '" && e.getPort() == "' + trigger.getPort() + '"){')
+            self.fOut.indent()   
+        # evaluate guard
+        if transition.hasGuard() :   
+            # handle parameters for guard evaluation       
+            self.writeFormalEventParameters(transition)  
+
+            self.fOut.write('if (')
+            transition.getGuard().accept(self)
+            self.fOut.extendWrite('){')
+            self.fOut.indent()    
+            
+        self.fOut.write("enableds.Add(" + str(index) + ");")
+
+        if transition.hasGuard() :
+            self.fOut.dedent()
+            self.fOut.write('}')
+        if not trigger.isUC() :
+            self.fOut.dedent()
+            self.fOut.write('}')
+        self.fOut.write()
+    
+    def visit_EnterAction(self, enter_method):
+        parent_node = enter_method.parent_node
+        self.fOut.write("private void enter_" + parent_node.full_name + "()")
+        self.fOut.write("{")
+        self.fOut.indent()
+        
+        # take care of any AFTER events
+        for transition in parent_node.transitions :
+            trigger = transition.getTrigger()
+            if trigger.isAfter() :
+                self.fOut.write("this.timers[" + str(trigger.getAfterIndex()) + "] = ")
+                trigger.after.accept(self)
+                self.fOut.extendWrite(";")
+        if enter_method.action:
+            enter_method.action.accept(self)
+        self.fOut.write("this.current_state[Node." + parent_node.parent.full_name + "].Add(Node." + parent_node.full_name + ");")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+        
+    #helper method
+    def writeEnterDefault(self, entered_node):
+        self.fOut.write("private void enterDefault_" + entered_node.full_name + "()")
+        self.fOut.write("{")
+        self.fOut.indent()
+        self.fOut.write("this.enter_" + entered_node.full_name + "();")
+        if entered_node.is_composite:
+            l = entered_node.defaults
+            for i in l:
+                if i.is_composite:
+                    self.fOut.write("this.enterDefault_" + i.full_name + "();")
+                elif i.is_basic:
+                    self.fOut.write("this.enter_" + i.full_name + "();")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+         
+    def visit_ExitAction(self, exit_method):
+        exited_node = exit_method.parent_node
+        self.fOut.write("private void exit_" + exited_node.full_name + "()")
+        self.fOut.write("{")
+        self.fOut.indent()
+        #If the exited node is composite take care of potential history and the leaving of descendants
+        if exited_node.is_composite :
+            #handle history
+            if exited_node.save_state_on_exit:
+                self.fOut.write("this.history_state[Node." + exited_node.full_name + "].AddRange(this.current_state[Node." + exited_node.full_name + "]);")
+            
+            #Take care of leaving children
+            children = exited_node.children
+            if exited_node.is_parallel_state:
+                for child in children:
+                    if not child.is_history :
+                        self.fOut.write("this.exit_" + child.full_name + "();")
+            else:
+                for child in children:
+                    if not child.is_history :
+                        self.fOut.write("if (this.current_state[Node." + exited_node.full_name + "].Contains(Node." + child.full_name +  ")){")
+                        self.fOut.indent()
+                        self.fOut.write("this.exit_" + child.full_name + "();")
+                        self.fOut.dedent()  
+                        self.fOut.write("}")
+        
+        
+        # take care of any AFTER events
+        for transition in exited_node.transitions :
+            trigger = transition.getTrigger()
+            if trigger.isAfter() :
+                self.fOut.write("this.timers.Remove(" + str(trigger.getAfterIndex()) + ");")
+                
+        #Execute user-defined exit action if present
+        if exit_method.action:
+            exit_method.action.accept(self)
+            
+        #Adjust state
+        self.fOut.write("this.current_state[Node." + exited_node.parent.full_name + "].Remove(Node." + exited_node.full_name + ");")
+
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+        
+            
+    #helper method
+    def writeEnterHistory(self, entered_node, is_deep):
+        self.fOut.write("private void enterHistory" + ("Deep" if is_deep else "Shallow") + "_" + entered_node.full_name + "()")
+        self.fOut.write("{")
+        self.fOut.indent()
+        self.fOut.write("if (this.history_state[Node." + entered_node.full_name + "].Count == 0){")
+        self.fOut.indent()
+        defaults = entered_node.defaults
+
+        for node in defaults:
+            if node.is_basic :
+                self.fOut.write("this.enter_" + node.full_name + "();")
+            elif node.is_composite :
+                self.fOut.write("this.enterDefault_" + node.full_name + "();")
+
+        self.fOut.dedent()
+        self.fOut.write("} else {")
+        self.fOut.indent()
+        children = entered_node.children
+        if entered_node.is_parallel_state:
+            for child in children:
+                if not child.is_history :
+                    self.fOut.write("this.enterHistory" + ("Deep" if is_deep else "Shallow") + "_" + child.full_name + "();")
+        else:
+            for child in children:
+                if not child.is_history :
+                    self.fOut.write("if (this.history_state[Node." + entered_node.full_name + "].Contains(Node." + child.full_name + ")){")
+                    self.fOut.indent()
+                    if child.is_composite:
+                        if is_deep :
+                            self.fOut.write("this.enter_" + child.full_name + "();")
+                            self.fOut.write("this.enterHistoryDeep_" + child.full_name + "();")
+                        else :
+                            self.fOut.write("this.enterDefault_" + child.full_name + "();")
+                    else:
+                        self.fOut.write("this.enter_" + child.full_name + "();")
+                    self.fOut.dedent()
+                    self.fOut.write("}")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+
+    def visit_StateChart(self, statechart):
+        self.fOut.write("//Statechart enter/exit action method(s) :")
+        self.fOut.write()
+        
+        #visit enter and exit actions of children
+        for i in statechart.composites + statechart.basics:
+            if i is not statechart.root :
+                i.enter_action.accept(self)
+                i.exit_action.accept(self)
+
+        # write out statecharts methods for enter/exit state
+        if len(statechart.composites) > 1 :
+            self.fOut.write("//Statechart enter/exit default method(s) :")
+            self.fOut.write()
+            for i in statechart.composites :
+                if i is not statechart.root :
+                    self.writeEnterDefault(i)
+
+        # write out statecharts methods for enter/exit history
+        if statechart.histories:
+            self.fOut.write("//Statechart enter/exit history method(s) :")
+            self.fOut.write()
+            for i in statechart.shallow_history_parents:
+                self.writeEnterHistory(i, False)
+            for i in statechart.deep_history_parents:
+                self.writeEnterHistory(i, True)   
+                
+        self.fOut.write("//Statechart transitions :")
+        self.fOut.write()
+        self.writeTransitionsRecursively(statechart.root)            
+                
+        # write out transition function
+        self.fOut.write("protected override void transition (Event e = null)")
+        self.fOut.write("{")
+        self.fOut.indent()
+        self.fOut.write("if (e == null) {");
+        self.fOut.indent()
+        self.fOut.write("e = new Event();")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write("this.state_changed = this.transition_" + statechart.root.full_name + "(e);")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+
+        # write out inState function
+        self.fOut.write("public bool inState(List<Node> nodes)")
+        self.fOut.write("{")
+        self.fOut.indent()
+        self.fOut.write("foreach(List<Node> actives in current_state.Values){")
+        self.fOut.indent()
+        self.fOut.write("foreach(Node node in actives)")
+        self.fOut.indent()
+        self.fOut.write("nodes.Remove (node);")
+        self.fOut.dedent()
+        self.fOut.write("if (nodes.Count == 0){")
+        self.fOut.indent()
+        self.fOut.write("return true;")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write("return false;")
+        self.fOut.dedent()
+        self.fOut.write("}")
+        self.fOut.write()
+        
+    def visit_ExpressionPartString(self, bare_string):
+        self.fOut.extendWrite(bare_string.string)
+        
+    def visit_SelfReference(self, self_reference):
+        self.fOut.extendWrite("this")
+        
+    def visit_StateReference(self, state_ref):
+        self.fOut.extendWrite("new List<Node>() {")
+        self.fOut.extendWrite(", ".join(["Node." + node.full_name for node in state_ref.getNodes()]))
+        self.fOut.extendWrite("}")
+        
+    def visit_InStateCall(self, in_state_call):
+        self.fOut.extendWrite("this.inState(")
+        in_state_call.target.accept(self)
+        self.fOut.extendWrite(")")
+        
+    def visit_RaiseEvent(self, raise_event):
+        if raise_event.isNarrow() or raise_event.isBroad():
+            self.fOut.write('Event send_event = new Event("' + raise_event.getEventName() + '", "", new object[] {')
+        elif raise_event.isLocal():
+            self.fOut.write('this.addEvent( new Event("' + raise_event.getEventName() +'", "", new object[] {')
+        elif raise_event.isOutput():
+            self.fOut.write('this.controller.outputEvent(new Event("' + raise_event.getEventName() + '", "' + raise_event.getPort() + '", new object[] {')
+        elif raise_event.isCD():
+            self.fOut.write('this.object_manager.addEvent(new Event("' + raise_event.getEventName() + '", "", new object[] { this, ')
+        first_param = True
+        for param in raise_event.getParameters() :
+            if first_param :
+                first_param = False
+            else :
+                self.fOut.extendWrite(',')
+            param.accept(self)
+        if raise_event.isNarrow():
+            self.fOut.extendWrite('});')
+            self.fOut.write('this.object_manager.addEvent(new Event("narrow_cast", "", new object[] {this, "' + raise_event.getTarget() + '" ,send_event}));')
+        elif raise_event.isBroad():
+            self.fOut.extendWrite('});')
+            self.fOut.write('this.object_manager.addEvent(new Event("broad_cast", "", new object[] {send_event}));')
+        else :
+            self.fOut.extendWrite('}));')
+            
+    def visit_Script(self, script):
+        self.writeCodeCorrectIndent(script.code)
+        
+    def visit_Log(self, log):
+        self.fOut.write('Console.WriteLine("' + log.message + '");')
+        
+    def visit_Assign(self, assign):
+        self.fOut.write()
+        assign.lvalue.accept(self)
+        self.fOut.extendWrite(" = ")
+        assign.expression.accept(self)
+        self.fOut.extendWrite(";")
+        

+ 714 - 0
debugging_environment/python_sccd_compiler/javascript_generator.py

@@ -0,0 +1,714 @@
+import time
+from constructs import FormalParameter
+from code_generation import CodeGenerator, Platforms
+
+class JavascriptGenerator(CodeGenerator):
+	
+	def __init__(self):
+		self.supported_platforms = [Platforms.Threads, Platforms.GameLoop]
+				
+	def visit_ClassDiagram(self, class_diagram):
+		# header
+		self.fOut.write("/**");
+		self.fOut.write(" * Statechart compiler by Glenn De Jonghe")
+		self.fOut.write(" * Javascript generator by Joeri Exelmans")
+		self.fOut.write(" * ")
+		self.fOut.write(" * Date:   " + time.asctime())
+		if class_diagram.name or class_diagram.author or class_diagram.description:
+			self.fOut.write(" * ")
+		if class_diagram.author:
+			self.fOut.write(" * Model author: " + class_diagram.author)
+		if class_diagram.name:
+			self.fOut.write(" * Model name:   " + class_diagram.name)
+		if class_diagram.description.strip():
+			self.fOut.write(" * Model description:")
+			self.fOut.indent()
+			self.fOut.write(class_diagram.description.strip())
+			self.fOut.dedent()
+		self.fOut.write(" */")
+		
+		self.fOut.write()
+
+		self.fOut.write("// put everything in an object (serves as \"namespace\")")
+		self.fOut.write(class_diagram.name + " = {};")
+		self.fOut.write()
+		self.fOut.write("// closure scope")
+		self.fOut.write("(function() {")
+		self.fOut.write()
+		
+		#visit children
+		for c in class_diagram.classes :
+			c.accept(self)
+			self.fOut.write("// put class in global diagram object")
+			self.fOut.write(class_diagram.name + '.' + c.name + ' = ' + c.name + ';')
+			self.fOut.write()
+		 
+		#writing out ObjectManager
+		self.fOut.write('var ObjectManager = function(controller) {')
+		self.fOut.indent()
+		self.fOut.write("ObjectManagerBase.call(this, controller);")
+		self.fOut.dedent()
+		self.fOut.write("};")
+		self.fOut.write()
+
+		self.fOut.write("ObjectManager.prototype = new ObjectManagerBase();")
+		self.fOut.write()
+		
+		self.fOut.write('ObjectManager.prototype.instantiate = function(class_name, construct_params) {')
+		self.fOut.indent()
+		for index, c in enumerate(class_diagram.classes) :
+			if index == 0 : 
+				self.fOut.write()
+			else :
+				self.fOut.extendWrite(' else ')
+			self.fOut.extendWrite('if (class_name === "' + c.name + '") {')
+			self.fOut.indent()
+			if c.statechart :
+				self.fOut.write('var instance = new ' + c.name + '(this.controller')
+				param_count = 0
+				for p in c.constructors[0].parameters:
+					self.fOut.extendWrite(', construct_params[' + str(param_count) + ']')
+					param_count += 1
+				self.fOut.extendWrite(');')
+			else :
+				self.fOut.write('var instance = new ' + c.name + '(')
+				param_count = 0
+				for p in c.constructors[0].parameters:
+					if (param_count != 0):
+						self.fOut.extendWrite(', ')
+					self.fOut.extendWrite('construct_params[' + str(param_count) + ']')
+					param_count += 1
+				self.fOut.extendWrite(');');
+			self.fOut.write('instance.associations = new Object();')
+			for a in c.associations :
+				a.accept(self)
+			self.fOut.dedent()
+			self.fOut.write('}')
+		self.fOut.write('return instance;')
+		self.fOut.dedent()
+		self.fOut.write("};")
+
+		self.fOut.write()
+		self.fOut.write("// put in global diagram object")
+		self.fOut.write(class_diagram.name + '.ObjectManager = ObjectManager;')
+
+		self.fOut.write()
+		if self.platform == Platforms.Threads :
+			controller_sub_class = "JsEventLoopControllerBase"
+		elif self.platform == Platforms.GameLoop :
+			controller_sub_class = "GameLoopControllerBase"
+
+		# write out __init__ method
+		if class_diagram.default_class.constructors :
+			for constructor in class_diagram.default_class.constructors :
+				self.writeControllerConstructor(class_diagram, controller_sub_class, constructor.parameters)
+		else :
+			self.writeControllerConstructor(class_diagram, controller_sub_class)
+
+		self.fOut.write("Controller.prototype = new " + controller_sub_class + "();")
+		self.fOut.write()
+		self.fOut.write("// put in global diagram object")
+		self.fOut.write(class_diagram.name + '.Controller = Controller;')
+		self.fOut.write()
+		self.fOut.write("})();")
+		self.fOut.write()
+
+	#helper method
+	def writeControllerConstructor(self, class_diagram, controller_sub_class, parameters = []):
+		self.writeConstructorSignature("Controller", parameters + [FormalParameter("keep_running", "", "true"), FormalParameter("finished_callback", "", None)])
+		self.fOut.indent()
+		self.fOut.write(controller_sub_class + ".call(this, new ObjectManager(this), keep_running, finished_callback);")
+		for i in class_diagram.inports:
+			self.fOut.write('this.addInputPort("' + i + '");')
+		for i in class_diagram.outports:
+			self.fOut.write('this.addOutputPort("' + i + '");')
+		actual_parameters = [p.getIdent() for p in parameters]
+		self.fOut.write('this.object_manager.createInstance("'+ class_diagram.default_class.name +'", [' +  ', '.join(actual_parameters)+ ']);')
+		self.fOut.dedent()
+		self.fOut.write('};')
+		self.fOut.write()
+
+	def visit_Class(self, class_node):
+		"""
+		Generate code for Class construct
+		"""
+
+		if class_node.super_classes:
+			super_classes = []
+			for super_class in class_node.super_classes:
+				super_classes.append(super_class)
+		else:
+			super_classes = ["RuntimeClassBase"]
+
+		#visit children
+		for i in class_node.constructors :
+			i.accept(self)
+
+		self.fOut.write()
+		self.fOut.write(class_node.name + ".prototype = new " + super_classes[0] + "();")
+		self.fOut.write()
+
+		if class_node.statechart is not None:
+			# assign each node a unique ID
+			self.fOut.write("// Unique IDs for all statechart nodes")
+			for (i,node) in enumerate(class_node.statechart.composites + class_node.statechart.basics):
+				self.fOut.write(class_node.name + ".prototype." + node.full_name + " = " + str(i) + ";")
+			self.fOut.write()
+
+		#visit children
+		for i in class_node.destructors :
+			i.accept(self)
+		for i in class_node.methods :
+			i.accept(self)
+		if class_node.statechart is not None:
+			class_node.statechart.accept(self)
+
+		if class_node.statechart is not None:
+			self.writeMethodSignature(class_node.name, "commonConstructor", [FormalParameter("controller", "", "null")])
+		else :
+			self.writeMethodSignature(class_node.name, "commonConstructor")
+
+		self.fOut.indent()
+		self.fOut.write('// Constructor part that is common for all constructors.')
+		self.fOut.write(super_classes[0] + ".call(this);");
+
+		#visit input, output ports
+		self.fOut.write()
+		self.fOut.write("// User defined input ports")
+		self.fOut.write("this.inports = new Object();")
+		for p in class_node.inports:
+			self.fOut.write("this.inports[\""+p+"\"] = controller.addInputPort(\""+p+"\", this);")
+
+		#for p in class_node.outports:
+
+		# write attributes
+		if class_node.attributes:
+			self.fOut.write()
+			self.fOut.write("// User defined attributes")
+			for attribute in class_node.attributes:
+				if attribute.init_value is None :
+					self.fOut.write("this." +  attribute.name + " = null;")
+				else :
+					self.fOut.write("this." +  attribute.name + " = " + attribute.init_value + ";")
+			self.fOut.write()
+
+		# if there is a statechart
+		if class_node.statechart is not None:			
+			self.fOut.write("this.controller = controller;")
+			self.fOut.write("this.object_manager = (controller == null ? null : controller.object_manager);")
+			self.fOut.write("this.current_state = new Object();")
+			self.fOut.write("this.history_state = new Object();")
+			if class_node.statechart.nr_of_after_transitions:
+				self.fOut.write("this.timers = new Object();")
+			self.fOut.write()
+			self.fOut.write("// Initialize statechart")
+			
+			if class_node.statechart.histories:
+				for node in class_node.statechart.combined_history_parents:
+					self.fOut.write("this.history_state[" + class_node.name + "." + node.full_name + "] = new Array();")
+				self.fOut.write()
+
+			for c in class_node.statechart.composites :
+				self.fOut.write("this.current_state[this." + c.full_name + "] = new Array();")
+		
+		self.fOut.dedent()
+		self.fOut.write("};")
+		self.fOut.write()
+		
+		self.writeMethodSignature(class_node.name, "start")
+		self.fOut.indent()
+		self.fOut.write(super_classes[0] + ".prototype.start.call(this);")
+		for default_node in class_node.statechart.root.defaults:
+			if default_node.is_composite:
+				self.fOut.write("this.enterDefault_" + default_node.full_name + "();")
+			elif default_node.is_basic:
+				self.fOut.write("this.enter_" + default_node.full_name + "();")
+		self.fOut.dedent()
+		self.fOut.write("};")
+		self.fOut.write()
+
+	#helper method
+	def writeConstructorSignature(self, prototype_name, parameters = []):
+		self.fOut.write("var " + prototype_name + " = function(")		   
+		for param in parameters :
+			if parameters.index(param) != 0:
+				self.fOut.extendWrite(', ')
+			param.accept(self)
+		self.fOut.extendWrite(") {")
+		self.fOut.indent()
+		for param in parameters :
+			if param.hasDefault() :
+				self.fOut.write("if (" + param.getIdent() + " === undefined) " +
+					param.getIdent() + " = " + param.getDefault() + ";")
+		self.fOut.dedent()
+
+	#helper method
+	def writeMethodSignature(self, prototype_name, method_name, parameters = []):
+		self.fOut.write(prototype_name + ".prototype." + method_name + " = function(")
+		for param in parameters :
+			if parameters.index(param) != 0 :
+				self.fOut.extendWrite(', ')
+			param.accept(self)
+		self.fOut.extendWrite(") {")
+		self.fOut.indent()
+		for param in parameters :
+			if param.hasDefault() :
+				self.fOut.write("if (!" + param.getIdent() + ") " +
+					param.getIdent() + " = " + param.getDefault() + ";")
+		self.fOut.dedent()
+		
+	#helper method
+	def writeMethod(self, prototype_name, name, parameters, return_type, body):
+		self.writeMethodSignature(prototype_name, name, parameters)
+		self.fOut.indent()
+		if body.strip():
+			self.writeCodeCorrectIndent(body)
+		else:
+			self.fOut.write("return")
+		self.fOut.write()
+		self.fOut.dedent()
+		self.fOut.write("};");
+		
+	def visit_FormalParameter(self, formal_parameter):
+		self.fOut.extendWrite(formal_parameter.getIdent())
+		
+	def visit_Constructor(self, constructor):
+		self.fOut.write("// The actual constructor")
+		parameters =  [FormalParameter("controller", "", None)] + constructor.getParams()
+		self.writeConstructorSignature(constructor.parent_class.name, parameters)
+		self.fOut.indent()
+		if constructor.parent_class.statechart is not None :
+			self.fOut.write("%s.prototype.commonConstructor.call(this,controller);" % constructor.parent_class.name)
+		else :
+			self.fOut.write("this.commonConstructor();")
+		if constructor.body :
+			self.fOut.write()
+			self.fOut.write("// constructor body (user-defined)")
+			self.writeCodeCorrectIndent(constructor.body)
+		self.fOut.dedent()
+		self.fOut.write("};")
+		self.fOut.write()
+
+	def visit_Destructor(self, destructor):
+		self.fOut.write("// User defined destructor")
+		self.writeMethod(destructor.parent_class.name, "destructor", [], "", destructor.body)
+		
+	def visit_Method(self, method):
+		self.fOut.write("// User defined method")
+		self.writeMethod(method.parent_class.name, method.name, method.parameters, method.return_type, method.body)
+		
+	def visit_Association(self, association):
+		self.fOut.write('instance.associations["' + association.name + '"] = new Association("' + association.to_class + '", ' + str(association.min) + ', ' + str(association.max) + ');')
+		
+	#helper method
+	def writeTransitionsRecursively(self, current_node):
+
+		self.writeMethodSignature(current_node.statechart.class_obj.name, "transition_" + current_node.full_name, [FormalParameter("event", "event")])
+		self.fOut.indent()
+		
+		valid_children = []
+		for child in current_node.children :
+			if child.is_composite or child.is_basic :
+				valid_children.append(child)  
+		 
+		self.fOut.write("var catched = false;")
+		do_dedent = False
+		if current_node.solves_conflict_outer :
+			self.writeFromTransitions(current_node)
+			if current_node.is_parallel_state or current_node.is_composite :
+				self.fOut.write("if (!catched) {")
+				self.fOut.indent()
+				do_dedent = True
+			
+		if current_node.is_parallel_state:
+			for child in valid_children :	 
+				self.fOut.write("catched = this.transition_" + child.full_name + "(event) || catched")
+		elif current_node.is_composite:
+			for i, child in enumerate(valid_children) :
+				if i > 0 :
+					self.fOut.write("else ")
+				else :
+					self.fOut.write()
+				self.fOut.extendWrite("if (this.current_state[this." + current_node.full_name + "][0] === this." + child.full_name + ") {")
+				self.fOut.indent()
+				self.fOut.write("catched = this.transition_" + child.full_name + "(event);")
+				self.fOut.dedent()
+				self.fOut.write("}")
+				
+		if current_node.solves_conflict_outer :
+			if do_dedent :
+				self.fOut.dedent()
+				self.fOut.write("}")
+		elif len(current_node.transitions) > 0 :
+				self.fOut.write("if (!catched) {")
+				self.fOut.indent()
+				self.writeFromTransitions(current_node)
+				self.fOut.dedent()
+				self.fOut.write("}");
+			
+		self.fOut.write("return catched;")
+		self.fOut.dedent()
+		self.fOut.write("};");
+		self.fOut.write();
+		
+		for child in valid_children :
+			self.writeTransitionsRecursively(child)
+				
+	#helper method
+	def writeFromTransitions(self, current_node): 
+		# get all transition out of this state
+		out_transitions = current_node.transitions
+		if len(out_transitions) == 0 :
+			return
+		
+		self.fOut.write('var enableds = new Array();')
+		for index, transition in enumerate(out_transitions, start=1):
+			self.writeTransitionCondition(transition, index)
+			
+		self.fOut.write("if (enableds.length > 1) {")
+		self.fOut.indent()
+		self.fOut.write('console.log("Runtime warning : indeterminism detected in a transition from node ' +  current_node.full_name+ '. Only the first in document order enabled transition is executed.")')
+		self.fOut.dedent()
+		self.fOut.write("}")
+		self.fOut.write()
+		self.fOut.write("if (enableds.length > 0) {")
+		self.fOut.indent()
+		self.fOut.write('var enabled = enableds[0];')	  
+			  
+		for index, transition in enumerate(out_transitions, start=1):
+			self.writeTransitionAction(transition, index)
+		
+		self.fOut.write('catched = true;')   
+		self.fOut.dedent()
+		self.fOut.write("}")
+		self.fOut.write()
+		
+	def visit_FormalEventParameter(self, formal_event_parameter):
+		self.fOut.extendWrite(formal_event_parameter.name)
+		
+	def writeFormalEventParameters(self, transition):
+		parameters = transition.getTrigger().getParameters()
+		if(len(parameters) > 0) :
+			self.fOut.write('var parameters = event.parameters;')
+			for index, parameter in enumerate(parameters):
+				self.fOut.write()
+				self.fOut.write("var ")
+				parameter.accept(self)
+				self.fOut.extendWrite(' = parameters[' + str(index) + '];')
+		
+		
+	def writeTransitionAction(self, transition, index):
+		if index > 1 :
+			self.fOut.write("else ")
+		else :
+			self.fOut.write()
+		self.fOut.extendWrite("if (enabled === " + str(index) + ") {")
+		self.fOut.indent()
+
+		# handle parameters to actually use them			 
+		self.writeFormalEventParameters(transition)
+		
+		exits = transition.getExitNodes()
+		
+		# write out exit actions
+		if not exits[-1].is_basic:
+			self.fOut.write("this.exit_" + exits[-1].full_name + "();")
+		else:
+			for node in exits:
+				if node.is_basic:
+					self.fOut.write("this.exit_" + node.full_name + "();")
+					
+		# write out trigger actions
+		transition.getAction().accept(self)
+		
+		for (entering_node, is_ending_node) in transition.getEnterNodes() : 
+			if is_ending_node :
+				if entering_node.is_composite:
+					self.fOut.write("this.enterDefault_" + entering_node.full_name + "();")
+				elif entering_node.is_history:
+					if (entering_node.is_history_deep) :
+						self.fOut.write("this.enterHistoryDeep_" + entering_node.parent.full_name + "();")
+					else :
+						self.fOut.write("this.enterHistoryShallow_" + entering_node.parent.full_name + "();")
+				else:
+					self.fOut.write("this.enter_" + entering_node.full_name + "();")
+			else :
+				if entering_node.is_composite:
+					self.fOut.write("this.enter_" + entering_node.full_name + "();")
+
+		self.fOut.dedent()
+		self.fOut.write("}")
+						
+	def writeTransitionCondition(self, transition, index):
+		trigger = transition.getTrigger()
+		if not trigger.isUC():  
+			self.fOut.write('if (event.name === "' + trigger.getEvent() + '"' + ((' && event.port === "' + trigger.getPort()+'"') if trigger.getPort() != "" else '') + ') {')
+			self.fOut.indent()   
+		# evaluate guard
+		if transition.hasGuard() :   
+			# handle parameters for guard evaluation	   
+			self.writeFormalEventParameters(transition)
+
+			self.fOut.write('if (')
+			transition.getGuard().accept(self)
+			self.fOut.extendWrite(') {')
+			self.fOut.indent()	
+			
+		self.fOut.write("enableds.push(" + str(index) + ");")
+
+		if transition.hasGuard() :
+			self.fOut.dedent()
+			self.fOut.write("}")
+		if not trigger.isUC() :
+			self.fOut.dedent()
+			self.fOut.write("}")
+		self.fOut.write()
+	
+	def visit_EnterAction(self, enter_method):
+		parent_node = enter_method.parent_node
+		self.writeMethodSignature(parent_node.statechart.class_obj.name, "enter_" + parent_node.full_name, [])
+		self.fOut.indent()
+		# take care of any AFTER events
+		for transition in parent_node.transitions :
+			trigger = transition.getTrigger()
+			if trigger.isAfter() :
+				self.fOut.write("this.timers[" + str(trigger.getAfterIndex()) + "] = ")
+				trigger.after.accept(self)
+				self.fOut.extendWrite(" * 1000.0; /* convert ms to s */")
+		if enter_method.action:
+			enter_method.action.accept(self)
+		self.fOut.write("this.current_state[this." + parent_node.parent.full_name + "].push(this." + parent_node.full_name + ");")
+		self.fOut.dedent()
+		self.fOut.write("};")
+		self.fOut.write()
+		
+	#helper method
+	def writeEnterDefault(self, entered_node):
+		self.writeMethodSignature(entered_node.statechart.class_obj.name, "enterDefault_" + entered_node.full_name, [])
+		self.fOut.indent()
+		self.fOut.write("this.enter_" + entered_node.full_name + "();")
+		if entered_node.is_composite:
+			l = entered_node.defaults
+			for i in l:
+				if i.is_composite:
+					self.fOut.write("this.enterDefault_" + i.full_name + "();")
+				elif i.is_basic:
+					self.fOut.write("this.enter_" + i.full_name + "();")
+		self.fOut.dedent()
+		self.fOut.write("};")
+		self.fOut.write()
+		 
+	def visit_ExitAction(self, exit_method):
+		exited_node = exit_method.parent_node
+		self.writeMethodSignature(exited_node.statechart.class_obj.name, "exit_" + exited_node.full_name, [])
+		self.fOut.indent()
+		
+		#If the exited node is composite take care of potential history and the leaving of descendants
+		if exited_node.is_composite :
+			#handle history
+			if exited_node.save_state_on_exit :
+				self.fOut.write("this.history_state[this." + exited_node.full_name + "] = this.current_state[this." + exited_node.full_name + "];")
+			
+			#Take care of leaving children
+			children = exited_node.children
+			if exited_node.is_parallel_state:
+				for child in children:
+					if not child.is_history :
+						self.fOut.write("this.exit_" + child.full_name + "();")
+			else:
+				for child in children:
+					if not child.is_history :
+						self.fOut.write("if (this.current_state[this." + exited_node.full_name + "].indexOf(this." + child.full_name +  ") !== -1) {")
+						self.fOut.indent()
+						self.fOut.write("this.exit_" + child.full_name + "();")
+						self.fOut.dedent()
+						self.fOut.write("}")
+		
+		
+		# take care of any AFTER events
+		for transition in exited_node.transitions :
+			trigger = transition.getTrigger()
+			if trigger.isAfter() :
+				self.fOut.write("delete this.timers[" + str(trigger.getAfterIndex()) + "];")
+				
+		#Execute user-defined exit action if present
+		if exit_method.action:
+			exit_method.action.accept(self)
+			
+		#Adjust state
+		self.fOut.write("this.current_state[this." + exited_node.parent.full_name + "] = new Array();") # SPECIAL CASE FOR ORTHOGONAL??
+		
+		self.fOut.dedent()
+		self.fOut.write("};")
+		self.fOut.write()
+		
+			
+	#helper method
+	def writeEnterHistory(self, entered_node, is_deep):
+		self.writeMethodSignature(entered_node.statechart.class_obj.name, "enterHistory" + ("Deep" if is_deep else "Shallow") + "_" + entered_node.full_name, [])
+		self.fOut.indent()
+		self.fOut.write("if (this.history_state[this." + entered_node.full_name + "].length === 0) {")
+		self.fOut.indent()
+		defaults = entered_node.defaults
+
+		for node in defaults:
+			if node.is_basic :
+				self.fOut.write("this.enter_" + node.full_name + "();")
+			elif node.is_composite :
+				self.fOut.write("this.enterDefault_" + node.full_name + "();")
+
+		self.fOut.dedent()
+		self.fOut.write("} else {")
+		self.fOut.indent()
+		children = entered_node.children
+		if entered_node.is_parallel_state:
+			for child in children:
+				if not child.is_history :
+					self.fOut.write("this.enterHistory" + ("Deep" if is_deep else "Shallow") + "_" + child.full_name + "();")
+		else:
+			for child in children:
+				if not child.is_history :
+					self.fOut.write("if (this.history_state[this." + entered_node.full_name + "].indexOf(this." + child.full_name + ") !== -1) {")
+					self.fOut.indent()
+					if child.is_composite:
+						if is_deep :
+							self.fOut.write("this.enter_" + child.full_name + "()")
+							self.fOut.write("this.enterHistoryDeep_" + child.full_name + "()")
+						else :
+							self.fOut.write("this.enterDefault_" + child.full_name + "()")
+					else:
+						self.fOut.write("this.enter_" + child.full_name + "()")
+					self.fOut.dedent()
+					self.fOut.write("}")
+		self.fOut.dedent()
+		self.fOut.write("}")
+		self.fOut.dedent()
+		self.fOut.write("};")
+		self.fOut.write()
+
+	def visit_StateChart(self, statechart):
+		self.fOut.write("// Statechart enter/exit action method(s) :")
+		self.fOut.write()
+		
+		#visit enter and exit action of children
+		for i in statechart.composites + statechart.basics:
+			if i is not statechart.root :
+				i.enter_action.accept(self)
+				i.exit_action.accept(self)
+
+		# write out statecharts methods for enter/exit state
+		if len(statechart.composites) > 1 :
+			self.fOut.write("// Statechart enter/exit default method(s) :")
+			self.fOut.write()
+			for i in statechart.composites :
+				if i is not statechart.root :
+					self.writeEnterDefault(i)
+
+		# write out statecharts methods for enter/exit history
+		if statechart.histories:
+			self.fOut.write("// Statechart enter/exit history method(s) :")
+			self.fOut.write()
+			for i in statechart.shallow_history_parents:
+				self.writeEnterHistory(i, False)
+			for i in statechart.deep_history_parents:
+				self.writeEnterHistory(i, True) 
+		   
+		   
+		self.fOut.write("// Statechart transitions :")	 
+		self.fOut.write()
+		self.writeTransitionsRecursively(statechart.root)			
+				
+		# write out transition function
+		self.fOut.write("// Execute transitions")
+		self.writeMethodSignature(statechart.class_obj.name, "transition", [FormalParameter("event", "Event", "new Event()")])
+		self.fOut.indent()
+		self.fOut.write("this.state_changed = this.transition_" + statechart.root.full_name + "(event);")
+		self.fOut.dedent()
+		self.fOut.write("};");
+		self.fOut.write()
+
+		# write out inState function
+		self.fOut.write("// inState method for statechart")
+		self.writeMethodSignature(statechart.class_obj.name, "inState", [FormalParameter("nodes", "Array")])
+		#self.fOut.write("def inState(self, nodes):")
+		self.fOut.indent()
+		self.fOut.write("for (var c in this.current_state) {")
+		self.fOut.indent()
+		self.fOut.write("if (!this.current_state.hasOwnProperty(c)) continue;")
+
+		self.fOut.write("var new_nodes = new Array();")
+		self.fOut.write("for (var n in nodes) {")
+		self.fOut.indent()
+		self.fOut.write("if (!nodes.hasOwnProperty(n)) continue;")
+		self.fOut.write("if (this.current_state[c].indexOf(nodes[n]) === -1) {")
+		self.fOut.indent()
+		self.fOut.write("new_nodes.push(nodes[n]);")
+		self.fOut.dedent()
+		self.fOut.write("}")
+		self.fOut.dedent()
+		self.fOut.write("}")
+		self.fOut.write("nodes = new_nodes;")
+		self.fOut.write("if (nodes.length === 0) {")
+		self.fOut.indent()
+		self.fOut.write("return true;")
+		self.fOut.dedent()
+
+		self.fOut.write("}")
+		self.fOut.dedent()
+		self.fOut.write("}")
+		self.fOut.write("return false;")
+		self.fOut.dedent()
+		self.fOut.write("};")
+		self.fOut.write()
+
+	def visit_ExpressionPartString(self, bare_string):
+		self.fOut.extendWrite(bare_string.string)
+		
+	def visit_SelfReference(self, self_reference):
+		self.fOut.extendWrite("this")
+		
+	def visit_StateReference(self, state_ref):
+		self.fOut.extendWrite("[" + ",".join(["this." + node.full_name for node in state_ref.getNodes()]) + "]")
+		
+	def visit_InStateCall(self, in_state_call):
+		self.fOut.extendWrite("this.inState(")
+		in_state_call.target.accept(self)
+		self.fOut.extendWrite(")")
+		
+	def visit_RaiseEvent(self, raise_event):
+		if raise_event.isNarrow() or raise_event.isBroad():
+			self.fOut.write('var send_event = new Event("' + raise_event.getEventName() + '", null, [')
+		elif raise_event.isLocal():
+			self.fOut.write('this.addEvent(new Event("' + raise_event.getEventName() + '", null, [')
+		elif raise_event.isOutput():
+			self.fOut.write('this.controller.outputEvent(new Event("' + raise_event.getEventName() + '", "' + raise_event.getPort() + '", [')
+		elif raise_event.isCD():
+			self.fOut.write('this.object_manager.addEvent(new Event("' + raise_event.getEventName() + '", null, [this, ')
+		first_param = True
+		for param in raise_event.getParameters() :
+			if first_param :
+				first_param = False
+			else :
+				self.fOut.extendWrite(',')
+			param.accept(self)
+		if raise_event.isNarrow():
+			self.fOut.extendWrite(']);')
+			self.fOut.write('this.object_manager.addEvent(new Event("narrow_cast", null, [this, ' + raise_event.getTarget() + ' , send_event]));')
+		elif raise_event.isBroad():
+			self.fOut.extendWrite(']);')
+			self.fOut.write('this.object_manager.addEvent(new Event("broad_cast", null, [send_event]));')
+		else :
+			self.fOut.extendWrite(']));')
+			
+	def visit_Script(self, script):
+		self.writeCodeCorrectIndent(script.code)
+		
+	def visit_Log(self, log):
+		self.fOut.write('console.log("' + log.message + '");')
+		
+	def visit_Assign(self, assign):
+		self.fOut.write()
+		assign.lvalue.accept(self)
+		self.fOut.extendWrite(" = ")
+		assign.expression.accept(self)
+	

+ 149 - 0
debugging_environment/python_sccd_compiler/lexer.py

@@ -0,0 +1,149 @@
+from utils import Enum
+
+TokenType = Enum("SLASH",
+                 "LBRACKET",
+                 "RBRACKET",
+                 "COMMA",
+                 "DOT",
+                 "NUMBER",
+                 "WORD",
+                 "QUOTED",
+                 "WHITESPACE",
+                 "UNKNOWN"
+                )
+
+class Token(object):
+    """ A simple Token structure. Token type, value and position.
+    """
+    def __init__(self, token_type, val, pos):
+        self.type = token_type
+        self.val = val
+        self.pos = pos
+
+    def __str__(self):
+        return '%s(%s) at %s' % (TokenType.name_of(self.type), self.val, self.pos)
+
+
+class LexerError(Exception):
+    def __init__(self, pos):
+        self.pos = pos
+        
+class Lexer(object):
+    single_rules = {
+            '/': TokenType.SLASH,
+            '(': TokenType.LBRACKET,
+            ')': TokenType.RBRACKET,
+            ',': TokenType.COMMA,
+            '.': TokenType.DOT 
+        }
+    
+    def __init__(self, skip_white_space = True, accept_unknown_tokens = False):
+        self.skip_white_space = skip_white_space
+        self.accept_unknown_tokens = accept_unknown_tokens
+
+    def input(self, buf):
+        """ Initialize the lexer with a buffer as input.
+        """
+        self.buf = buf
+        self.pos = 0
+        self.buflen = len(buf)
+
+    def nextToken(self):
+        """ Return the next token (a Token object) found in the
+            input buffer. None is returned if the end of the
+            buffer was reached.
+            In case of a lexing error (the current chunk of the
+            buffer matches no rule), a LexerError is raised.
+        """
+        if self.skip_white_space :
+            self.skipWhiteSpace() 
+        if self.pos >= self.buflen:
+            return None
+
+        #c part of next token
+        c = self.buf[self.pos]
+        
+        #check if it is an operator
+        result_type = self.single_rules.get(c,None)
+        if result_type is not None :
+            token = Token(result_type, c, self.pos)
+            self.pos += 1
+            return token
+        else : #not an operator
+            if (self.isAlpha(c)) :
+                return self.processIdentifier()
+            elif (self.isDigit(c)) :
+                return self.processNumber()
+            elif ( c == "'" or c == '"') :
+                return self.processQuote()
+            elif (self.isWhiteSpace(c)) :
+                return self.processWhiteSpace()
+
+        # if we're here, no rule matched
+        if self.accept_unknown_tokens :
+            token = Token(TokenType.UNKNOWN, c, self.pos)
+            self.pos += 1
+            return token
+        raise LexerError("Invalid character at position " + str(this.pos) + ".")
+
+    def tokens(self):
+        """ Returns an iterator to the tokens found in the buffer.
+        """
+        while True:
+            tok = self.nextToken()
+            if tok is None: break
+            yield tok
+            
+    def skipWhiteSpace(self):
+        while (self.pos < self.buflen) : 
+            if self.isWhiteSpace(self.buf[self.pos]) :
+                self.pos += 1
+            else :
+                break      
+            
+    def isAlpha(self, c):
+        return c.isalpha() or c == '_';
+    
+    def isAlphaNum(self, c):
+        return c.isalnum() or c == '_';
+    
+    def isDigit(self, c):
+        return c.isdigit()
+    
+    def isWhiteSpace(self, c):
+        return c == ' ' or c == '\t' or c == '\r' or c == '\n'
+    
+    def processNumber(self):
+        nextpos = self.pos + 1
+        while (nextpos < self.buflen) and (self.isDigit(self.buf[nextpos])) :
+            nextpos += 1;
+        token = Token(TokenType.NUMBER, self.buf[self.pos:nextpos], self.pos)
+        self.pos = nextpos
+        return token
+    
+    def processIdentifier(self):
+        nextpos = self.pos + 1
+        while (nextpos < self.buflen) and (self.isAlphaNum(self.buf[nextpos])) :
+            nextpos += 1;
+        token = Token(TokenType.WORD, self.buf[self.pos:nextpos], self.pos)
+        self.pos = nextpos
+        return token
+    
+    def processQuote(self):
+        # this.pos points at the opening quote. Find the ending quote.
+        end_index = self.buf.find(self.buf[self.pos], self.pos + 1)
+    
+        if (end_index == -1) :
+            raise LexerError("Missing matching quote for the quote at position " + str(this.pos) + ".")
+        token = Token(TokenType.QUOTED, self.buf[self.pos:end_index+1], self.pos)
+
+        self.pos = end_index + 1;
+        return token;
+    
+    def processWhiteSpace(self):
+        nextpos = self.pos + 1
+        while (nextpos < self.buflen) and (self.isWhiteSpace(self.buf[nextpos])) :
+            nextpos += 1;
+        token = Token(TokenType.WHITESPACE, self.buf[self.pos:nextpos], self.pos)
+        self.pos = nextpos
+        return token

+ 69 - 0
debugging_environment/python_sccd_compiler/path_calculator.py

@@ -0,0 +1,69 @@
+from visitor import Visitor
+
+class PathCalculator(Visitor):
+    """ Computes the states that must be exited and entered for a specific transition if the system is to make
+        that transition. 
+    """
+    
+    def visit_ClassDiagram(self, class_diagram): 
+        for c in class_diagram.classes :
+            c.accept(self)
+
+    def visit_Class(self, c):
+        c.statechart.accept(self)
+        
+    def visit_StateChart(self, statechart):
+        for node in statechart.basics + statechart.composites:
+            node.accept(self)
+                     
+    def visit_StateChartNode(self, node):
+        for transition in node.transitions :
+            transition.accept(self)
+            
+    def visit_StateChartTransition(self, transition):
+        #Find the scope of the transition (lowest common proper ancestor)
+        #TODO: Could it be made more efficient if we calculated the LCA from the source node and just one of the target nodes?
+        LCA = self.calculateLCA(transition)
+        
+        #Calculate exit nodes
+        transition.exit_nodes = [transition.parent_node]
+        for node in transition.parent_node.getAncestors() :
+            if (node == LCA) :
+                break
+            transition.exit_nodes.append(node)
+       
+        #Calculate enter nodes
+        transition.enter_nodes = []
+        
+        #we then add the branching paths to the other nodes
+        for target_node in transition.target.target_nodes :
+            to_append_list = [(target_node, True)]
+            for anc in target_node.getAncestors() :
+                if anc == LCA : #If we reach the LCA in the ancestor hierarchy we break
+                    break;
+                to_add = True;  #boolean value to see if the current ancestor should be added to the result
+                for enter_node_entry in transition.enter_nodes :
+                    if anc == enter_node_entry[0] :
+                        to_add = False #If we reach an ancestor in the hierarchy that is already listed as enter node, we don't add and break
+                        break
+                if to_add:
+                    to_append_list.append((anc, False)) #Only the first from the ancestor list should get True
+                else :
+                    break
+                    
+            to_append_list.reverse() #the enter sequence should be in the reverse order of the ancestor hierarchy
+            transition.enter_nodes.extend(to_append_list)       
+
+    def calculateLCA(self, transition):
+        """
+        Calculates the lowest common ancestor of a transition
+        """ 
+        for anc in transition.parent_node.getAncestors() :
+            all_descendants = True 
+            for node in transition.target.getNodes() :
+                if not node.isDescendantOf(anc) :
+                    all_descendants = False
+                    break
+            if all_descendants :
+                return anc
+        return None

+ 644 - 0
debugging_environment/python_sccd_compiler/python_generator.py

@@ -0,0 +1,644 @@
+import time
+from constructs import FormalParameter
+from code_generation import CodeGenerator, Platforms
+
+class PythonGenerator(CodeGenerator):
+	
+	def __init__(self):
+		self.supported_platforms = [Platforms.Threads, Platforms.GameLoop]
+				
+	def visit_ClassDiagram(self, class_diagram):
+		self.fOut.write("# Statechart compiler by Glenn De Jonghe")
+		self.fOut.write("#")
+		self.fOut.write("# Date:   " + time.asctime())
+		if class_diagram.name or class_diagram.author or class_diagram.description:
+			self.fOut.write()
+		if class_diagram.author:
+			self.fOut.write("# Model author: " + class_diagram.author)
+		if class_diagram.name:
+			self.fOut.write("# Model name:   " + class_diagram.name)
+		if class_diagram.description.strip():
+			self.fOut.write("# Model description:")
+			self.fOut.write('"""')
+			self.fOut.indent()
+			self.fOut.write(class_diagram.description.strip())
+			self.fOut.dedent()
+			self.fOut.write('"""')
+		self.fOut.write()
+		
+		#Mandatory imports
+		self.fOut.write('from python_runtime.statecharts_core import ObjectManagerBase, Event, InstanceWrapper, RuntimeClassBase, Association')
+		#User imports
+		if class_diagram.top.strip():
+			self.writeCodeCorrectIndent(class_diagram.top)
+		self.fOut.write()
+		
+		#visit children
+		for c in class_diagram.classes :
+			c.accept(self)
+		 
+		#writing out ObjectManager
+		self.fOut.write('class ObjectManager (ObjectManagerBase):')
+		self.fOut.indent()
+		self.fOut.write('def __init__(self, controller):')
+		self.fOut.indent()
+		self.fOut.write("super(ObjectManager, self).__init__(controller)")
+		self.fOut.dedent()
+		self.fOut.write()
+		
+		self.fOut.write('def instantiate(self, class_name, construct_params):')
+		self.fOut.indent()
+		self.fOut.write("associations = []")
+		for index, c in enumerate(class_diagram.classes) :
+			if index == 0 : 
+				self.fOut.write()
+			else :
+				self.fOut.write('el')
+			self.fOut.extendWrite('if class_name == "' + c.name + '" :')
+			self.fOut.indent()
+			if c.statechart :
+				self.fOut.write('instance =  ' + c.name + '(self.controller, *construct_params)')
+			else :
+				self.fOut.write('instance =  ' + c.name + '(*construct_params)')
+			for a in c.associations :
+				a.accept(self)
+			self.fOut.dedent()
+		self.fOut.write('if instance:')
+		self.fOut.indent()
+		self.fOut.write('return InstanceWrapper(instance, associations)')
+		self.fOut.dedent()
+		self.fOut.write('else :')
+		self.fOut.indent()
+		self.fOut.write('return None')
+		self.fOut.dedent()
+		self.fOut.dedent()
+		self.fOut.dedent()
+		
+		self.fOut.write()
+		if self.platform == Platforms.Threads :
+			controller_sub_class = "ThreadsControllerBase"
+		elif self.platform == Platforms.GameLoop :
+			controller_sub_class = "GameLoopControllerBase"
+		self.fOut.write("from python_runtime.statecharts_core import " + controller_sub_class)
+
+		# write out controller
+		self.fOut.write("class Controller(" + controller_sub_class + "):")
+		self.fOut.indent()
+	
+		# write out __init__ method
+		if class_diagram.default_class.constructors :
+			for constructor in class_diagram.default_class.constructors :
+				self.writeControllerConstructor(class_diagram, constructor.parameters)
+		else :
+			self.writeControllerConstructor(class_diagram)
+
+		self.fOut.dedent()
+		self.fOut.write("def main():")
+		self.fOut.indent()
+		self.fOut.write("controller = Controller()")
+		self.fOut.write("controller.start()")
+		self.fOut.dedent()
+		self.fOut.write()
+	
+		self.fOut.write('if __name__ == "__main__":')
+		self.fOut.indent()
+		self.fOut.write("main()")
+		self.fOut.dedent()
+		self.fOut.write()
+		
+	#helper method
+	def writeControllerConstructor(self, class_diagram, parameters = []):
+		self.writeMethodSignature('__init__', parameters + [FormalParameter("keep_running", "", "True")])
+		self.fOut.indent()
+		self.fOut.write("super(Controller, self).__init__(ObjectManager(self), keep_running)")
+		for i in class_diagram.inports:
+			self.fOut.write('self.addInputPort("' + i + '")')
+		for i in class_diagram.outports:
+			self.fOut.write('self.addOutputPort("' + i + '")')
+		actual_parameters = [p.getIdent() for p in parameters]
+		self.fOut.write('self.object_manager.createInstance("'+ class_diagram.default_class.name +'", [' +  ', '.join(actual_parameters)+ '])')
+		self.fOut.write()
+		self.fOut.dedent()
+
+	def visit_Class(self, class_node):
+		"""
+		Generate code for Class construct
+		"""
+		self.fOut.write()
+		# take care of inheritance
+		if class_node.super_classes:
+			class_node.super_classes.append("RuntimeClassBase")
+			super_classes = []
+			for super_class in class_node.super_classes:
+				super_classes.append(super_class)
+			self.fOut.write("class " + class_node.name + "(" + ", ".join(super_classes) +  "):")
+		else:
+			self.fOut.write("class " + class_node.name + "(RuntimeClassBase):")
+
+		self.fOut.indent()
+		self.fOut.write()
+		
+		if class_node.statechart is not None:
+			# assign each node a unique ID
+			self.fOut.write("# Unique IDs for all statechart nodes")
+			for (i,node) in enumerate(class_node.statechart.composites + class_node.statechart.basics):
+				self.fOut.write(node.full_name + " = " + str(i))
+	
+			self.fOut.write()
+			self.writeMethodSignature("commonConstructor", [FormalParameter("controller", "", "None")])
+		else :
+			self.writeMethodSignature("commonConstructor")
+		self.fOut.indent()
+		self.fOut.write('"""Constructor part that is common for all constructors."""')
+		self.fOut.write("RuntimeClassBase.__init__(self)")
+
+		# write private input/output ports
+		self.fOut.write()
+		self.fOut.write("# User defined input ports")
+		self.fOut.write("self.inports = {}")
+		for p in class_node.inports:
+			self.fOut.write("self.inports[\""+p+"\"] = controller.addInputPort(\""+p+"\", self)")
+
+		# write attributes
+		if class_node.attributes:
+			self.fOut.write()
+			self.fOut.write("# User defined attributes")
+			for attribute in class_node.attributes:
+				if attribute.init_value is None :
+					self.fOut.write("self." +  attribute.name + " = None")
+				else :
+					self.fOut.write("self." +  attribute.name + " = " + attribute.init_value)	 
+			self.fOut.write()
+
+		# if there is a statechart
+		if class_node.statechart is not None:			
+			self.fOut.write("self.controller = controller")
+			self.fOut.write("self.object_manager = controller.getObjectManager()")
+			self.fOut.write("self.current_state = {}")
+			self.fOut.write("self.history_state = {}")
+			if class_node.statechart.nr_of_after_transitions:
+				self.fOut.write("self.timers = {}")
+			self.fOut.write()
+			self.fOut.write("#Initialize statechart :")
+			self.fOut.write()
+			
+			if class_node.statechart.histories:
+				for node in class_node.statechart.combined_history_parents:
+					self.fOut.write("self.history_state[" + class_node.name + "." + node.full_name + "] = []")
+				self.fOut.write()
+
+			for c in class_node.statechart.composites :
+				self.fOut.write("self.current_state[self." + c.full_name + "] = []")
+		
+		self.fOut.dedent()
+		self.fOut.write()
+		
+		self.writeMethodSignature("start")
+		self.fOut.indent()
+		self.fOut.write("super(" + class_node.name + ", self).start()")
+		if class_node.statechart:
+			for default_node in class_node.statechart.root.defaults:
+				if default_node.is_composite:
+					self.fOut.write("self.enterDefault_" + default_node.full_name + "()")
+				elif default_node.is_basic:
+					self.fOut.write("self.enter_" + default_node.full_name + "()")
+		self.fOut.dedent()
+		self.fOut.write()
+		
+		#visit children
+		for i in class_node.constructors :
+			i.accept(self)
+		for i in class_node.destructors :
+			i.accept(self)
+		for i in class_node.methods :
+			i.accept(self)
+		if class_node.statechart is not None:
+			class_node.statechart.accept(self)
+		  
+		# write out str method
+		self.fOut.dedent()
+
+	#helper method
+	def writeMethodSignature(self, name, parameters = []):
+		self.fOut.write("def " + name + "(self")		   
+		for param in parameters :
+			self.fOut.extendWrite(', ')
+			param.accept(self)
+		self.fOut.extendWrite("):")
+		
+	#helper method
+	def writeMethod(self, name, parameters, return_type, body):
+		self.writeMethodSignature(name, parameters)
+		self.fOut.indent()
+		if body.strip():
+			self.writeCodeCorrectIndent(body)
+		else:
+			self.fOut.write("return")
+		self.fOut.write()
+		self.fOut.dedent()
+		
+	def visit_FormalParameter(self, formal_parameter):
+		self.fOut.extendWrite(formal_parameter.getIdent())
+		if formal_parameter.hasDefault() :
+			self.fOut.extendWrite(" = " + formal_parameter.getDefault())
+		
+	def visit_Constructor(self, constructor):
+		self.fOut.write("#The actual constructor")
+		parameters =  [FormalParameter("controller", "", None)] + constructor.getParams()
+		self.writeMethodSignature("__init__", parameters)
+		self.fOut.indent()
+		if constructor.parent_class.statechart is not None :
+			self.fOut.write("self.commonConstructor(controller)")
+		else :
+			self.fOut.write("self.commonConstructor()")
+		if constructor.body :
+			self.fOut.write()
+			self.fOut.write("#constructor body (user-defined)")
+			self.writeCodeCorrectIndent(constructor.body)
+		self.fOut.dedent()
+		self.fOut.write()
+		
+	def visit_Destructor(self, destructor):
+		self.fOut.write("# User defined destructor")
+		self.writeMethod("__del__", [], "", destructor.body)
+		
+	def visit_Method(self, method):
+		self.fOut.write("# User defined method")
+		self.writeMethod(method.name, method.parameters, method.return_type, method.body)
+		
+	def visit_Association(self, association):
+		self.fOut.write('associations.append(Association("' + association.name + '", "' + association.to_class + '", ' + str(association.min) + ', ' + str(association.max) + '))')
+		
+	#helper method
+	def writeTransitionsRecursively(self, current_node):
+		self.fOut.write("def transition_" + current_node.full_name + "(self, event) :")
+		self.fOut.indent()
+		
+		valid_children = []
+		for child in current_node.children :
+			if child.is_composite or child.is_basic :
+				valid_children.append(child)  
+		 
+		self.fOut.write("catched = False")
+		do_dedent = False
+		if current_node.solves_conflict_outer :
+			self.writeFromTransitions(current_node)
+			if current_node.is_parallel_state or current_node.is_composite :
+				self.fOut.write("if not catched :")
+				self.fOut.indent()
+				do_dedent = True
+			
+		if current_node.is_parallel_state:
+			for child in valid_children :	 
+				self.fOut.write("catched = self.transition_" + child.full_name + "(event) or catched")
+		elif current_node.is_composite:
+			for i, child in enumerate(valid_children) :
+				if i > 0 :
+					self.fOut.write("el")
+				else :
+					self.fOut.write()
+				self.fOut.extendWrite("if self.current_state[self." + current_node.full_name + "][0] == self." + child.full_name + ":")
+				self.fOut.indent()
+				self.fOut.write("catched = self.transition_" + child.full_name + "(event)")
+				self.fOut.dedent()
+				
+		if current_node.solves_conflict_outer :
+			if do_dedent :
+				self.fOut.dedent()
+		elif len(current_node.transitions) > 0 :
+				self.fOut.write("if not catched :")
+				self.fOut.indent()
+				self.writeFromTransitions(current_node)
+				self.fOut.dedent()
+			
+		self.fOut.write("return catched")
+		self.fOut.dedent()
+		self.fOut.write();
+		
+		for child in valid_children :
+			self.writeTransitionsRecursively(child)
+				
+	#helper method
+	def writeFromTransitions(self, current_node): 
+		# get all transition out of this state
+		out_transitions = current_node.transitions
+		if len(out_transitions) == 0 :
+			return
+		
+		self.fOut.write('enableds = []')
+		for index, transition in enumerate(out_transitions, start=1):
+			self.writeTransitionCondition(transition, index)
+			
+		self.fOut.write("if len(enableds) > 1 :")
+		self.fOut.indent()
+		self.fOut.write('print "Runtime warning : indeterminism detected in a transition from node ' +  current_node.full_name+ '. Only the first in document order enabled transition is executed."')
+		self.fOut.dedent()
+		self.fOut.write()
+		self.fOut.write("if len(enableds) > 0 :")
+		self.fOut.indent()
+		self.fOut.write('enabled = enableds[0]')	  
+			  
+		for index, transition in enumerate(out_transitions, start=1):
+			self.writeTransitionAction(transition, index)
+		
+		self.fOut.write('catched = True')   
+		self.fOut.dedent()		 
+		self.fOut.write()
+		
+	def visit_FormalEventParameter(self, formal_event_parameter):
+		self.fOut.extendWrite(formal_event_parameter.name)
+		
+	def writeFormalEventParameters(self, transition):
+		parameters = transition.getTrigger().getParameters()
+		if(len(parameters) > 0) :
+			self.fOut.write('parameters = event.getParameters()')
+			for index, parameter in enumerate(parameters):
+				self.fOut.write()
+				parameter.accept(self)
+				self.fOut.extendWrite(' = parameters[' + str(index) + ']')
+		
+		
+	def writeTransitionAction(self, transition, index):
+		if index > 1 :
+			self.fOut.write("el")
+		else :
+			self.fOut.write()
+		self.fOut.extendWrite("if enabled == " + str(index) + " :")
+		self.fOut.indent()
+
+		# handle parameters to actually use them			 
+		self.writeFormalEventParameters(transition)
+		
+		exits = transition.getExitNodes()
+		
+		# write out exit actions
+		if not exits[-1].is_basic:
+			self.fOut.write("self.exit_" + exits[-1].full_name + "()")
+		else:
+			for node in exits:
+				if node.is_basic:
+					self.fOut.write("self.exit_" + node.full_name + "()")
+					
+		# write out trigger actions
+		transition.getAction().accept(self)
+		
+		for (entering_node, is_ending_node) in transition.getEnterNodes() : 
+			if is_ending_node :
+				if entering_node.is_composite:
+					self.fOut.write("self.enterDefault_" + entering_node.full_name + "()")
+				elif entering_node.is_history:
+					if (entering_node.is_history_deep) :
+						self.fOut.write("self.enterHistoryDeep_" + entering_node.parent.full_name + "()")
+					else :
+						self.fOut.write("self.enterHistoryShallow_" + entering_node.parent.full_name + "()")
+				else:
+					self.fOut.write("self.enter_" + entering_node.full_name + "()")
+			else :
+				if entering_node.is_composite:
+					self.fOut.write("self.enter_" + entering_node.full_name + "()")
+
+		self.fOut.dedent()
+						
+	def writeTransitionCondition(self, transition, index):
+		trigger = transition.getTrigger()
+		if not trigger.isUC():  
+			self.fOut.write('if event.name == "' + trigger.getEvent() + '" and event.getPort() == "' + trigger.getPort() + '" :')
+			self.fOut.indent()   
+		# evaluate guard
+		if transition.hasGuard() :   
+			# handle parameters for guard evaluation	   
+			self.writeFormalEventParameters(transition)
+
+			self.fOut.write('if ')
+			transition.getGuard().accept(self)
+			self.fOut.extendWrite(' :')
+			self.fOut.indent()	
+			
+		self.fOut.write("enableds.append(" + str(index) + ")")
+
+		if transition.hasGuard() :
+			self.fOut.dedent()
+		if not trigger.isUC() :
+			self.fOut.dedent()
+		self.fOut.write()
+	
+	def visit_EnterAction(self, enter_method):
+		parent_node = enter_method.parent_node
+		self.writeMethodSignature("enter_" + parent_node.full_name, [])
+		self.fOut.indent()
+		# take care of any AFTER events
+		for transition in parent_node.transitions :
+			trigger = transition.getTrigger()
+			if trigger.isAfter() :
+				self.fOut.write("self.timers[" + str(trigger.getAfterIndex()) + "] = ")
+				trigger.after.accept(self)
+		if enter_method.action:
+			enter_method.action.accept(self)
+		self.fOut.write("self.current_state[self." + parent_node.parent.full_name + "].append(self." + parent_node.full_name + ")")
+		self.fOut.dedent()
+		self.fOut.write()
+		
+	#helper method
+	def writeEnterDefault(self, entered_node):
+		self.writeMethodSignature("enterDefault_" + entered_node.full_name, [])
+		self.fOut.indent()
+		self.fOut.write("self.enter_" + entered_node.full_name + "()")
+		if entered_node.is_composite:
+			l = entered_node.defaults
+			for i in l:
+				if i.is_composite:
+					self.fOut.write("self.enterDefault_" + i.full_name + "()")
+				elif i.is_basic:
+					self.fOut.write("self.enter_" + i.full_name + "()")
+		self.fOut.dedent()
+		self.fOut.write()
+		 
+	def visit_ExitAction(self, exit_method):
+		exited_node = exit_method.parent_node
+		self.writeMethodSignature("exit_" + exited_node.full_name, [])
+		self.fOut.indent()
+		
+		#If the exited node is composite take care of potential history and the leaving of descendants
+		if exited_node.is_composite :
+			#handle history
+			if exited_node.save_state_on_exit :
+				self.fOut.write("self.history_state[self." + exited_node.full_name + "] = self.current_state[self." + exited_node.full_name + "]")
+			
+			#Take care of leaving children
+			children = exited_node.children
+			if exited_node.is_parallel_state:
+				for child in children:
+					if not child.is_history :
+						self.fOut.write("self.exit_" + child.full_name + "()")
+			else:
+				for child in children:
+					if not child.is_history :
+						self.fOut.write("if self." + child.full_name +  " in self.current_state[self." + exited_node.full_name + "] :")
+						self.fOut.indent()
+						self.fOut.write("self.exit_" + child.full_name + "()")
+						self.fOut.dedent()  
+		
+		
+		# take care of any AFTER events
+		for transition in exited_node.transitions :
+			trigger = transition.getTrigger()
+			if trigger.isAfter() :
+				self.fOut.write("self.timers.pop(" + str(trigger.getAfterIndex()) + ", None)")
+				
+		#Execute user-defined exit action if present
+		if exit_method.action:
+			exit_method.action.accept(self)
+			
+		#Adjust state
+		self.fOut.write("self.current_state[self." + exited_node.parent.full_name + "] = []") # SPECIAL CASE FOR ORTHOGONAL??
+		
+		self.fOut.dedent()
+		self.fOut.write()
+		
+			
+	#helper method
+	def writeEnterHistory(self, entered_node, is_deep):
+		self.writeMethodSignature("enterHistory" + ("Deep" if is_deep else "Shallow") + "_" + entered_node.full_name, [])
+		self.fOut.indent()
+		self.fOut.write("if self.history_state[self." + entered_node.full_name + "] == []:")
+		self.fOut.indent()
+		defaults = entered_node.defaults
+
+		for node in defaults:
+			if node.is_basic :
+				self.fOut.write("self.enter_" + node.full_name + "()")
+			elif node.is_composite :
+				self.fOut.write("self.enterDefault_" + node.full_name + "()")
+
+		self.fOut.dedent()
+		self.fOut.write("else:")
+		self.fOut.indent()
+		children = entered_node.children
+		if entered_node.is_parallel_state:
+			for child in children:
+				if not child.is_history :
+					self.fOut.write("self.enterHistory" + ("Deep" if is_deep else "Shallow") + "_" + child.full_name + "()")
+		else:
+			for child in children:
+				if not child.is_history :
+					self.fOut.write("if self." + child.full_name + " in self.history_state[self." + entered_node.full_name + "] :")
+					self.fOut.indent()
+					if child.is_composite:
+						if is_deep :
+							self.fOut.write("self.enter_" + child.full_name + "()")
+							self.fOut.write("self.enterHistoryDeep_" + child.full_name + "()")
+						else :
+							self.fOut.write("self.enterDefault_" + child.full_name + "()")
+					else:
+						self.fOut.write("self.enter_" + child.full_name + "()")
+					self.fOut.dedent()
+		self.fOut.dedent()
+		self.fOut.dedent()
+		self.fOut.write()
+
+	def visit_StateChart(self, statechart):
+		self.fOut.write("# Statechart enter/exit action method(s) :")
+		self.fOut.write()
+		
+		#visit enter and exit action of children
+		for i in statechart.composites + statechart.basics:
+			if i is not statechart.root :
+				i.enter_action.accept(self)
+				i.exit_action.accept(self)
+
+		# write out statecharts methods for enter/exit state
+		if len(statechart.composites) > 1 :
+			self.fOut.write("#Statechart enter/exit default method(s) :")
+			self.fOut.write()
+			for i in statechart.composites :
+				if i is not statechart.root :
+					self.writeEnterDefault(i)
+
+		# write out statecharts methods for enter/exit history
+		if statechart.histories:
+			self.fOut.write("#Statechart enter/exit history method(s) :")
+			self.fOut.write()
+			for i in statechart.shallow_history_parents:
+				self.writeEnterHistory(i, False)
+			for i in statechart.deep_history_parents:
+				self.writeEnterHistory(i, True) 
+		   
+		   
+		self.fOut.write("#Statechart transitions :")	 
+		self.fOut.write()
+		self.writeTransitionsRecursively(statechart.root)			
+				
+		# write out transition function
+		self.fOut.write("# Execute transitions")
+		self.fOut.write("def transition(self, event = Event(\"\")):")
+		self.fOut.indent()
+		self.fOut.write("self.state_changed = self.transition_" + statechart.root.full_name + "(event)")
+		self.fOut.dedent()
+
+		# write out inState function
+		self.fOut.write("# inState method for statechart")
+		self.fOut.write("def inState(self, nodes):")
+		self.fOut.indent()
+		self.fOut.write("for actives in self.current_state.itervalues():")
+		self.fOut.indent()
+		self.fOut.write("nodes = [node for node in nodes if node not in actives]")
+		self.fOut.write("if not nodes :")
+		self.fOut.indent()
+		self.fOut.write("return True")
+		self.fOut.dedent()
+		self.fOut.dedent()
+		self.fOut.write("return False")
+		self.fOut.dedent()
+		self.fOut.write()
+		
+	def visit_ExpressionPartString(self, bare_string):
+		self.fOut.extendWrite(bare_string.string)
+		
+	def visit_SelfReference(self, self_reference):
+		self.fOut.extendWrite("self")
+		
+	def visit_StateReference(self, state_ref):
+		self.fOut.extendWrite("[" + ",".join(["self." + node.full_name for node in state_ref.getNodes()]) + "]")
+		
+	def visit_InStateCall(self, in_state_call):
+		self.fOut.extendWrite("self.inState(")
+		in_state_call.target.accept(self)
+		self.fOut.extendWrite(")")
+		
+	def visit_RaiseEvent(self, raise_event):
+		if raise_event.isNarrow() or raise_event.isBroad():
+			self.fOut.write('send_event = Event("' + raise_event.getEventName() + '", parameters = [')
+		elif raise_event.isLocal():
+			self.fOut.write('self.addEvent(Event("' + raise_event.getEventName() +'", parameters = [')
+		elif raise_event.isOutput():
+			self.fOut.write('self.controller.outputEvent(Event("' + raise_event.getEventName() + '", port="' + raise_event.getPort() + '", parameters = [')
+		elif raise_event.isCD():
+			self.fOut.write('self.object_manager.addEvent(Event("' + raise_event.getEventName() + '", parameters = [self, ')
+		first_param = True
+		for param in raise_event.getParameters() :
+			if first_param :
+				first_param = False
+			else :
+				self.fOut.extendWrite(',')
+			param.accept(self)
+		if raise_event.isNarrow():
+			self.fOut.extendWrite('])')
+			self.fOut.write('self.object_manager.addEvent(Event("narrow_cast", parameters = [self, ' + raise_event.getTarget() + ' , send_event]))')
+		elif raise_event.isBroad():
+			self.fOut.extendWrite('])')
+			self.fOut.write('self.object_manager.addEvent(Event("broad_cast", parameters = [send_event]))')
+		else :
+			self.fOut.extendWrite(']))')
+			
+	def visit_Script(self, script):
+		self.writeCodeCorrectIndent(script.code)
+		
+	def visit_Log(self, log):
+		self.fOut.write('print "' + log.message + '"')
+		
+	def visit_Assign(self, assign):
+		self.fOut.write()
+		assign.lvalue.accept(self)
+		self.fOut.extendWrite(" = ")
+		assign.expression.accept(self)
+	

+ 112 - 0
debugging_environment/python_sccd_compiler/sccdc.py

@@ -0,0 +1,112 @@
+import argparse
+import os
+from python_generator import PythonGenerator
+from csharp_generator import CSharpGenerator
+from javascript_generator import JavascriptGenerator
+from utils import Logger
+from code_generation import Languages, Platforms
+from state_linker import StateLinker
+from path_calculator import PathCalculator
+from constructs import ClassDiagram
+from compiler_exceptions import CompilerException
+   
+def generate(input_file, output_file, target_language, platform):
+    class_diagram = createAST(input_file)
+    generateFromAST(class_diagram, output_file, target_language, platform)
+      
+def createAST(input_file):
+    cd = ClassDiagram(input_file) #create AST
+    StateLinker().visit(cd) #visitor fixing state references
+    PathCalculator().visit(cd) #visitor calculating paths
+    return cd
+    
+def generateFromAST(class_diagram, output_file, target_language, platform):
+    succesfull_generation = False
+    if target_language == Languages.Python :
+        succesfull_generation = PythonGenerator().generate(class_diagram, output_file, platform)
+    elif target_language == Languages.CSharp:
+        succesfull_generation = CSharpGenerator().generate(class_diagram, output_file, platform)
+    elif target_language == Languages.Javascript:
+        succesfull_generation = JavascriptGenerator().generate(class_diagram, output_file, platform)
+    # let user know ALL classes have been processed and loaded
+    if succesfull_generation :
+        Logger.showInfo("The following classes <" + ", ".join(class_diagram.class_names) + "> have been exported to the following file: " + output_file)
+        
+def main():
+    parser = argparse.ArgumentParser()
+    parser.add_argument('input', help='The path to the XML file to be compiled.')
+    parser.add_argument('-o', '--output', type=str, help='The path to the generated code. Defaults to the same name as the input file but with matching extension.')
+    parser.add_argument('-v', '--verbose', type=int, help='2 = all output; 1 = only warnings and errors; 0 = only errors; -1 = no output.  Defaults to 2.', default = 2)
+    parser.add_argument('-p', '--platform', type=str, help="Let the compiled code run on top of threads or gameloop. The default is threads.")
+    parser.add_argument('-l', '--language', type=str, help='Target language, either "csharp" or "python". Defaults to the latter.')
+    
+    args = vars(parser.parse_args())
+    #Set verbose
+    if args['verbose'] is not None:
+        if args['verbose'] in [-1, 0,1,2] :
+            Logger.verbose = args['verbose']
+        else :
+            Logger.showError("Invalid verbose argument.")
+    else :
+        Logger.verbose = 2
+
+    #Set source file
+    source = args['input']
+    if not source.endswith(".xml") :
+        Logger.showError("Input file not valid.")
+        return
+    
+    #Set target language
+    if args['language'] :
+        args['language'] = args['language'].lower()
+
+        if args['language'] == "csharp" or args['language'] == "c#" :
+            target_language = Languages.CSharp
+        elif args['language'] == "python" :
+            target_language = Languages.Python
+        elif args['language'] == "javascript" :
+            target_language = Languages.Javascript
+        else :
+            Logger.showError("Invalid language.")
+    else :
+        target_language = Languages.Python  
+        
+    #Set output file
+    if args['output'] :
+        output = args['output']
+        if target_language == Languages.Python and not output.endswith(".py") :
+            Logger.showError('Output file should end in ".py".')
+            return
+        elif target_language == Languages.CSharp and not output.endswith(".cs") :
+            Logger.showError('Output file should end in ".cs".')
+            return
+    else :
+        output = os.path.splitext(os.path.split(source)[1])[0] 
+        if target_language == Languages.Python :
+            output += ".py"
+        elif target_language == Languages.CSharp :
+            output += ".cs"
+        
+    #Set platform    
+    if args['platform'] :
+        args['platform'] = args['platform'].lower()
+        if args['platform'] == "threads" :
+            platform = Platforms.Threads
+        elif args['platform'] == "gameloop" :
+            platform = Platforms.GameLoop
+        else :
+            Logger.showError("Invalid platform.")
+            return          
+    else :
+        platform = Platforms.Threads
+        
+    #Compile    
+    try :
+        generate(source, output, target_language, platform)
+    except CompilerException as exception :
+        Logger.showError(str(exception));
+
+if __name__ == "__main__":
+    main()
+
+

+ 151 - 0
debugging_environment/python_sccd_compiler/state_linker.py

@@ -0,0 +1,151 @@
+from visitor import Visitor
+from constructs import INSTATE_SEQ
+from compiler_exceptions import CompilerException
+from lexer import Lexer, Token, TokenType
+
+class StateReferenceException(CompilerException):
+    pass
+
+class StateLinker(Visitor):
+    
+    def __init__(self):
+        self.visiting_statechart = None
+        self.visiting_node = None
+        self.lexer = Lexer()
+    
+    def visit_ClassDiagram(self, class_diagram): 
+        for c in class_diagram.classes :
+            c.accept(self)
+
+    def visit_Class(self, c):
+        c.statechart.accept(self)
+        
+    def visit_StateChart(self, statechart):
+        self.visiting_statechart = statechart
+        for node in statechart.basics + statechart.composites:
+            node.accept(self)
+                     
+    def visit_StateChartNode(self, node):
+        self.visiting_node = node
+        node.enter_action.accept(self)
+        node.exit_action.accept(self)
+        for transition in node.transitions :
+            transition.accept(self)
+            
+    def visit_StateChartTransition(self, transition):
+        try :
+            transition.target.accept(self)
+        except StateReferenceException as exception :
+            raise StateReferenceException("Transition from <" + self.visiting_node.full_name + "> has invalid target. " + exception.message)
+        try :
+            transition.action.accept(self)
+        except StateReferenceException as exception :
+            raise StateReferenceException("Transition from <" + self.visiting_node.full_name + "> has invalid action. " + exception.message)
+        try :
+            if transition.guard :
+                transition.guard.accept(self)
+        except StateReferenceException as exception :
+            raise StateReferenceException("Transition from <" + self.visiting_node.full_name  + "> has invalid guard. " + exception.message)
+        
+    def visit_StateReference(self, state_reference):
+        state_reference.target_nodes = []
+        
+        current_node = None #Will be used to find the target state(s)
+        split_stack = [] #used for branching
+
+        self.lexer.input(state_reference.path_string)
+
+        for token in self.lexer.tokens() :
+            
+            if current_node == None : #current_node is not set yet or has been reset, the CHILD token can now have a special meaning
+                if token.type == TokenType.SLASH :
+                    #Root detected
+                    current_node = self.visiting_statechart.root
+                    #Token consumed so continue
+                    continue
+                else :
+                    current_node = self.visiting_node
+                    
+            if token.type == TokenType.DOT :
+                #Advance to next token
+                token = self.lexer.nextToken()
+                
+                if token is None or token.type == TokenType.SLASH :
+                    #CURRENT operator "." detected
+                    continue
+                elif token.type == TokenType.DOT :
+                    #Advance to next token
+                    token = self.lexer.nextToken()
+                    if token is None or token.type == TokenType.SLASH :
+                        #PARENT operator ".." detected
+                        current_node = current_node.parent
+                        if current_node is None :
+                            raise StateReferenceException("Illegal use of PARENT \"..\" operator at position " + str(token.pos) + " in state reference. Root of statechart reached.")
+                    
+                    else :
+                        raise StateReferenceException("Illegal use of PARENT \"..\" operator at position " + str(token.pos) + " in state reference.")
+    
+                else :
+                    raise StateReferenceException("Illegal use of CURRENT \".\" operator at position " + str(token.pos) + " in state reference.")
+                    
+            elif token.type == TokenType.SLASH :
+                continue
+            elif token.type == TokenType.WORD :
+                #try to advance to next child state
+                cname = token.val
+                found = False
+                for child in current_node.children :
+                    if child.name == cname : 
+                        found = True
+                        current_node = child
+                        break
+                if not found :
+                    raise StateReferenceException("Refering to non exiting node at posisition " + str(token.pos) + " in state reference.")
+            elif token.type == TokenType.LBRACKET :
+                split_stack.append(current_node)
+            elif token.type == TokenType.RBRACKET :
+                if len(split_stack) > 0 :
+                    split_stack.pop()
+                else :
+                    raise StateReferenceException("Invalid token at position " + str(token.pos) + " in state reference.")
+            elif token.type == TokenType.COMMA :
+                state_reference.target_nodes.append(current_node)
+                if len(split_stack) > 0 :
+                    current_node = split_stack[-1]
+                else :
+                    current_node = None
+            
+            else :
+                raise StateReferenceException("Invalid token at position " + str(token.pos) + " in state reference.")
+        
+        if (len(split_stack) != 0) or (current_node is None) : #RB missing or extra COMMA
+            raise StateReferenceException("State reference ends unexpectedly.")
+        
+        #TODO better validation of the target! When is it a valid state configuration?
+        for node in state_reference.target_nodes :
+            if current_node == node :
+                raise StateReferenceException("A state reference can't reference the same node more than once.")
+            if node.isDescendantOrAncestorOf(current_node) :
+                raise StateReferenceException("A state reference can't reference a node and one of its descendants.");
+        
+        state_reference.target_nodes.append(current_node)
+            
+        if len(state_reference.target_nodes) == 0 :
+            raise StateReferenceException("Meaningless state reference.")
+                
+    def visit_EnterExitAction(self, action):
+        if action.action :
+            action.action.accept(self)
+            
+    def visit_Action(self, action):
+        for subaction in action.sub_actions :
+            subaction.accept(self)
+            
+    def visit_InStateCall(self, call):
+        try :
+            call.target.accept(self)
+        except StateReferenceException :
+            raise StateReferenceException("Invalid state reference for " + INSTATE_SEQ + " call.")
+        
+    def visit_Assign(self, assign):
+        assign.expression.accept(self)

+ 154 - 0
debugging_environment/python_sccd_compiler/tests.py

@@ -0,0 +1,154 @@
+import unittest
+import sccdc
+import importlib
+import os
+import xml.etree.ElementTree as ET
+from compiler_exceptions import CompilerException, TransitionException
+from code_generation import Platforms, Languages
+from python_runtime.statecharts_core import Event
+
+SHARED_TEST_FILES_FOLDER = "../test_files"
+
+class TestEvent(object):
+    def __init__(self, name, port, parameters = []):
+        self.name = name
+        self.port = port
+        self.parameters = parameters
+        
+    def matches(self, event):
+        if event is None :
+            return False
+        if event.getName() != self.name :
+            return False
+        if event.getPort() != self.port :
+            return False
+        compare_parameters = event.getParameters()
+        if len(self.parameters) != len(compare_parameters) :
+            return False
+        for index in xrange(len(self.parameters)) :
+            if self.parameters[index] !=  str(compare_parameters[index]):
+                return False
+        return True
+    
+    def __repr__(self):
+        representation = "(event name : " + str(self.name) + "; port : " + str(self.port)
+        if self.parameters :
+            representation += "; parameters : " + str(self.parameters)
+        representation += ")"
+        return representation
+
+class XMLTestCase(unittest.TestCase):
+    
+    def __init__(self, file_name):
+        super(XMLTestCase, self).__init__()
+        self.file_name = file_name
+        self.name = os.path.splitext(file_name)[0]
+        self.source_path = os.getcwd() + "/" + SHARED_TEST_FILES_FOLDER + "/" + self.file_name
+        self.target_path = os.getcwd() + "/" + self.name + ".py"
+        self.file_generated = False
+                    
+    def __str__(self):
+        return self.file_name
+        
+    def setUp(self):
+        self.delete_generated_file = not os.path.isfile(self.target_path)
+        
+    def tearDown(self):
+        if self.file_generated and self.delete_generated_file :
+            os.remove(self.target_path)
+            os.remove(self.target_path + "c")
+            
+
+    def runTest(self):
+        test_xml = ET.parse(self.source_path).getroot().find("test")
+        self.assertIsNot(test_xml, None, "No test data found. (A test that should just compile correctly, still needs an empthy test tag.)")
+        
+        #Check if the exception attribute is set and act accordingly
+        exception_attribute = test_xml.get("exception","")
+        if exception_attribute == "" :
+            sccdc.generate(self.source_path, self.target_path, Languages.Python, Platforms.Threads)
+        else :
+            if exception_attribute == "CompilerException" :
+                with self.assertRaises(CompilerException):
+                    sccdc.generate(self.source_path, self.target_path, Languages.Python, Platforms.Threads)
+            elif exception_attribute == "TransitionException" :
+                with self.assertRaises(TransitionException):
+                    sccdc.generate(self.source_path, self.target_path, Languages.Python, Platforms.Threads)
+            else :
+                raise AssertionError("Invalid value for the exception attribute.")
+            return
+            
+        
+        self.file_generated = True
+        import_file = importlib.import_module(self.name)
+        self.controller = import_file.Controller(False)
+        
+        #Preparing input for controller
+        input_xml = test_xml.find("input")
+        if input_xml is not None :
+            for event_xml in input_xml :
+                if event_xml.tag == "event" :
+                    self.controller.addInput(Event(event_xml.get("name"), event_xml.get("port")))
+                    
+        expected_xml = test_xml.find("expected")
+        if expected_xml is None : 
+            #no expected result, so we just simulate without catching output
+            self.controller.start()
+            self.controller.join()
+            return
+        
+        #Creating a datastructure for the expected output
+        expected_result = []
+        output_ports = set()
+
+        for slot_xml in expected_xml :
+            if slot_xml.tag == "slot" :
+                slot = []
+                for event_xml in slot_xml :
+                    if event_xml.tag == "event" :
+                        event_name = event_xml.get("name")
+                        port = event_xml.get("port")
+                        parameters = []
+                        parameters_xml = event_xml.findall("parameter")
+                        for parameter_xml in parameters_xml :
+                            parameter_value = parameter_xml.get("value", None)
+                            if parameter_value is not None :
+                                parameters.append(parameter_value)
+                        slot.append(TestEvent(event_name, port,parameters))
+                        output_ports.add(port)
+                if slot :
+                    expected_result.append(slot)
+
+        #Execution
+        output_listener = self.controller.addOutputListener(list(output_ports))
+        self.controller.start()
+        self.controller.join()
+        
+        #Check output
+        for (slot_index, slot) in enumerate(expected_result, start=1) : 
+            remaining_options = slot[:]
+            received_output = [] 
+            while remaining_options :
+                output_event = output_listener.fetch()
+                received_output.append(output_event)
+                match_index = -1
+                for (index, option) in enumerate(remaining_options) :
+                    if option.matches(output_event) :
+                        match_index = index
+                        break
+                
+                self.assertNotEqual(match_index, -1, "Expected results slot " + str(slot_index) + " mismatch. Expected " + str(slot) + ", but got " + str(received_output) +  " instead.") #no match found in the options
+                remaining_options.pop(match_index)
+                            
+        #check if there are no extra events          
+        self.assertEqual(output_listener.fetch(0), None, "More output events than expected on selected ports.")   
+        
+        
+if __name__ == '__main__':
+    suite = unittest.TestSuite()
+
+    for file_name in os.listdir(os.getcwd() + "/" + SHARED_TEST_FILES_FOLDER):
+        if file_name.endswith(".xml"): 
+            suite.addTest(XMLTestCase(file_name))
+            
+    unittest.TextTestRunner(verbosity=2).run(suite)

+ 73 - 0
debugging_environment/python_sccd_compiler/utils.py

@@ -0,0 +1,73 @@
+class Logger(object):
+    verbose = 0 #-1= no output
+                #0 = only errors
+                #1 = only warnings and errors
+                #2 = all output
+                
+    @staticmethod   
+    def showError(error):
+        if(Logger.verbose > -1) :
+            print "ERROR : " + error
+                
+    @staticmethod
+    def showWarning(warning):
+        if(Logger.verbose > 0) :
+            print "WARNING : " + warning
+            
+    @staticmethod    
+    def showInfo(info):
+        if(Logger.verbose > 1) :
+            print "INFO : " + info
+
+#######################
+
+class Enum():    
+    def __init__(self, *entries):
+        self._keys = entries
+        self._map = {}
+        for v,k in enumerate(self._keys) :
+            self._map[k] = v
+            
+    def __getattr__(self, name):
+        return self._map[name]
+            
+    def name_of(self, index):
+        return self._keys[index]
+
+#######################
+
+class FileOutputer:
+
+    def __init__(self, filename):
+        self.out = open(filename, 'w')
+        self.indentLevel = 0
+        self.indentSpace = "    "
+        self.first_write = True
+
+    def write(self, text = ""):
+        if self.first_write :
+            self.first_write = False
+            if text == "":
+                self.out.write(self.indentLevel*self.indentSpace)
+            else:
+                self.out.write(self.indentLevel*self.indentSpace + text)  
+        else:
+            if text == "":
+                self.out.write("\n" + self.indentLevel*self.indentSpace)
+            else:
+                self.out.write("\n" + self.indentLevel*self.indentSpace + text)
+    
+    def extendWrite(self, text = ""):
+        self.out.write(text)            
+                
+    def indent(self):
+        self.indentLevel+=1
+
+    def dedent(self):
+        self.indentLevel-=1
+
+    def close(self):
+        self.out.close()
+
+
+#######################

+ 30 - 0
debugging_environment/python_sccd_compiler/visitor.py

@@ -0,0 +1,30 @@
+class Visitor(object):
+    def _visit(self, node, prepend, *args):
+        prepend = prepend + "_"
+        meth = None
+        for cls in node.__class__.__mro__:
+            meth_name = prepend + cls.__name__
+            meth = getattr(self, meth_name, None)
+            if meth:
+                break
+
+        if not meth:
+            meth = self.generic_visit
+        return meth(node, *args)
+    
+    def visit(self, node, *args):
+        self._visit(node, "visit", *args)
+    
+    def enter(self, node, *args):
+        self._visit(node, "enter", *args)
+        
+    def exit(self, node, *args):
+        self._visit(node, "exit", *args)
+
+    def generic_visit(self, node):
+        #print 'generic_visit '+node.__class__.__name__
+        pass
+        
+class Visitable(object):
+    def accept(self, visitor):
+        visitor.visit(self) 

+ 178 - 0
debugging_environment/simulation_client.py

@@ -0,0 +1,178 @@
+'''
+TODO:
+V Realtime interrupts of the visualization need to be propagated to the simulation.
+V Change visualization to show in same browser window, not a pop-up.
+V Reset
+V Communication debugging interface -> visualization interface (for reset for example, or step back).
+V State visualization in debugging interface (on hover?).
+V Communication visualization interface -> debugging interface (for 'select an entity', for example).
+V As fast as possible simulation.
+V Visualization of "current small step" (1-8).
+V Breakpoints.
+V Inject events.
+V God events.
+V Fix bug: no visualization when small stepping.
+V Highlight transitioning nodes.
+V Display simulation time.
+V Realtime scale.
+V Termination condition.
+V Handling of multiple connections for a single output port when a message is routed.
+- Remove and add element/port/port connection. (? validity)
+- Proper serialization of state: now I only serialize primitive values, and ignore composite ones. Needs to have a translation between Python and JS.
+- Parameters for simulation initialization.
+- Robustness.
+- Each client has their own debugger?
+- Integrate with new version of SCCD (see Joeri's mail).
+'''
+
+import socket, sys, json, threading, time, pickle, copy
+
+sys.path.append("pypdevs")
+sys.path.append("..")
+
+import Tkinter as tk
+from particle_interaction import *
+import sccd
+from python_runtime.statecharts_core import Event
+
+HOST, PORT = "127.0.0.1", 9999
+sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+sock.connect((HOST, PORT))
+
+'''
+This function actually receives messages from the debugging interface (or instrumented visualizatin interface).
+The communication protocol is very basic: all messages are terminated with a new line. This function makes sure
+only 'full' messages are returned.
+'''
+end='\n'
+def recv_end(the_socket):
+    total_data = []
+    data = ''
+    while True:
+        data = the_socket.recv(8192)
+        if end in data:
+            total_data.append(data[:data.find(end)])
+            break
+        total_data.append(data)
+        if len(total_data) > 1:
+            last_pair = total_data[-2] + total_data[-1]
+            if end in last_pair:
+                total_data[-2]=last_pair[:last_pair.find(end)]
+                total_data.pop()
+                break
+    return ''.join(total_data)
+
+'''
+Send a message to the communication layer (which will then be routed to either the debugging interface or the
+visualization server, based on the first entry in the sent array). Each message needs to end with a new line,
+as the protocol specifies.
+'''
+def send_msg(msg):
+    try:
+        sock.send(msg + '\n')
+    except socket.error:
+        sys.exit(0)
+
+'''
+Handle output messages of the simulation on the pos, color, and time ports, respectively.
+'''
+def handle_output_pos(msgs):
+    for msg_contents in msgs:
+        send_msg(json.dumps(["VIS", "POS_OUT", msg_contents]))
+
+def handle_output_color(msgs):
+    for msg_contents in msgs:
+        send_msg(json.dumps(["VIS", "COLOR_OUT", msg_contents]))
+
+def handle_output_time(msgs):
+    for msg_contents in msgs:
+        send_msg(json.dumps(["VIS", "TIME_OUT", "%.2f" % (float(msg_contents / 30.0))]))
+
+'''
+Serializes a Python object to a form where it is ready for JSON serialization.
+'''
+def todict(obj, classkey=None):
+    if isinstance(obj, dict):
+        data = {}
+        for (k, v) in obj.items():
+            if v.__class__.__name__.endswith("State") or not hasattr(v, '__dict__'): # TODO: UGLY!!!
+                data[k] = todict(v, classkey)
+        return data
+    elif hasattr(obj, "__iter__"):
+        return [todict(v, classkey) for v in copy.copy(obj) if (v.__class__.__name__.endswith("State") or not hasattr(v, '__dict__'))] # TODO: UGLY!!!
+    elif hasattr(obj, "__dict__"):
+        data = dict([(key, todict(value, classkey)) 
+            for key, value in copy.copy(obj.__dict__).iteritems() 
+            if not callable(value) and not key.startswith('_') and (value.__class__.__name__.endswith("State") or not hasattr(value, '__dict__'))]) # TODO: UGLY!!!
+        if classkey is not None and hasattr(obj, "__class__"):
+            data[classkey] = obj.__class__.__name__
+        return data
+    else:
+        return obj
+
+'''
+Blocks until a message is received on the specified port. Immediately sends that message (which needs to be
+forwarded to the debugging interface).
+'''
+def poll_port(port):
+    while 1:
+        msg = port.fetch(-1)
+        send_msg(json.dumps(["DBG", todict(msg)]))
+        
+if __name__ == '__main__':
+    # Simulation parameters.
+    resolution = (800, 600)
+    framerate = 30
+    spawn_chance = 0.2
+    die_chance = 0.01
+
+    # Instantiate model to simulate.
+    model = Root(Canvas(resolution), framerate, spawn_chance, die_chance)
+    
+    # Instantiate and start our debugger (compiled Statecharts model).
+    sim_controller = sccd.Controller(model)
+    sim_controller.start()
+    
+    # Forward debugging messages to debugging server (in a separate thread).
+    reply_port = sim_controller.addOutputListener('reply')
+    thrd = threading.Thread(target=poll_port,args=[reply_port])
+    thrd.daemon = True
+    thrd.start()
+    
+    # Listen for simulation output on specified DEVS ports.
+    sim_controller.addInput(Event("set_listen_ports", "request", ["POS_OUT", handle_output_pos]))
+    sim_controller.addInput(Event("set_listen_ports", "request", ["COLOR_OUT", handle_output_color]))
+    sim_controller.addInput(Event("set_listen_ports", "request", ["TIME_OUT", handle_output_time]))
+    
+    print 'Waiting for commands...'
+    
+    # Main loop: receive a message from the debugging interface (or the instrumented visualization server) and send it to the debugger.
+    while 1:
+        try:
+            msg = recv_end(sock)
+        except socket.error:
+            break
+        msg_head, msg_body = msg[:4], msg[4:]
+        if msg_head == 'dbg_':
+            decoded_event = json.loads(msg_body);
+            parameters = decoded_event["parameters"]
+            if decoded_event["name"] == "god_event":
+                event = Event("god_event", "request", parameters)
+            elif decoded_event["name"] == "inject":
+                event = Event("inject", "request", parameters)
+            elif decoded_event["name"] == "add_breakpoint":
+                event = Event("add_breakpoint", "request", parameters[0])
+            elif decoded_event["name"] == "toggle_breakpoint":
+                event = Event("toggle_breakpoint", "request", parameters)
+            elif decoded_event["name"] == "del_breakpoint":
+                event = Event("del_breakpoint", "request", parameters)
+            elif decoded_event["name"] == "reset":
+                event = Event("reset", "request", parameters)
+            elif parameters[0] == "realtime":
+                event = Event(parameters[0], "request", [{"termination_condition": termination_condition, "realtime_scale": float(parameters[1]["realtime_scale"])}])
+            else:
+                event = Event(parameters[0], "request", [{"termination_condition": termination_condition}])
+            sim_controller.addInput(event)
+        elif msg_head == 'vis_':
+            event = Event("realtime_interrupt", "request", [msg_body])
+            sim_controller.addInput(event)

+ 674 - 0
javascript_models/LICENSE

@@ -0,0 +1,674 @@
+GNU GENERAL PUBLIC LICENSE
+                       Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+                            Preamble
+
+  The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users.  We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors.  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+  To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights.  Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received.  You must make sure that they, too, receive
+or can get the source code.  And you must show them these terms so they
+know their rights.
+
+  Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+  For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software.  For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+  Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so.  This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software.  The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable.  Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products.  If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+  Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary.  To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+                       TERMS AND CONDITIONS
+
+  0. Definitions.
+
+  "This License" refers to version 3 of the GNU General Public License.
+
+  "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+  "The Program" refers to any copyrightable work licensed under this
+License.  Each licensee is addressed as "you".  "Licensees" and
+"recipients" may be individuals or organizations.
+
+  To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy.  The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+  A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+  To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy.  Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+  To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies.  Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+  An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License.  If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+  1. Source Code.
+
+  The "source code" for a work means the preferred form of the work
+for making modifications to it.  "Object code" means any non-source
+form of a work.
+
+  A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+  The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form.  A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+  The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities.  However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work.  For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+  The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+  The Corresponding Source for a work in source code form is that
+same work.
+
+  2. Basic Permissions.
+
+  All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met.  This License explicitly affirms your unlimited
+permission to run the unmodified Program.  The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work.  This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+  You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force.  You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright.  Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+  Conveying under any other circumstances is permitted solely under
+the conditions stated below.  Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+  3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+  No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+  When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+  4. Conveying Verbatim Copies.
+
+  You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+  You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+  5. Conveying Modified Source Versions.
+
+  You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+    a) The work must carry prominent notices stating that you modified
+    it, and giving a relevant date.
+
+    b) The work must carry prominent notices stating that it is
+    released under this License and any conditions added under section
+    7.  This requirement modifies the requirement in section 4 to
+    "keep intact all notices".
+
+    c) You must license the entire work, as a whole, under this
+    License to anyone who comes into possession of a copy.  This
+    License will therefore apply, along with any applicable section 7
+    additional terms, to the whole of the work, and all its parts,
+    regardless of how they are packaged.  This License gives no
+    permission to license the work in any other way, but it does not
+    invalidate such permission if you have separately received it.
+
+    d) If the work has interactive user interfaces, each must display
+    Appropriate Legal Notices; however, if the Program has interactive
+    interfaces that do not display Appropriate Legal Notices, your
+    work need not make them do so.
+
+  A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit.  Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+  6. Conveying Non-Source Forms.
+
+  You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+    a) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by the
+    Corresponding Source fixed on a durable physical medium
+    customarily used for software interchange.
+
+    b) Convey the object code in, or embodied in, a physical product
+    (including a physical distribution medium), accompanied by a
+    written offer, valid for at least three years and valid for as
+    long as you offer spare parts or customer support for that product
+    model, to give anyone who possesses the object code either (1) a
+    copy of the Corresponding Source for all the software in the
+    product that is covered by this License, on a durable physical
+    medium customarily used for software interchange, for a price no
+    more than your reasonable cost of physically performing this
+    conveying of source, or (2) access to copy the
+    Corresponding Source from a network server at no charge.
+
+    c) Convey individual copies of the object code with a copy of the
+    written offer to provide the Corresponding Source.  This
+    alternative is allowed only occasionally and noncommercially, and
+    only if you received the object code with such an offer, in accord
+    with subsection 6b.
+
+    d) Convey the object code by offering access from a designated
+    place (gratis or for a charge), and offer equivalent access to the
+    Corresponding Source in the same way through the same place at no
+    further charge.  You need not require recipients to copy the
+    Corresponding Source along with the object code.  If the place to
+    copy the object code is a network server, the Corresponding Source
+    may be on a different server (operated by you or a third party)
+    that supports equivalent copying facilities, provided you maintain
+    clear directions next to the object code saying where to find the
+    Corresponding Source.  Regardless of what server hosts the
+    Corresponding Source, you remain obligated to ensure that it is
+    available for as long as needed to satisfy these requirements.
+
+    e) Convey the object code using peer-to-peer transmission, provided
+    you inform other peers where the object code and Corresponding
+    Source of the work are being offered to the general public at no
+    charge under subsection 6d.
+
+  A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+  A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling.  In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage.  For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product.  A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+  "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source.  The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+  If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information.  But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+  The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed.  Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+  Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+  7. Additional Terms.
+
+  "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law.  If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+  When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it.  (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.)  You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+  Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+    a) Disclaiming warranty or limiting liability differently from the
+    terms of sections 15 and 16 of this License; or
+
+    b) Requiring preservation of specified reasonable legal notices or
+    author attributions in that material or in the Appropriate Legal
+    Notices displayed by works containing it; or
+
+    c) Prohibiting misrepresentation of the origin of that material, or
+    requiring that modified versions of such material be marked in
+    reasonable ways as different from the original version; or
+
+    d) Limiting the use for publicity purposes of names of licensors or
+    authors of the material; or
+
+    e) Declining to grant rights under trademark law for use of some
+    trade names, trademarks, or service marks; or
+
+    f) Requiring indemnification of licensors and authors of that
+    material by anyone who conveys the material (or modified versions of
+    it) with contractual assumptions of liability to the recipient, for
+    any liability that these contractual assumptions directly impose on
+    those licensors and authors.
+
+  All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10.  If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term.  If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+  If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+  Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+  8. Termination.
+
+  You may not propagate or modify a covered work except as expressly
+provided under this License.  Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+  However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+  Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+  Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License.  If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+  9. Acceptance Not Required for Having Copies.
+
+  You are not required to accept this License in order to receive or
+run a copy of the Program.  Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance.  However,
+nothing other than this License grants you permission to propagate or
+modify any covered work.  These actions infringe copyright if you do
+not accept this License.  Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+  10. Automatic Licensing of Downstream Recipients.
+
+  Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License.  You are not responsible
+for enforcing compliance by third parties with this License.
+
+  An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations.  If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+  You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License.  For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+  11. Patents.
+
+  A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based.  The
+work thus licensed is called the contributor's "contributor version".
+
+  A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version.  For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+  Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+  In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement).  To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+  If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients.  "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+  If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+  A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License.  You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+  Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+  12. No Surrender of Others' Freedom.
+
+  If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all.  For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+  13. Use with the GNU Affero General Public License.
+
+  Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work.  The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+  Each version is given a distinguishing version number.  If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation.  If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+  If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+  Later license versions may give you additional or different
+permissions.  However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+  15. Disclaimer of Warranty.
+
+  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+  16. Limitation of Liability.
+
+  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+  17. Interpretation of Sections 15 and 16.
+
+  If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+                     END OF TERMS AND CONDITIONS
+
+            How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    {one line to give the program's name and a brief idea of what it does.}
+    Copyright (C) {year}  {name of author}
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+  If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+    {project}  Copyright (C) {year}  {fullname}
+    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+  You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+  The GNU General Public License does not permit incorporating your program
+into proprietary programs.  If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.  But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.

+ 52 - 0
javascript_models/README.md

@@ -0,0 +1,52 @@
+This is a fork of https://github.com/gl3nn/sccd_compiler
+
+Statecharts and Class Diagram Compiler
+======================================
+
+Usage
+-------------
+Manual for the compiler written in Python :
+```sh
+$python sccdc.py --help
+usage: sccdc.py [-h] [-o OUTPUT] [-v VERBOSE] [-p PROTOCOL] [-l LANGUAGE]
+                input
+
+positional arguments:
+  input                 The path to the XML file to be compiled.
+
+optional arguments:
+  -h, --help            show this help message and exit
+  -o OUTPUT, --output OUTPUT
+                        The path to the generated code. Defaults to the same
+                        name as the input file but with matching extension.
+  -v VERBOSE, --verbose VERBOSE
+                        2 = all output; 1 = only warnings and errors; 0 = only
+                        errors; -1 = no output. Defaults to 2.
+  -p PLATFORM, --platform PLATFORM
+                        Let the compiled code run on top of threads or
+                        gameloop. The default is threads.
+  -l LANGUAGE, --language LANGUAGE
+                        Target language, "csharp", "python" or "javascript". Defaults
+                        to "python".
+```
+
+For a detailed explanation on the formalism's syntax please consult the latest report <a href="http://msdl.cs.mcgill.ca/people/glenn/60_Downloads">here</a>.
+
+Tests
+-------------
+Executing the tests written for the Python compiler and generated Python code can be done by running `tests.py`. This file imports the test cases from the `test_files` folder.
+
+Tanks Example
+-------------
+In the `tanks` folder a tanks game can be found for which both the input handling of the player-controlled tank, and the behaviour of the NPC tank are modelled using the SCCD formalism. For this specific example the commands to compile the models are as follows :
+
+```sh
+python sccdc.py tanks/player_controller.xml -o tanks/player_controller.py -p gameloop
+python sccdc.py tanks/ai_controller.xml -o tanks/ai_controller.py -p gameloop
+```
+The resulting files `player_controller.py` and `ai_controller.py` (and any other compiled code) depend on the runtime files found in `python_runtime`, so this folder should either be put in `PYTHONPATH` or directly in the `tanks` directory (you can use a symbolic link).
+
+Live demo
+---------
+
+Live demo of a statechart (compiled to Javascript) simulating a bouncing ball: https://gwd.dyn.mk/public/sccd/svgdemo

+ 11 - 0
javascript_models/bouncing.html

@@ -0,0 +1,11 @@
+<div>
+<script src="javascript_runtime/statecharts_core.js"></script>
+<script src="javascript_runtime/libs/utils.js"></script>
+<script src="javascript_runtime/libs/svg.js"></script>
+<script src="javascript_runtime/libs/ui.js"></script>
+<script src="bouncing_balls.js"></script>
+<script>
+controller = new Bouncing_Balls.Controller();
+controller.start();
+</script> 
+</div>

File diff suppressed because it is too large
+ 1733 - 0
javascript_models/bouncing_balls.js


+ 403 - 0
javascript_models/bouncing_balls.js.xml

@@ -0,0 +1,403 @@
+<?xml version="1.0" ?>
+<diagram name="Bouncing_Balls" author="Simon Van Mierlo+Joeri Exelmans+Raphael Mannadiar">
+	<description>
+		Tkinter frame with bouncing balls in it.
+	</description>
+	<inport name="field_ui"/>
+	<inport name="ball_ui"/>
+	<inport name="ui"/>
+	<class name="Button">
+		<relationships>
+			<association name="parent" class="Field" min="1" max="1"/>
+		</relationships>
+		<method name="Button">
+			<parameter name="parent" type="Field"/>
+			<parameter name="event_name" type="str"/>
+			<parameter name="button_text" type="str"/>
+			<body>
+			<![CDATA[
+				this.event_name = event_name;
+				var button = ui.append_button(parent.field_window, event_name);
+				ui.bind_event(button.element, ui.EVENTS.MOUSE_CLICK, this.controller, 'mouse_click');
+			]]>
+			</body>
+		</method>
+		<scxml  initial="initializing">
+			<state id="initializing">
+				<transition target="../running">
+					<raise event="button_created" scope="narrow" target="'parent'">
+					</raise>
+				</transition>
+			</state>
+			<state id="running">
+				<transition port="ui" target="." event="mouse_click" cond="button == ui.MOUSE_BUTTONS.LEFT">
+					<parameter name="x" type="int"/>
+					<parameter name="y" type="int"/>
+					<parameter name="button" type="Button"/>
+					<raise event="button_pressed" scope="narrow" target="'parent'">
+						<parameter expr="this.event_name"/>
+					</raise>
+				</transition>
+			</state>
+		</scxml>
+	</class>
+	<class name="Field">
+		<inport name="field_ui"/>
+		<relationships>
+			<association name="parent" class="MainApp" min="1" max="1"/>
+			<association name="buttons" class="Button"/>
+			<association name="balls" class="Ball"/>
+		</relationships>
+		<attribute name="field_window"/>
+		<attribute name="canvas"/>
+		<method name="Field">
+			<body>
+			<![CDATA[
+				this.field_window = ui.new_window(400, 450);
+				this.canvas = ui.append_canvas(this.field_window, 400, 400, {'background':'#eee'});
+				ui.bind_event(this.field_window, ui.EVENTS.WINDOW_CLOSE, this.controller, 'window_close');
+				ui.bind_event(this.field_window, ui.EVENTS.KEY_PRESS, this.controller, 'key_press');
+				ui.bind_event(this.canvas.element, ui.EVENTS.MOUSE_RIGHT_CLICK, this.controller, 'right_click', this.inports['field_ui']);
+				ui.bind_event(this.canvas.element, ui.EVENTS.MOUSE_MOVE, this.controller, 'mouse_move');
+				ui.bind_event(this.canvas.element, ui.EVENTS.MOUSE_RELEASE, this.controller, 'mouse_release');
+			]]>
+			</body>
+		</method>
+		<method name="~Field">
+			<body>
+			<![CDATA[
+				ui.close_window(this.field_window);
+			]]>
+			</body>
+		</method>
+		<scxml  initial="root">
+			<state id="root" initial="waiting">
+				<state id="waiting">
+					<transition target="../initializing" event="set_association_name">
+						<parameter name="association_name" type="str"/>
+						<script>
+							<![CDATA[
+								this.association_name = association_name;
+							]]>
+						</script>
+					</transition>
+				</state>
+				<state id="packing">
+					<transition target="../running" event="button_created">
+					</transition>
+				</state>
+				<state id="deleting">
+					<transition after="0.05" target="../deleted">
+						<raise event="delete_field" scope="narrow" target="'parent'">
+							<parameter expr="this.association_name"/>
+						</raise>
+					</transition>
+				</state>
+				<state id="creating">
+					<transition target="../packing" event="instance_created">
+						<parameter name="association_name" type="string"/>
+						<raise event="start_instance" scope="cd">
+							<parameter expr="association_name"/>
+						</raise>
+					</transition>
+				</state>
+				<state id="initializing">
+					<transition target="../creating">
+						<raise event="create_instance" scope="cd">
+							<parameter expr="'buttons'"/>
+							<parameter expr="'Button'"/>
+							<parameter expr="this"/>
+							<parameter expr="'create_new_field'"/>
+							<parameter expr="'Spawn New Window'"/>
+						</raise>
+					</transition>
+				</state>
+				<state id="deleted">
+				</state>
+				<parallel id="running">
+					<transition port="ui" target="../deleting" event="window_close" cond="window == this.field_window || window == ui.window">
+						<parameter name="window" type="Window"/>
+						<raise event="delete_instance" scope="cd">
+							<parameter expr="'buttons'"/>
+						</raise>
+						<raise event="delete_self" scope="narrow" target="'balls'">
+						</raise>
+					</transition>
+					<state id="main_behaviour" initial="running">
+						<state id="running">
+							<transition port="field_ui" target="../creating" event="right_click">
+								<parameter name="x" type="int"/>
+								<parameter name="y" type="int"/>
+								<parameter name="button" type="Button"/>
+								<raise event="create_instance" scope="cd">
+									<parameter expr="'balls'"/>
+									<parameter expr="'Ball'"/>
+									<parameter expr="this.canvas"/>
+									<parameter expr="x"/>
+									<parameter expr="y"/>
+									<parameter expr="this.field_window"/>
+								</raise>
+							</transition>
+						</state>
+						<state id="creating">
+							<transition target="../running" event="instance_created">
+								<parameter name="association_name" type="string"/>
+								<raise event="set_association_name" scope="narrow" target="association_name">
+									<parameter expr="association_name"/>
+								</raise>
+								<raise event="start_instance" scope="cd">
+									<parameter expr="association_name"/>
+								</raise>
+							</transition>
+						</state>
+					</state>
+					<state id="deleting_behaviour" initial="running">
+						<state id="running">
+							<transition target="." event="delete_ball">
+								<parameter name="association_name" type="str"/>
+								<raise event="delete_instance" scope="cd">
+									<parameter expr="association_name"/>
+								</raise>
+							</transition>
+						</state>
+					</state>
+					<state id="child_behaviour" initial="listening">
+						<state id="listening">
+							<transition target="." event="button_pressed">
+								<parameter name="event_name" type="str"/>
+								<raise event="button_pressed" scope="narrow" target="'parent'">
+									<parameter expr="event_name"/>
+								</raise>
+							</transition>
+						</state>
+					</state>
+				</parallel>
+			</state>
+		</scxml>
+	</class>
+	<class name="MainApp" default="True">
+		<relationships>
+			<association name="fields" class="Field"/>
+		</relationships>
+		<method name="MainApp">
+			<body>
+			<![CDATA[
+				this.nr_of_fields = 0;
+				ui.bind_event(ui.window, ui.EVENTS.WINDOW_CLOSE, this.controller, 'window_close');
+			]]>
+			</body>
+		</method>
+		<scxml  initial="running">
+			<state id="running" initial="root">
+				<state id="stopped">
+				</state>
+				<parallel id="root">
+					<state id="main_behaviour" initial="initializing">
+						<state id="initializing">
+							<transition target="../running">
+								<raise event="create_field">
+								</raise>
+							</transition>
+						</state>
+						<state id="running">
+							<transition target="." event="button_pressed" cond="event_name == 'create_new_field'">
+								<parameter name="event_name" type="str"/>
+								<raise event="create_field">
+								</raise>
+							</transition>
+						</state>
+					</state>
+					<state id="cd_behaviour" initial="waiting">
+						<state id="creating">
+							<transition target="../waiting" event="instance_created">
+								<parameter name="association_name" type="string"/>
+								<raise event="start_instance" scope="cd">
+									<parameter expr="association_name"/>
+								</raise>
+								<raise event="set_association_name" scope="narrow" target="association_name">
+									<parameter expr="association_name"/>
+								</raise>
+								<script>
+									<![CDATA[
+										this.nr_of_fields += 1;
+									]]>
+								</script>
+							</transition>
+						</state>
+						<state id="waiting">
+							<transition target="../creating" event="create_field">
+								<raise event="create_instance" scope="cd">
+									<parameter expr="'fields'"/>
+								</raise>
+							</transition>
+							<transition target="../check_nr_of_fields" event="delete_field">
+								<parameter name="association_name" type="str"/>
+								<raise event="delete_instance" scope="cd">
+									<parameter expr="association_name"/>
+								</raise>
+								<script>
+									<![CDATA[
+										this.nr_of_fields -= 1;
+									]]>
+								</script>
+							</transition>
+						</state>
+						<state id="check_nr_of_fields">
+							<transition target="../waiting" cond="this.nr_of_fields != 0">
+							</transition>
+							<transition target="../../../stopped" cond="this.nr_of_fields == 0">
+								<script>
+									<![CDATA[
+										ui.close_window(ui.window);
+									]]>
+								</script>
+							</transition>
+						</state>
+					</state>
+				</parallel>
+			</state>
+		</scxml>
+	</class>
+	<class name="Ball">
+		<inport name="ball_ui"/>
+		<relationships>
+			<association name="parent" class="Field" min="1" max="1"/>
+		</relationships>
+		<attribute name="field_window"/>
+		<attribute name="canvas"/>
+		<attribute name="element"/>
+		<method name="Ball">
+			<parameter name="canvas"/>
+			<parameter name="x"/>
+			<parameter name="y"/>
+			<parameter name="field_window"/>
+			<body>
+			<![CDATA[
+				this.canvas = canvas;
+				this.field_window = field_window;
+				this.r = 20.0;
+				this.vel = {'x':utils.random() * 2.0 - 1.0, 'y':utils.random() * 2.0 - 1.0};
+				this.mouse_pos = {'':''};
+				this.smooth = 0.4;
+				var circle = this.canvas.add_circle(x, y, this.r, {'fill':'#000'});
+				ui.bind_event(circle, ui.EVENTS.MOUSE_PRESS, this.controller, 'mouse_press', this.inports['ball_ui']);
+				ui.bind_event(circle, ui.EVENTS.MOUSE_RIGHT_CLICK, this.controller, 'right_click');
+				this.element = circle;
+			]]>
+			</body>
+		</method>
+		<method name="~Ball">
+			<body>
+			<![CDATA[
+				this.canvas.remove_element(this.element);
+			]]>
+			</body>
+		</method>
+		<scxml  initial="main_behaviour">
+			<state id="main_behaviour" initial="initializing">
+				<transition target="../deleted" event="delete_self">
+					<raise event="delete_ball" scope="narrow" target="'parent'">
+						<parameter expr="this.association_name"/>
+					</raise>
+				</transition>
+				<state id="dragging">
+					<transition port="ui" target="../bouncing" event="mouse_release">
+						<parameter name="x" type="int"/>
+						<parameter name="y" type="int"/>
+						<script>
+							<![CDATA[
+								this.element.set_color('#f00');
+							]]>
+						</script>
+					</transition>
+					<transition port="ui" target="." event="mouse_move">
+						<parameter name="x" type="int"/>
+						<parameter name="y" type="int"/>
+						<parameter name="button" type="Button"/>
+						<script>
+							<![CDATA[
+								var dx = x - this.mouse_pos['x'];
+								var dy = y - this.mouse_pos['y'];
+								this.element.move(dx, dy);
+								var pos = this.element.get_position();
+								if(pos.x - this.r <= 0) {
+									pos.x = this.r + 1;
+								} else {
+									if(pos.x + this.r >= this.canvas.width) {
+										pos.x = this.canvas.width - this.r - 1;
+									}
+								}
+								if(pos.y - this.r <= 0) {
+									pos.y = this.r + 1;
+								} else {
+									if(pos.y + this.r >= this.canvas.height) {
+										pos.y = this.canvas.height - this.r - 1;
+									}
+								}
+								this.element.set_position(pos.x, pos.y);
+								this.mouse_pos = {'x':x, 'y':y};
+								this.vel = {'x':(1 - this.smooth) * dx + this.smooth * this.vel['x'], 'y':(1 - this.smooth) * dy + this.smooth * this.vel['y']};
+							]]>
+						</script>
+					</transition>
+				</state>
+				<state id="selected">
+					<transition port="ball_ui" target="../dragging" event="mouse_press" cond="button == ui.MOUSE_BUTTONS.LEFT">
+						<parameter name="x" type="int"/>
+						<parameter name="y" type="int"/>
+						<parameter name="button" type="Button"/>
+						<script>
+							<![CDATA[
+								this.mouse_pos = {'x':x, 'y':y};
+							]]>
+						</script>
+					</transition>
+					<transition port="ui" target="." event="key_press" cond="key == ui.KEYCODES.DELETE &amp;&amp; active_window == this.field_window">
+						<parameter name="key" type="Key"/>
+						<parameter name="active_window" type="Window"/>
+						<raise event="delete_self" scope="local">
+						</raise>
+					</transition>
+				</state>
+				<state id="initializing">
+					<transition target="../bouncing" event="set_association_name">
+						<parameter name="association_name" type="str"/>
+						<script>
+							<![CDATA[
+								this.association_name = association_name;
+							]]>
+						</script>
+					</transition>
+				</state>
+				<state id="bouncing">
+					<transition after="0.01" target=".">
+						<script>
+							<![CDATA[
+								var pos = this.element.get_position();
+								if(pos.x - this.r <= 0 || pos.x + this.r >= this.canvas.width) {
+									this.vel['x'] = -this.vel['x'];
+								}
+								if(pos.y - this.r <= 0 || pos.y + this.r >= this.canvas.height) {
+									this.vel['y'] = -this.vel['y'];
+								}
+								this.element.move(this.vel['x'], this.vel['y']);
+							]]>
+						</script>
+					</transition>
+					<transition port="ball_ui" target="../selected" event="mouse_press" cond="button == ui.MOUSE_BUTTONS.LEFT">
+						<parameter name="x" type="int"/>
+						<parameter name="y" type="int"/>
+						<parameter name="button" type="Button"/>
+						<script>
+							<![CDATA[
+								this.element.set_color('#ff0');
+							]]>
+						</script>
+					</transition>
+				</state>
+			</state>
+			<state id="deleted">
+			</state>
+		</scxml>
+	</class>
+</diagram>

File diff suppressed because it is too large
+ 1733 - 0
javascript_models/bouncing_balls_backup.js


+ 77 - 0
javascript_models/csharp_runtime/Association.cs

@@ -0,0 +1,77 @@
+using System;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Diagnostics;
+
+namespace sccdlib
+{
+    /**
+     * wrapper object for one association relation
+     */
+    public class Association
+    {
+        string name;
+        string class_name;
+        int min_card;
+        int max_card;
+        List<InstanceWrapper> instances;
+        
+        public Association (string name, string class_name, int min_card, int max_card)
+        {
+            this.min_card = min_card;
+            this.max_card = max_card;
+            this.name = name;
+            this.class_name = class_name;
+            this.instances = new List<InstanceWrapper>();
+        }
+        
+        public string getName ()
+        {
+            return this.name;
+        }
+        
+        public string getClassName ()
+        {
+            return this.class_name;   
+        }
+        
+        public bool allowedToAdd ()
+        {
+            return ( (this.max_card == -1) || ( this.instances.Count < this.max_card ) );    
+        }
+        
+        public void addInstance (InstanceWrapper instance)
+        {
+            if (this.allowedToAdd ()) {
+                this.instances.Add (instance);
+            } else {
+                throw new AssociationException("Not allowed to add the instance to the association.");
+            }
+        }
+        
+        public ReadOnlyCollection<InstanceWrapper> getAllInstances ()
+        {
+            return this.instances.AsReadOnly();   
+        }
+        
+        /*
+        public List<InstanceWrapper> getAllInstances ()
+        {
+            return new List<InstanceWrapper>(this.instances);
+        }*/
+        
+        public InstanceWrapper getInstance(int index)
+        {
+            try 
+            {
+                return this.instances[index];
+            }
+            catch (ArgumentOutOfRangeException)
+            {
+                throw new AssociationException("Invalid index for fetching instance from association.");
+            }
+        }
+        
+    }
+}
+

+ 23 - 0
javascript_models/csharp_runtime/AssociationException.cs

@@ -0,0 +1,23 @@
+using System;
+
+namespace sccdlib
+{
+    public class AssociationException : RunTimeException
+    {
+        public AssociationException ()
+        {
+        }
+        
+        public AssociationException(string message)
+            : base(message)
+        {
+        }
+    
+        public AssociationException(string message, Exception inner)
+            : base(message, inner)
+        {
+        }
+    }
+  
+}
+

+ 22 - 0
javascript_models/csharp_runtime/AssociationReferenceException.cs

@@ -0,0 +1,22 @@
+using System;
+
+namespace sccdlib
+{
+    public class AssociationReferenceException : RunTimeException
+    {
+        public AssociationReferenceException ()
+        {
+        }
+        
+        public AssociationReferenceException(string message)
+            : base(message)
+        {
+        }
+    
+        public AssociationReferenceException(string message, Exception inner)
+            : base(message, inner)
+        {
+        }
+    }
+}
+

+ 12 - 0
javascript_models/csharp_runtime/AssociationWrapper.cs

@@ -0,0 +1,12 @@
+using System;
+
+namespace sccdlib
+{
+    public class AssociationWrapper
+    {
+        public AssociationWrapper ()
+        {
+        }
+    }
+}
+

+ 38 - 0
javascript_models/csharp_runtime/ConcurrentOutputListener.cs

@@ -0,0 +1,38 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+
+namespace sccdlib
+{
+    public class ConcurrentOutputListener : IOutputListener
+    {
+        ConcurrentQueue<Event> queue = new ConcurrentQueue<Event>();
+        List<string> ports = new List<string>();
+        
+        public ConcurrentOutputListener (string[] port_names)
+        {
+            foreach (string port_name in port_names)
+            {
+                this.ports.Add (port_name);
+            }
+        }
+        
+        public void add (Event output_event)
+        {
+            if (this.ports.Count == 0 || this.ports.Contains (output_event.getPort ())) {
+                this.queue.Enqueue (output_event);
+            }
+        }
+                
+        public Event fetch ()
+        {
+            Event fetched_event;
+            bool success = this.queue.TryDequeue (out fetched_event);
+            if (success) {
+                return fetched_event;
+            }
+            return null;
+        }
+    }
+}
+

+ 89 - 0
javascript_models/csharp_runtime/ControllerBase.cs

@@ -0,0 +1,89 @@
+using System;
+using System.Collections.Generic;
+
+namespace sccdlib
+{
+    public abstract class ControllerBase
+    {
+        protected ObjectManagerBase object_manager;
+        protected bool done = false;
+        protected List<string> input_ports = new List<string>();
+        protected EventQueue input_queue = new EventQueue();
+
+        protected List<string> output_ports = new List<string>();
+        protected List<IOutputListener> output_listeners = new List<IOutputListener>();
+
+        public ControllerBase ()
+        {
+        }
+
+        protected void addInputPort(string port_name)
+        {
+            this.input_ports.Add(port_name);
+        }
+        
+        protected void addOutputPort(string port_name)
+        {
+            this.output_ports.Add(port_name);
+        }
+
+        public void broadcast(Event new_event)
+        {
+            this.object_manager.broadcast(new_event);
+        }
+        
+        public virtual void start()
+        {
+            this.object_manager.start();
+        }
+    
+        public virtual void stop()
+        {
+        }
+
+        public void outputEvent(Event output_event)
+        {
+            foreach (IOutputListener listener in this.output_listeners)
+            {
+                listener.add(output_event);
+            }
+        }
+        
+        public IOutputListener addOutputListener(string[] ports)
+        {
+            IOutputListener listener = this.createOutputListener(ports);
+            this.output_listeners.Add(listener);
+            return listener;
+        }
+        
+        protected virtual IOutputListener createOutputListener (string[] ports)
+        {
+            return new OutputListener(ports);   
+        }
+        
+        public virtual void addInput(Event input_event, double time_offset = 0.0)
+        {   
+            if ( input_event.getName() == "" )
+                throw new InputException("Input event can't have an empty name.");
+            
+            if ( !this.input_ports.Contains (input_event.getPort()) )
+                throw new InputException("Input port mismatch.");
+            
+            this.input_queue.Add(input_event, time_offset);
+        }
+    
+        public virtual void addEventList(List<Tuple<Event,double>> event_list)
+        {
+            foreach (Tuple<Event,double> event_tuple in event_list)
+            {   
+                this.addInput (event_tuple.Item1, event_tuple.Item2);
+            }
+        }
+        
+        public ObjectManagerBase getObjectManager ()
+        {
+            return this.object_manager;
+        }
+    }
+}
+

+ 41 - 0
javascript_models/csharp_runtime/Event.cs

@@ -0,0 +1,41 @@
+using System;
+using System.Collections.Generic;
+
+namespace sccdlib
+{
+    public class Event
+    {
+        string name = "";
+        string port = "";
+        object[] parameters;
+        
+
+        public Event (string name = "", string port = "", object[] parameters = null)
+        {
+            this.name = name;
+            this.port = port;
+            this.parameters = (parameters == null ? new object[] {} : parameters);
+        }
+
+        public string getName ()
+        {
+            return this.name;
+        }
+
+        public string getPort ()
+        {
+            return this.port;
+        }
+        
+        public object[] getParameters ()
+        {
+            return this.parameters;
+        }
+        
+        public override string ToString()
+        {
+            return string.Format("(event name : {0}; port : {1}; parameters : [{2}])", this.name, this.port, string.Join(", ", this.parameters));
+        }
+    }
+}
+

+ 105 - 0
javascript_models/csharp_runtime/EventQueue.cs

@@ -0,0 +1,105 @@
+using System;
+using System.Collections.Generic;
+
+namespace sccdlib
+{
+    /// <summary>
+    /// Abstracting the event Queue. Currently uses a List to store it's content, but could have better performance when built on a priority queue.
+    /// </summary>
+    public class EventQueue
+    {
+        private class EventQueueEntry
+        {
+            double time_offset;
+            Event e;
+            
+            public EventQueueEntry(Event e, double time_offset)
+            {
+                this.e = e;
+                this.time_offset = time_offset;
+            }
+            
+            public void decreaseTime(double offset)
+            {
+                this.time_offset -= offset;   
+            }
+            
+            public Event getEvent()
+            {
+                return this.e;
+            }
+            
+            public double getTime ()
+            {
+                return this.time_offset;
+            }
+            
+        }
+
+        List<EventQueueEntry> event_list = new List<EventQueueEntry>();
+                
+        public void Add (Event e, double time_offset)
+        {
+            EventQueueEntry entry = new EventQueueEntry(e,time_offset);
+            //We maintain a sorted stable list
+            int insert_index = 0;
+            for (int index = this.event_list.Count-1; index >= 0; index--)
+            {
+                if (this.event_list[index].getTime() <= time_offset)
+                {
+                    insert_index = index + 1;
+                    break;
+                }
+            }
+            this.event_list.Insert(insert_index, entry);
+        }
+
+        public void decreaseTime(double offset)
+        {
+            foreach (EventQueueEntry e in this.event_list)
+                e.decreaseTime(offset);
+        }
+        
+        public bool isEmpty()
+        {
+            return this.event_list.Count == 0;
+        }
+        
+        
+        /// <summary>
+        /// Gets the earliest time.
+        /// </summary>
+        /// <returns>
+        /// The earliest time. Positive infinity if no events are present.
+        /// </returns>
+        public double getEarliestTime ()
+        {
+            if (this.isEmpty())
+            {
+                return double.PositiveInfinity;
+            }
+            else
+            {
+                return this.event_list[0].getTime();
+            }
+        }
+
+        public List<Event> popDueEvents ()
+        {
+            List<Event> result = new List<Event> ();
+            if (this.isEmpty() || this.event_list[0].getTime() > 0.0)
+                //There are no events, or the earliest event isn't due, so we can already return an emtpy result
+                return result;
+
+            int index = 0;
+            while (index < this.event_list.Count && this.event_list[index].getTime() <= 0.0)
+            {
+                result.Add(this.event_list[index].getEvent()); //Add all events that are due (offset less than 0) to the result
+                index++;
+            }
+            this.event_list.RemoveRange(0, result.Count);
+            return result;
+        }
+    }
+}
+

+ 22 - 0
javascript_models/csharp_runtime/GameControllerBase.cs

@@ -0,0 +1,22 @@
+using System;
+using System.Collections.Generic;
+
+namespace sccdlib
+{
+    public class GameControllerBase : ControllerBase
+    {
+        public GameControllerBase ()
+            : base()
+        {        
+        }
+        
+        public void update(double delta)
+        {  
+            this.input_queue.decreaseTime(delta);
+            foreach(Event e in this.input_queue.popDueEvents())
+                this.broadcast (e);
+            this.object_manager.stepAll(delta);
+        }
+    }
+}
+

+ 11 - 0
javascript_models/csharp_runtime/IOutputListener.cs

@@ -0,0 +1,11 @@
+using System;
+
+namespace sccdlib
+{
+    public interface IOutputListener
+    {
+        void add (Event output_event);
+        Event fetch ();
+    }
+}
+

+ 23 - 0
javascript_models/csharp_runtime/InputException.cs

@@ -0,0 +1,23 @@
+using System;
+
+namespace sccdlib
+{
+    public class InputException : RunTimeException
+    {
+        public InputException ()
+        {
+        }
+        
+        public InputException(string message)
+            : base(message)
+        {
+        }
+    
+        public InputException(string message, Exception inner)
+            : base(message, inner)
+        {
+        }
+    }
+  
+}
+

+ 34 - 0
javascript_models/csharp_runtime/InstanceWrapper.cs

@@ -0,0 +1,34 @@
+using System;
+using System.Collections.Generic;
+
+namespace sccdlib
+{
+    public class InstanceWrapper
+    {
+        RuntimeClassBase instance;
+        Dictionary<string,Association> associations = new Dictionary<string, Association>();
+        
+        
+        public InstanceWrapper (RuntimeClassBase instance, List<Association> associations)
+        {
+            this.instance = instance;
+            foreach (var association in associations) {
+                this.associations[association.getName()] = association;   
+            }
+        }
+        
+        public Association getAssociation (string name)
+        {
+            try{
+                return this.associations[name];
+            }catch (KeyNotFoundException) {
+                throw new AssociationReferenceException("Unknown association.");
+            }
+        }
+        
+        public RuntimeClassBase getInstance ()
+        {
+            return this.instance;
+        }
+    }
+}

+ 12 - 0
javascript_models/csharp_runtime/MyClass.cs

@@ -0,0 +1,12 @@
+using System;
+
+namespace sccdlib
+{
+	public class MyClass
+	{
+		public MyClass ()
+		{
+		}
+	}
+}
+

+ 253 - 0
javascript_models/csharp_runtime/ObjectManagerBase.cs

@@ -0,0 +1,253 @@
+using System;
+using System.Collections.Generic;
+using System.Text.RegularExpressions;
+
+namespace sccdlib
+{
+    public abstract class ObjectManagerBase
+    {
+        protected ControllerBase controller;
+        EventQueue events = new EventQueue();
+        Dictionary<RuntimeClassBase,InstanceWrapper> instances_map = new Dictionary<RuntimeClassBase,InstanceWrapper> ();
+        
+        public ObjectManagerBase (ControllerBase controller)
+        {
+            this.controller = controller;
+        }
+       
+        
+        public void addEvent (Event input_event, double time_offset = 0.0)
+        {
+            this.events.Add (input_event, time_offset);
+        }
+        
+        public void broadcast (Event new_event)
+        {
+            foreach (RuntimeClassBase instance in this.instances_map.Keys)
+                instance.addEvent(new_event);
+        }
+        
+        public  double getWaitTime()
+        {
+            //first get waiting time of the object manager's events
+            double smallest_time = this.events.getEarliestTime();
+            //check all the instances
+            foreach (RuntimeClassBase instance in this.instances_map.Keys)
+                smallest_time = Math.Min(smallest_time, instance.getEarliestEventTime());
+            return smallest_time;
+        }
+        
+        public void step (double delta)
+        {
+            this.events.decreaseTime(delta);
+            foreach( Event e in this.events.popDueEvents())
+                this.handleEvent (e);
+        }
+        
+        private void handleEvent (Event handle_event)
+        {
+            string event_name = handle_event.getName ();
+            if (event_name == "narrow_cast") {
+                this.handleNarrowCastEvent(handle_event.getParameters());
+            } else if (event_name == "broad_cast") {
+                this.handleBroadCastEvent(handle_event.getParameters());
+            } else if (event_name == "create_instance") {
+                this.handleCreateEvent(handle_event.getParameters());
+            } else if (event_name == "associate_instance") {
+                this.handleAssociateEvent(handle_event.getParameters());
+            } else if (event_name == "start_instance") {
+                this.handleStartInstanceEvent(handle_event.getParameters());
+            }
+        }
+        
+        public void stepAll (double delta)
+        {
+            this.step(delta);
+            foreach (RuntimeClassBase instance in this.instances_map.Keys)
+                instance.step(delta);
+        }
+    
+        
+        public void start ()
+        {
+            foreach (RuntimeClassBase instance in this.instances_map.Keys)
+                instance.start(); 
+        }
+        
+        /// <summary>
+        /// Processes the association reference.
+        /// </summary>
+        /// <returns>
+        /// The association reference.
+        /// </returns>
+        /// <param name='input_string'>
+        /// Input_string.
+        /// </param>
+        private List<Tuple<string, int>> processAssociationReference (string input_string)
+        {
+            if (input_string.Length == 0)
+                throw new AssociationReferenceException("Empty association reference.");
+            string[] path_string = input_string.Split (new char[] {'/'});
+            Regex regex = new Regex(@"^([a-zA-Z_]\w*)(?:\[(\d+)\])?$");
+            
+            var result = new List<Tuple<string, int>>();
+            
+            foreach (string string_piece in path_string) {
+                Match match = regex.Match (string_piece);
+                if (match.Success ){
+                    string name = match.Groups[1].ToString ();
+                    int index;
+                    if (match.Groups[2].Success)
+                        int.TryParse(match.Groups[2].ToString(), out index);
+                    else
+                        index = -1;
+                    result.Add( new Tuple<string, int>(name,index));
+                }else{
+                    throw new AssociationReferenceException("Invalid entry in association reference.");
+                }   
+            }
+            return result;
+        }
+        
+        /// <summary>
+        /// Gets the instances.
+        /// </summary>
+        /// <returns>
+        /// The instances.
+        /// </returns>
+        /// <param name='source'>
+        /// Source.
+        /// </param>
+        /// <param name='traversal_list'>
+        /// Traversal_list.
+        /// </param>
+        private List<InstanceWrapper> getInstances (RuntimeClassBase source, List<Tuple<string, int>> traversal_list)
+        {
+            var currents = new List<InstanceWrapper> ();
+            currents.Add (this.instances_map [source]);
+            foreach (Tuple<string, int> tuple in traversal_list) {
+                var nexts = new List<InstanceWrapper> ();
+                foreach ( InstanceWrapper current in currents ){
+                    Association association = current.getAssociation (tuple.Item1);   
+                    if (tuple.Item2 >= 0 )
+                        nexts.Add ( association.getInstance(tuple.Item2) );
+                    else if (tuple.Item2 == -1)
+                        nexts.AddRange ( association.getAllInstances() );
+                    else
+                        throw new AssociationReferenceException("Incorrect index in association reference.");
+                }
+                currents = nexts;
+            }
+            return currents;
+        }
+        
+        /// <summary>
+        /// Handles the start instance event.
+        /// </summary>
+        /// <param name='parameters'>
+        /// [0] The instance the event originates from.
+        /// [1] An association reference string targeting the instance to start.
+        /// </param>
+        private void handleStartInstanceEvent (object[] parameters)
+        {
+            if (parameters.Length != 2) {
+                throw new ParameterException ("The start instance event needs 2 parameters.");    
+            } else {
+                RuntimeClassBase source = (RuntimeClassBase) parameters[0];
+                var traversal_list = this.processAssociationReference((string) parameters [1]);
+                
+                foreach( InstanceWrapper i in this.getInstances (source, traversal_list)){
+                    i.getInstance().start();
+                }
+            }
+        }
+        
+        /// <summary>
+        /// Handles the broad cast event.
+        /// </summary>
+        /// <param name='parameters'>
+        /// [0] The event to be broadcasted.
+        /// </param>
+        private void handleBroadCastEvent(object[] parameters)
+        {
+            if (parameters.Length != 1 ) 
+                throw new ParameterException ("The broadcast event needs 1 parameter.");   
+            this.broadcast((Event)parameters[0]); 
+        }
+
+        private void handleCreateEvent (object[] parameters)
+        {
+            if (parameters.Length < 2) {
+                throw new ParameterException ("The create event needs at least 2 parameters.");   
+            } else {
+                RuntimeClassBase source = (RuntimeClassBase)parameters [0];
+                string association_name = (string)parameters [1];
+                Association association = this.instances_map[source].getAssociation (association_name);
+                if (association.allowedToAdd ()){
+                    int constructor_parameters_length = parameters.Length -2;
+                    object[] constructor_parameters = new object[constructor_parameters_length];
+                    Array.Copy(parameters, 2, constructor_parameters, 0, constructor_parameters_length);
+                    InstanceWrapper new_instance_wrapper = this.createInstance(association.getClassName (), constructor_parameters);
+                    association.addInstance (new_instance_wrapper);
+                    source.addEvent(
+                        new Event(name: "instance_created", parameters : new object[] {association_name})
+                    );
+                }else{
+                    source.addEvent (
+                        new Event(name: "instance_creation_error", parameters : new object[] {association_name})    
+                    );
+                }    
+            }
+        }
+        
+                
+        private void handleAssociateEvent (object[] parameters)
+        {
+            if (parameters.Length != 3) {
+                throw new ParameterException ("The associate_instance event needs 3 parameters.");
+            } else {
+                RuntimeClassBase source = (RuntimeClassBase)parameters [0];
+                List<InstanceWrapper> to_copy_list = this.getInstances (source, this.processAssociationReference ((string)parameters [1]));
+                if (to_copy_list.Count != 1)
+                    throw new AssociationReferenceException ("Invalid source association reference.");
+                InstanceWrapper wrapped_to_copy_instance = to_copy_list [0];
+                List<Tuple<string,int>> dest_list = this.processAssociationReference ((string)parameters [2]);
+                if (dest_list.Count == 0)
+                    throw new AssociationReferenceException ("Invalid destination association reference.");
+                Tuple<string,int> last_tuple = dest_list [dest_list.Count - 1];
+                if (last_tuple.Item2 != -1)
+                    throw new AssociationReferenceException ("Last association name in association reference should not be accompanied by an index.");
+                dest_list.RemoveAt (dest_list.Count - 1);
+                foreach (InstanceWrapper i in this.getInstances(source, dest_list)) {
+                    i.getAssociation (last_tuple.Item1).addInstance (wrapped_to_copy_instance);
+                }
+            }
+        }
+            
+        private void handleNarrowCastEvent(object[] parameters)
+        {
+            if (parameters.Length != 3){
+                throw new ParameterException ("The associate_instance event needs 3 parameters.");
+            }else{
+                RuntimeClassBase source = (RuntimeClassBase)parameters [0];
+                Event cast_event = (Event) parameters[2];
+                foreach (InstanceWrapper i in this.getInstances(source, this.processAssociationReference( (string) parameters[1])))
+                    i.getInstance ().addEvent(cast_event);
+            
+            }
+        }   
+        
+        
+        protected abstract InstanceWrapper instantiate(string class_name, object[] construct_params);
+
+            
+        public InstanceWrapper createInstance(string class_name, object[] construct_params)
+        {
+            InstanceWrapper iw = this.instantiate(class_name, construct_params);
+            if (iw != null)
+                this.instances_map[iw.getInstance ()] = iw;
+            return iw;
+        }
+    }
+}
+

+ 34 - 0
javascript_models/csharp_runtime/OutputListener.cs

@@ -0,0 +1,34 @@
+using System;
+using System.Collections.Generic;
+
+namespace sccdlib
+{
+    public class OutputListener : IOutputListener
+    {
+        Queue<Event> queue = new Queue<Event>();
+        List<string> ports = new List<string>();
+        
+        public OutputListener (string[] port_names)
+        {
+            foreach (string port_name in port_names)
+            {
+                this.ports.Add (port_name);
+            }
+        }
+        
+        public void add (Event output_event)
+        {
+            if (this.ports.Count == 0 || this.ports.Contains (output_event.getPort ())) {
+                this.queue.Enqueue (output_event);
+            }
+        }
+                
+        public Event fetch ()
+        {
+            if (this.queue.Count > 0)
+                return this.queue.Dequeue ();
+            return null;
+        }
+    }
+}
+

+ 22 - 0
javascript_models/csharp_runtime/ParameterException.cs

@@ -0,0 +1,22 @@
+using System;
+
+namespace sccdlib
+{
+    public class ParameterException : RunTimeException
+    {
+        public ParameterException ()
+        {
+        }      
+                
+        public ParameterException(string message)
+            : base(message)
+        {
+        }
+    
+        public ParameterException(string message, Exception inner)
+            : base(message, inner)
+        {
+        }
+    }
+}
+

+ 27 - 0
javascript_models/csharp_runtime/Properties/AssemblyInfo.cs

@@ -0,0 +1,27 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+
+// Information about this assembly is defined by the following attributes. 
+// Change them to the values specific to your project.
+
+[assembly: AssemblyTitle("csharp_runtime")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("")]
+[assembly: AssemblyCopyright("gl3nn")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
+// The form "{Major}.{Minor}.*" will automatically update the build and revision,
+// and "{Major}.{Minor}.{Build}.*" will update just the revision.
+
+[assembly: AssemblyVersion("1.0.*")]
+
+// The following attributes are used to specify the signing key for the assembly, 
+// if desired. See the Mono documentation for more information about signing.
+
+//[assembly: AssemblyDelaySign(false)]
+//[assembly: AssemblyKeyFile("")]
+

+ 22 - 0
javascript_models/csharp_runtime/RunTimeException.cs

@@ -0,0 +1,22 @@
+using System;
+
+namespace sccdlib
+{
+    public class RunTimeException : Exception
+    {
+        public RunTimeException ()
+        {
+        }
+        
+        public RunTimeException(string message)
+            : base(message)
+        {
+        }
+    
+        public RunTimeException(string message, Exception inner)
+            : base(message, inner)
+        {
+        }
+    }
+}
+

+ 95 - 0
javascript_models/csharp_runtime/RuntimeClassBase.cs

@@ -0,0 +1,95 @@
+using System;
+using System.Collections.Generic;
+
+namespace sccdlib
+{
+    public abstract class RuntimeClassBase
+    {
+
+        protected bool active = false;
+        protected bool state_changed = false;
+        protected EventQueue events = new EventQueue();
+        protected ControllerBase controller;
+        protected ObjectManagerBase object_manager;
+        protected Dictionary<int,double> timers = null;
+
+        public RuntimeClassBase ()
+        {
+        }
+        
+        public void addEvent (Event input_event, double time_offset = 0.0)
+        {
+            this.events.Add (input_event, time_offset);
+        }
+        
+        
+        public double getEarliestEventTime ()
+        {
+            if (this.timers != null)
+            {
+                double smallest_timer_value = double.PositiveInfinity;
+                foreach (double timer_value in this.timers.Values)
+                {
+                    if (timer_value < smallest_timer_value)
+                        smallest_timer_value = timer_value;
+                }
+                return Math.Min(this.events.getEarliestTime(), smallest_timer_value); 
+            }
+            return this.events.getEarliestTime();   
+        }
+
+        /// <summary>
+        /// Execute statechart
+        /// </summary>
+        /// <param name='delta'>
+        /// Time passed since last step.
+        /// </param>
+        public void step(double delta)
+        {
+            if (!this.active)
+                return;
+
+            this.events.decreaseTime(delta);
+
+            if (this.timers != null && this.timers.Count > 0)
+            {
+                var next_timers = new Dictionary<int,double>();
+                foreach(KeyValuePair<int,double> pair in this.timers)
+                {
+                    double new_time = pair.Value - delta;
+                    if (new_time <= 0.0)
+                        this.addEvent (new Event("_" + pair.Key + "after"), new_time);
+                    else
+                        next_timers[pair.Key] = new_time;
+                }
+                this.timers = next_timers;
+            }
+
+            this.microstep();
+            while (this.state_changed)
+                this.microstep();
+        }
+        
+        private void microstep ()
+        {
+            List<Event> due = this.events.popDueEvents();
+            if (due.Count == 0) {
+                this.transition ();   
+            } else {
+                foreach (Event e in due)
+                {
+                    this.transition(e);
+                }
+            }
+        }
+        
+        protected abstract void transition (Event e = null);
+        
+        public virtual void start ()
+        {
+            this.active = true;
+        }
+        
+    }
+}
+

+ 146 - 0
javascript_models/csharp_runtime/ThreadsControllerBase.cs

@@ -0,0 +1,146 @@
+using System;
+using System.Threading;
+using System.Collections.Generic;
+
+namespace sccdlib
+{
+    public class ThreadsControllerBase : ControllerBase
+    {
+        bool stop_thread = false;
+        bool keep_running;
+        Thread thread = null;
+        Mutex input_mutex = new Mutex(false);
+        Mutex stop_thread_mutex = new Mutex(false);
+        AutoResetEvent wait_handle = new AutoResetEvent(false);
+        DateTime last_recorded_time = DateTime.UtcNow;
+        
+        public ThreadsControllerBase (bool keep_running = true)
+            : base()
+        {          
+            this.keep_running = keep_running;
+            this.thread = new Thread (new ThreadStart (this.run));
+        }
+        
+        private void handleInput(double delta)
+        {
+            this.input_mutex.WaitOne(-1);
+            this.input_queue.decreaseTime(delta);
+            foreach(Event e in this.input_queue.popDueEvents())
+                this.broadcast (e);
+            this.input_mutex.ReleaseMutex();
+        }
+        
+        public override void start()
+        {
+            this.thread.Start ();
+        }
+    
+        public override void stop()
+        {
+            this.stop_thread_mutex.WaitOne(-1);
+            this.stop_thread = true;
+            this.stop_thread_mutex.ReleaseMutex ();
+            this.wait_handle.Set();
+        }
+        
+        
+        private double getWaitTime ()
+        {
+            this.input_mutex.WaitOne (-1);
+            double wait_time = Math.Min (this.object_manager.getWaitTime (), this.input_queue.getEarliestTime ());
+            this.input_mutex.ReleaseMutex ();
+    
+            if (double.IsPositiveInfinity (wait_time)) {
+                if (this.done) {
+                    this.done = false;
+                } else {
+                    this.done = true;
+                    return 0.0;
+                }
+            }
+            return wait_time;
+        }
+    
+        private void handleWaiting ()
+        {
+            double wait_time = this.getWaitTime ();
+            if (wait_time <= 0.0)
+                return;
+            if (double.IsPositiveInfinity(wait_time))
+            {
+                if (this.keep_running)
+                {
+                    this.wait_handle.WaitOne(-1); //Wait until signal
+                }
+                else
+                {
+                    this.stop_thread_mutex.WaitOne(-1);
+                    this.stop_thread = true;
+                    this.stop_thread_mutex.ReleaseMutex();
+                }
+            }
+            else if (wait_time != 0.0)
+            {
+                //Calculate how much wait time is left.
+                double actual_wait_time = (wait_time - DateTime.UtcNow.Subtract(this.last_recorded_time).TotalSeconds); //In seconds and double
+                if (actual_wait_time > 0.0)
+                {
+                    this.wait_handle.Reset();
+                    this.wait_handle.WaitOne((int)Math.Ceiling(actual_wait_time * 1000)); //Convert to seconds and int round up
+                }
+            }
+        }
+    
+        private void run()
+        {
+            this.last_recorded_time = DateTime.UtcNow;
+            base.start ();
+            DateTime previous_recorded_time;
+            double last_iteration_time = 0.0;
+
+            while (true)
+            {
+                this.handleInput(last_iteration_time);
+                //Compute the new state based on internal events
+                this.object_manager.stepAll(last_iteration_time);
+
+                this.handleWaiting();
+                
+                this.stop_thread_mutex.WaitOne (-1);
+                if (this.stop_thread) 
+                    break;
+                this.stop_thread_mutex.ReleaseMutex ();
+                
+                previous_recorded_time = this.last_recorded_time;
+                this.last_recorded_time = DateTime.UtcNow;
+                last_iteration_time = this.last_recorded_time.Subtract(previous_recorded_time).TotalSeconds;
+            }
+        }
+    
+        public void join()
+        {
+            this.thread.Join ();
+        }
+    
+        public override void addInput(Event input_event, double time_offset = 0.0)
+        {
+            this.input_mutex.WaitOne (-1);
+            base.addInput (input_event, time_offset); //TODO Add time to offset that has already passed, so that next subtraction evens it out? Also Gameloop then!
+            this.input_mutex.ReleaseMutex ();
+            this.wait_handle.Set();
+        }
+    
+        public override void addEventList(List<Tuple<Event,double>> event_list)
+        {
+            this.input_mutex.WaitOne (-1);
+            base.addEventList (event_list);
+            this.input_mutex.ReleaseMutex ();
+        }
+        
+        protected override IOutputListener createOutputListener (string[] ports)
+        {
+            return new ConcurrentOutputListener(ports);   
+        }
+    }
+}
+

+ 55 - 0
javascript_models/csharp_runtime/sccdlib.csproj

@@ -0,0 +1,55 @@
+<?xml version="1.0" encoding="utf-8"?>
+<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
+  <PropertyGroup>
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
+    <ProductVersion>10.0.0</ProductVersion>
+    <SchemaVersion>2.0</SchemaVersion>
+    <ProjectGuid>{B4A57EE1-3C90-4B43-9ACA-43821CB35EA0}</ProjectGuid>
+    <OutputType>Library</OutputType>
+    <RootNamespace>sccdlib</RootNamespace>
+    <AssemblyName>sccdlib</AssemblyName>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
+    <DebugSymbols>true</DebugSymbols>
+    <DebugType>full</DebugType>
+    <Optimize>false</Optimize>
+    <OutputPath>bin\Debug</OutputPath>
+    <DefineConstants>DEBUG;</DefineConstants>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <ConsolePause>false</ConsolePause>
+  </PropertyGroup>
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
+    <DebugType>none</DebugType>
+    <Optimize>true</Optimize>
+    <OutputPath>bin\Release</OutputPath>
+    <ErrorReport>prompt</ErrorReport>
+    <WarningLevel>4</WarningLevel>
+    <ConsolePause>false</ConsolePause>
+  </PropertyGroup>
+  <ItemGroup>
+    <Reference Include="System" />
+  </ItemGroup>
+  <ItemGroup>
+    <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="Event.cs" />
+    <Compile Include="ObjectManagerBase.cs" />
+    <Compile Include="InstanceWrapper.cs" />
+    <Compile Include="Association.cs" />
+    <Compile Include="OutputListener.cs" />
+    <Compile Include="ControllerBase.cs" />
+    <Compile Include="GameControllerBase.cs" />
+    <Compile Include="RuntimeClassBase.cs" />
+    <Compile Include="AssociationException.cs" />
+    <Compile Include="IOutputListener.cs" />
+    <Compile Include="ConcurrentOutputListener.cs" />
+    <Compile Include="AssociationReferenceException.cs" />
+    <Compile Include="RunTimeException.cs" />
+    <Compile Include="ParameterException.cs" />
+    <Compile Include="EventQueue.cs" />
+    <Compile Include="ThreadsControllerBase.cs" />
+    <Compile Include="InputException.cs" />
+  </ItemGroup>
+  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
+</Project>

+ 50 - 0
javascript_models/csharp_runtime/sccdlib.sln

@@ -0,0 +1,50 @@
+
+Microsoft Visual Studio Solution File, Format Version 11.00
+# Visual Studio 2010
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "sccdlib", "sccdlib.csproj", "{B4A57EE1-3C90-4B43-9ACA-43821CB35EA0}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{B4A57EE1-3C90-4B43-9ACA-43821CB35EA0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{B4A57EE1-3C90-4B43-9ACA-43821CB35EA0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{B4A57EE1-3C90-4B43-9ACA-43821CB35EA0}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{B4A57EE1-3C90-4B43-9ACA-43821CB35EA0}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(MonoDevelopProperties) = preSolution
+		StartupItem = sccdlib.csproj
+		Policies = $0
+		$0.TextStylePolicy = $1
+		$1.inheritsSet = VisualStudio
+		$1.inheritsScope = text/plain
+		$1.scope = text/x-csharp
+		$0.CSharpFormattingPolicy = $2
+		$2.IndentSwitchBody = True
+		$2.AnonymousMethodBraceStyle = NextLine
+		$2.PropertyBraceStyle = NextLine
+		$2.PropertyGetBraceStyle = NextLine
+		$2.PropertySetBraceStyle = NextLine
+		$2.EventBraceStyle = NextLine
+		$2.EventAddBraceStyle = NextLine
+		$2.EventRemoveBraceStyle = NextLine
+		$2.StatementBraceStyle = NextLine
+		$2.ElseNewLinePlacement = NewLine
+		$2.CatchNewLinePlacement = NewLine
+		$2.FinallyNewLinePlacement = NewLine
+		$2.WhileNewLinePlacement = DoNotCare
+		$2.ArrayInitializerWrapping = DoNotChange
+		$2.ArrayInitializerBraceStyle = NextLine
+		$2.BeforeMethodDeclarationParentheses = False
+		$2.BeforeMethodCallParentheses = False
+		$2.BeforeConstructorDeclarationParentheses = False
+		$2.BeforeDelegateDeclarationParentheses = False
+		$2.NewParentheses = False
+		$2.SpacesBeforeBrackets = False
+		$2.inheritsSet = Mono
+		$2.inheritsScope = text/x-csharp
+		$2.scope = text/x-csharp
+	EndGlobalSection
+EndGlobal

+ 0 - 0
javascript_models/csharp_sccd_compiler/Action.cs


Some files were not shown because too many files changed in this diff