Commit 6bf6f3ba authored by Jérome Perrin's avatar Jérome Perrin

update prototype to call manpy

parent f2e973fb
import json
import subprocess
from pprint import pformat
from flask import Flask, jsonify, redirect, url_for from flask import Flask, jsonify, redirect, url_for
from flask import request from flask import request
from crossdomain import crossdomain
from util import deunicodeData
app = Flask(__name__) app = Flask(__name__)
global data global data
...@@ -21,8 +23,8 @@ def addModel(): ...@@ -21,8 +23,8 @@ def addModel():
def main(*args): def main(*args):
app.run(debug=True) app.run(debug=True)
@app.route("/someTest", methods=["POST", "OPTIONS"]) @app.route("/someTest", methods=["POST", "OPTIONS"])
@crossdomain(origin='*')
def someTest(): def someTest():
app.logger.debug('someTest') app.logger.debug('someTest')
app.logger.debug(request) app.logger.debug(request)
...@@ -33,7 +35,6 @@ def someTest(): ...@@ -33,7 +35,6 @@ def someTest():
return jsonify(request.json) return jsonify(request.json)
@app.route("/setModel", methods=["POST", "OPTIONS"]) @app.route("/setModel", methods=["POST", "OPTIONS"])
@crossdomain(origin='*')
def setModel(): def setModel():
app.logger.debug('setModel') app.logger.debug('setModel')
data['model'] = request.json data['model'] = request.json
...@@ -42,14 +43,12 @@ def setModel(): ...@@ -42,14 +43,12 @@ def setModel():
return "ok" return "ok"
@app.route("/updateModel", methods=["POST", "OPTIONS"]) @app.route("/updateModel", methods=["POST", "OPTIONS"])
@crossdomain(origin='*')
def updateModel(): def updateModel():
app.logger.debug('updateModel') app.logger.debug('updateModel')
data['model'] = request.json data['model'] = request.json
return "ok" return "ok"
@app.route("/setSimulationParameters", methods=["POST", "OPTIONS"]) @app.route("/setSimulationParameters", methods=["POST", "OPTIONS"])
@crossdomain(origin='*')
def setSimulationParameters(): def setSimulationParameters():
app.logger.debug('setSimulationParameters') app.logger.debug('setSimulationParameters')
parameter_dict = request.json parameter_dict = request.json
...@@ -81,11 +80,25 @@ def _simulate(): ...@@ -81,11 +80,25 @@ def _simulate():
data['model']["throughput"] = throughput data['model']["throughput"] = throughput
@app.route("/getModel", methods=["GET", "OPTIONS"]) @app.route("/getModel", methods=["GET", "OPTIONS"])
@crossdomain(origin='*')
def getModel(): def getModel():
app.logger.debug('getModel') app.logger.debug('getModel')
_simulate() _simulate()
return jsonify(data['model']) return jsonify(data['model'])
@app.route("/runSimulation", methods=["POST", "OPTIONS"])
def runSimulation():
parameter_dict = request.json['json']
app.logger.debug("running with:\n%s" % (pformat(parameter_dict,)))
if 0:
p = subprocess.Popen(['./bin/dream_simulation', '-', '-'], shell=True, bufsize=8192,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
p.stdin.write(json.dumps(parameter_dict))
app.logger.debug(p.stdout.read())
from dream.simulation.LineGenerationJSON import main
return jsonify(json.loads(main(input_data=json.dumps(parameter_dict))))
if __name__ == "__main__": if __name__ == "__main__":
main() main()
...@@ -76,7 +76,6 @@ li { margin: 3px; ...@@ -76,7 +76,6 @@ li { margin: 3px;
font-size:13px; font-size:13px;
} }
/* demo elements */ /* demo elements */
.menu,#render, #explanation { .menu,#render, #explanation {
...@@ -182,16 +181,28 @@ path, ._jsPlumb_endpoint { cursor:pointer; } ...@@ -182,16 +181,28 @@ path, ._jsPlumb_endpoint { cursor:pointer; }
border-radius: 10px; border-radius: 10px;
} }
#tools { #tools {
position: absolute; position: absolute;
width: 200px; width: 200px;
height: 500px; height: 400px;
border: 2px solid; border: 2px solid;
margin-top: 20px; margin-top: 20px;
margin-left: 35px; margin-left: 35px;
border-radius: 10px; border-radius: 10px;
} }
#simulation_controls {
position: absolute;
width: 200px;
margin-top: 550px;
margin-left: 35px;
font-size:13px;
height: 300px;
border: 2px solid;
border-radius: 10px;
}
.tool { .tool {
border: 1px dotted gray; border: 1px dotted gray;
/*margin-top: 20px; /*margin-top: 20px;
......
...@@ -4,18 +4,33 @@ ...@@ -4,18 +4,33 @@
<title>jsPlumb 1.4.0 - flowchart connectors demonstration - jQuery</title> <title>jsPlumb 1.4.0 - flowchart connectors demonstration - jQuery</title>
<link rel="stylesheet" href="css/demo-new.css"> <link rel="stylesheet" href="css/demo-new.css">
<link rel="stylesheet" href="css/flowchartDemo.css"> <link rel="stylesheet" href="css/flowchartDemo.css">
<link rel="stylesheet" href="css/jquery-ui.css"> <link rel="stylesheet" href="css/jquery-ui.css">
</head> </head>
<body data-demo-id="flowchartConnectorsDemo" data-library="jquery"> <body data-demo-id="flowchartConnectorsDemo" data-library="jquery">
<div id="headerWrapper"><div id="header"></div></div> <div id="headerWrapper"><div id="header"></div></div>
<div id="tools">
Tools <div id="tools">
</div> Tools
</div>
<div id="simulation_controls">
Simulation Parameters
<div title="Configure">
<form>
<fieldset id="general-fieldset">
</fieldset>
<!-- <button id="run_simulation">Run Simulation</button> -->
<a id="run_simulation">Run Simulation</a>
</form>
</div>
</div>
<div id="main"> <div id="main">
<div id="render"></div> <div id="render"></div>
</div> </div>
<div id="sidebar">
<div id="sidebar">
<table> <table>
<tr> <tr>
<td>Input</td> <td>Input</td>
...@@ -29,6 +44,8 @@ ...@@ -29,6 +44,8 @@
<textarea rows="20" cols="47" id="json_result" style="align:right"> <textarea rows="20" cols="47" id="json_result" style="align:right">
</textarea></td> </textarea></td>
</table> </table>
<!--
<div id="explanation"> <div id="explanation">
<p>This is a demonstration of Flowchart combined with simulation.</p> <p>This is a demonstration of Flowchart combined with simulation.</p>
<p>Drag not available people to the box "Available". If there is enough workers, a green path will be displayed on the Flowchart.</p> <p>Drag not available people to the box "Available". If there is enough workers, a green path will be displayed on the Flowchart.</p>
...@@ -36,10 +53,12 @@ ...@@ -36,10 +53,12 @@
<p>For now, there is no real simulation, only some little code to make this demo working</p> <p>For now, there is no real simulation, only some little code to make this demo working</p>
<p>This demonstration uses jsPlumb 1.4.0, jQuery 1.8.1 and jQuery UI 1.8.23.</p> <p>This demonstration uses jsPlumb 1.4.0, jQuery 1.8.1 and jQuery UI 1.8.23.</p>
</div> </div>
-->
</div> </div>
<!-- DEP --> <!-- DEP -->
<script type="text/javascript" src="lib/underscore-min.js"></script> <script type="text/javascript" src="lib/underscore-min.js"></script>
<script type="text/javascript" src="lib/jquery-1.8.1-min.js"></script> <!-- <script type="text/javascript" src="lib/jquery-1.8.1-min.js"></script> -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.js"></script>
<script type="text/javascript" src="lib/jquery-ui-1.8.23-min.js"></script> <script type="text/javascript" src="lib/jquery-ui-1.8.23-min.js"></script>
<script type="text/javascript" src="lib/jquery.ui.touch-punch.min.js"></script> <script type="text/javascript" src="lib/jquery.ui.touch-punch.min.js"></script>
<script type="text/javascript" src="lib/md5.js"></script> <script type="text/javascript" src="lib/md5.js"></script>
...@@ -82,7 +101,7 @@ ...@@ -82,7 +101,7 @@
<!-- /JS --> <!-- /JS -->
<div id="dialog-form" title="Change Througput"> <div id="dialog-form" title="Configure">
<p class="validateTips">All form fields are required.</p> <p class="validateTips">All form fields are required.</p>
<form> <form>
...@@ -93,8 +112,8 @@ ...@@ -93,8 +112,8 @@
<!-- demo code --> <!-- demo code -->
<script src="src/dream.js"></script> <script src="src/dream.js"></script>
<script src="src/jsonPlumb.js"></script> <script src="src/jsonPlumb.js"></script>
<script src="src/dream_launcher.js"></script> <script src="src/dream_launcher.js"></script>
</body> </body>
......
(function (scope, $, jsPlumb, console, _) { (function (scope, $, jsPlumb, console, _) {
"use strict"; "use strict";
var dream = function (configuration) { var dream = function (configuration) {
var that = {}, priv = {}; var that = {}, priv = {}, general = {};
priv.onError = function(error) { priv.onError = function(error) {
console.log("Error", error); console.log("Error", error);
...@@ -35,9 +35,10 @@ ...@@ -35,9 +35,10 @@
priv.displayTool = function() { priv.displayTool = function() {
var render_element = $("[id=tools]"); var render_element = $("[id=tools]");
_.each(_.pairs(configuration), function(value, key, list) { _.each(_.pairs(configuration), function(value, key, list) {
render_element.append('<div id="' + value[0] + '" class="tool">' + if (value[0] !== 'Dream-Configuration') { // XXX
value[0].split('-')[1] + render_element.append('<div id="' + value[0] + '" class="tool">' +
"<ul/></div>"); value[0].split('-')[1] + "<ul/></div>");
};
}); });
}; };
...@@ -45,10 +46,30 @@ ...@@ -45,10 +46,30 @@
priv.plumb.removeElement(element_id); priv.plumb.removeElement(element_id);
}; };
priv.initDialog = function(title, element_id) { priv.initDialog = function() {
$( "#dialog-form" ).dialog({autoOpen: false}); $( "#dialog-form" ).dialog({autoOpen: false});
}; };
priv.initGeneralProperties = function() {
var fieldset = $("#general-fieldset"),
previous_data = priv.plumb.getData()['general'],
previous_value = "",
prefix = "General-";
fieldset.children().remove()
$.each(configuration['Dream-Configuration']['property_list'],
function(idx, property){
if (property._class === "Dream.Property") {
previous_value = previous_data[property.id] || "";
if (previous_value.length > 0) {
previous_value = ' value="' + previous_value + '"';
}
fieldset.append("<label>" + property.id + "</label>" +
'<input type="text" name="' + prefix + property.id + '"' +
previous_value + ' id="' + prefix + property.id + '"' +
' class="text ui-widget-content ui-corner-all"/>');
}});
};
priv.prepareDialogForElement = function(title, element_id) { priv.prepareDialogForElement = function(title, element_id) {
// code to allow changing values on connections. For now we assume // code to allow changing values on connections. For now we assume
// that it is throughput. But we will need more generic code // that it is throughput. But we will need more generic code
...@@ -67,11 +88,9 @@ ...@@ -67,11 +88,9 @@
$("#dialog-fieldset").children().remove() $("#dialog-fieldset").children().remove()
var element_id_prefix = element_id.split("_")[0]; var element_id_prefix = element_id.split("_")[0];
var property_list = configuration[element_id_prefix].property_list || []; var property_list = configuration[element_id_prefix].property_list || [];
console.log("getData on element_id", element_id);
var previous_data = priv.plumb.getData()["element"]; var previous_data = priv.plumb.getData()["element"];
previous_data = previous_data[element_id] || {}; previous_data = previous_data[element_id] || {};
previous_data = previous_data.data || {}; previous_data = previous_data.data || {};
console.log("previous_data", previous_data);
var previous_value; var previous_value;
var renderField = function(property_list, previous_data, prefix) { var renderField = function(property_list, previous_data, prefix) {
if (prefix === undefined) { if (prefix === undefined) {
...@@ -113,7 +132,6 @@ ...@@ -113,7 +132,6 @@
$( this ).dialog( "close" ); $( this ).dialog( "close" );
}, },
Delete: function() { Delete: function() {
console.log("Going to delete $(this)", $(this));
if (confirm("Are you sure you want to delete " + element_id + " ?")) { if (confirm("Are you sure you want to delete " + element_id + " ?")) {
priv.removeElement(element_id); priv.removeElement(element_id);
} }
...@@ -175,6 +193,16 @@ ...@@ -175,6 +193,16 @@
priv.plumb.start(); priv.plumb.start();
priv.displayTool(); priv.displayTool();
priv.initDialog(); priv.initDialog();
priv.initGeneralProperties();
}
});
Object.defineProperty(that, "initGeneralProperties", {
configurable: false,
enumerable: false,
writable: false,
value: function () {
priv.initGeneralProperties();
} }
}); });
...@@ -196,6 +224,60 @@ ...@@ -196,6 +224,60 @@
} }
}); });
function formatForManpy(data) {
var manpy_dict = {}, coreObject = [];
$.each(data['element'], function(idx, element) {
var clone_element = {};
/* clone the element and put content of 'data' at the top level. */
$.each(element, function(k, v) {
if (k == 'data') {
$.each(v, function(kk, vv) {
clone_element[kk] = vv;
});
} else {
clone_element[k] = v;
}
});
coreObject.push( clone_element );
});
manpy_dict['coreObject'] = coreObject;
manpy_dict['modelResource'] = [];
manpy_dict['general'] = data['general'];
return manpy_dict;
}
that.setGeneralProperties = function(properties) {
priv.plumb.setGeneralProperties(properties);
}
that.getData = function() { return priv.plumb.getData() };
that.runSimulation = function(callback) {
// handle Dream.General properties (in another function maybe ?)
var prefix = "General-", properties = {}, prefixed_property_id;
$.each(configuration['Dream-Configuration']['property_list'],
function(idx, property){
if (property._class === "Dream.Property") {
prefixed_property_id = prefix + property.id;
properties[property.id] = $("#" + prefixed_property_id).val();
}
});
priv.plumb.setGeneralProperties(properties);
var model = formatForManpy(priv.plumb.getData());
$.ajax(
'/runSimulation', {
data: JSON.stringify({json: model}),
contentType: 'application/json',
type: 'POST',
success: function(data, textStatus, jqXHR){
callback(data);
}
});
};
return that; return that;
}; };
var DreamNamespace = (function () { var DreamNamespace = (function () {
...@@ -227,4 +309,4 @@ ...@@ -227,4 +309,4 @@
value: DreamNamespace value: DreamNamespace
}); });
}(window, jQuery, jsPlumb, console, _)); }(window, jQuery, jsPlumb, console, _));
\ No newline at end of file
...@@ -8,6 +8,7 @@ ...@@ -8,6 +8,7 @@
var element_id; var element_id;
var id_container = {}; // to allow generating next ids, like Machine_1, Machine_2, etc var id_container = {}; // to allow generating next ids, like Machine_1, Machine_2, etc
var property_container = {entity: {id: "entity", type:"string", _class: "Dream.Property"}, var property_container = {entity: {id: "entity", type:"string", _class: "Dream.Property"},
// XXX is it possible not to repeat id ?
mean: {id: "mean", type: "string", _class: "Dream.Property"}, mean: {id: "mean", type: "string", _class: "Dream.Property"},
distributionType: {id: "distributionType", type: "string", _class: "Dream.Property"}, distributionType: {id: "distributionType", type: "string", _class: "Dream.Property"},
stdev: {id: "stdev", type: "string", _class: "Dream.Property"}, stdev: {id: "stdev", type: "string", _class: "Dream.Property"},
...@@ -19,6 +20,9 @@ ...@@ -19,6 +20,9 @@
repairman: {id: "repairman", type: "string", _class: "Dream.Property"}, repairman: {id: "repairman", type: "string", _class: "Dream.Property"},
isDummy: {id: "isDummy", type: "string", _class: "Dream.Property"}, isDummy: {id: "isDummy", type: "string", _class: "Dream.Property"},
capacity: {id: "capacity", type: "string", _class: "Dream.Property"}, capacity: {id: "capacity", type: "string", _class: "Dream.Property"},
numberOfReplications: {id: "numberOfReplications", type: "string", _class: "Dream.Property"},
maxSimTime: {id: "maxSimTime", type: "string", _class: "Dream.Property"},
confidenceLevel: {id: "confidenceLevel", type: "string", _class: "Dream.Property"},
}; };
property_container["interarrivalTime"] = {id:"interarrivalTime", property_container["interarrivalTime"] = {id:"interarrivalTime",
property_list: [property_container["mean"], property_container["distributionType"]], property_list: [property_container["mean"], property_container["distributionType"]],
...@@ -36,31 +40,41 @@ ...@@ -36,31 +40,41 @@
_class: "Dream.PropertyList"}; _class: "Dream.PropertyList"};
var configuration = { var configuration = {
"Dream-Source": { anchor: {RightMiddle: {}}, "Dream-Source": { anchor: {RightMiddle: {}}, /* TODO: make anchor not a configuration option and allow to connect from everywhere */
property_list: [property_container["interarrivalTime"], property_container["entity"]], property_list: [property_container["interarrivalTime"], property_container["entity"]],
_class: 'Dream.Source',
}, },
"Dream-Machine": { anchor: {RightMiddle: {}, LeftMiddle: {}, TopCenter: {}, BottomCenter: {}}, "Dream-Machine": { anchor: {RightMiddle: {}, LeftMiddle: {}, TopCenter: {}, BottomCenter: {}},
property_list: [property_container["processingTime"], property_container["failures"]], property_list: [property_container["processingTime"], property_container["failures"]],
_class: 'Dream.Machine',
}, },
"Dream-Queue": { anchor: {RightMiddle: {}, LeftMiddle: {}}, "Dream-Queue": { anchor: {RightMiddle: {}, LeftMiddle: {}},
property_list: [property_container["capacity"], property_container["isDummy"]], property_list: [property_container["capacity"], property_container["isDummy"]],
_class: 'Dream.Queue',
}, },
"Dream-Exit": { anchor: {LeftMiddle: {}}}, "Dream-Exit": { anchor: {LeftMiddle: {},}, _class: 'Dream.Exit' },
"Dream-Repairman": { anchor: {TopCenter: {}, BottomCenter: {}}, "Dream-Repairman": { anchor: {TopCenter: {}, BottomCenter: {}},
property_list: [property_container["capacity"]], property_list: [property_container["capacity"]],
_class: 'Dream.Repairman',
}, },
"Dream-Configuration": { property_list: [ property_container["numberOfReplications"],
property_container["maxSimTime"],
property_container["confidenceLevel"], ],
_class: 'Dream.Repairman', },
} }
dream_instance = DREAM.newDream(configuration) dream_instance = DREAM.newDream(configuration)
dream_instance.start(); dream_instance.start();
$( ".tool" ).draggable({ opacity: 0.7, helper: "clone", $( ".tool" ).draggable({ opacity: 0.7, helper: "clone",
stop: function(tool) { stop: function(tool) {
var box_top, box_left; var box_top, box_left, _class;
box_top = tool.clientY; box_top = tool.clientY;
box_left = tool.clientX; box_left = tool.clientX;
id_container[tool.target.id] = (id_container[tool.target.id] || 0) + 1 id_container[tool.target.id] = (id_container[tool.target.id] || 0) + 1;
_class = tool.target.id.replace('-', '.'); // XXX - vs .
dream_instance.newElement({id : tool.target.id + "_" + id_container[tool.target.id], dream_instance.newElement({id : tool.target.id + "_" + id_container[tool.target.id],
coordinate: {y: box_top, x: box_left}, coordinate: {y: box_top, x: box_left},
class: tool.target.id, _class: _class,
}); });
window_id += 1; window_id += 1;
}, },
...@@ -72,13 +86,11 @@ ...@@ -72,13 +86,11 @@
if (response !== undefined && response.data !== undefined) { if (response !== undefined && response.data !== undefined) {
// Add all elements // Add all elements
_.each(response.data.element, function(value, key, list) { _.each(response.data.element, function(value, key, list) {
console.log("value", value);
var element_id = value.id; var element_id = value.id;
var preference_data = response.data.preference[element_id] || {}; var preference_data = response.data.preference !== undefined ? response.data.preference[element_id] : {};
_.each(_.pairs(preference_data), function(preference_value, preference_key, preference_list) { _.each(_.pairs(preference_data), function(preference_value, preference_key, preference_list) {
value[preference_value[0]] = preference_value[1]; value[preference_value[0]] = preference_value[1];
}); });
console.log("going to add newElement", value);
dream_instance.newElement(value); dream_instance.newElement(value);
dream_instance.updateElementData(element_id, {data: value.data || {}}); dream_instance.updateElementData(element_id, {data: value.data || {}});
}); });
...@@ -89,26 +101,42 @@ ...@@ -89,26 +101,42 @@
splitted_element_id = element_id.split("_"); splitted_element_id = element_id.split("_");
prefix = splitted_element_id[0]; prefix = splitted_element_id[0];
suffix = splitted_element_id[1]; suffix = splitted_element_id[1];
console.log("suffix", suffix);
id_container[prefix] = Math.max((id_container[prefix] || 0), parseInt(suffix, 10)); id_container[prefix] = Math.max((id_container[prefix] || 0), parseInt(suffix, 10));
console.log("id_container", id_container);
if (successor_list.length > 0) { if (successor_list.length > 0) {
_.each(successor_list, function(successor_value, successor_key, list) { _.each(successor_list, function(successor_value, successor_key, list) {
dream_instance.connect(value.id, successor_value); dream_instance.connect(value.id, successor_value);
}); });
} }
}); });
dream_instance.setGeneralProperties(response.data.general);
dream_instance.initGeneralProperties(); // XXX
$("#json_output").text(JSON.stringify(dream_instance.getData(), undefined, " "));
} }
// once the data is read, we can subscribe to every changes // once the data is read, we can subscribe to every changes
$.subscribe("Dream.Gui.onDataChange", function(event, data) { $.subscribe("Dream.Gui.onDataChange", function(event, data) {
console.log("onDataChange, data", data); console.log("onDataChange, data", data);
$("#json_output")[0].value = JSON.stringify(data, undefined, " "); $("#json_output").text(JSON.stringify(data, undefined, " "));
jio.put({_id: "dream_demo", data: data}, function(err, response) { jio.put({_id: "dream_demo", data: data}, function(err, response) {
console.log("jio put:", response);} console.log("jio put:", response);}
); );
}); });
}); });
$("#run_simulation").button().click(
function(e){
dream_instance.runSimulation(
function(data) {
$("#json_result").text(JSON.stringify(data, undefined, " "));
$.each(data.coreObject, function(idx, obj){
var e = $("#" + obj.id);
/* attach something to each corresponding core object */
// e.tooltip(JSON.stringify(obj['results'], undefined, " "));
})
});
e.preventDefault();
return false;
});
}) })
})(jQuery, _); })(jQuery, _);
...@@ -82,6 +82,7 @@ ...@@ -82,6 +82,7 @@
jsPlumb.bind("connectionDetached", function(info, originalEvent) { jsPlumb.bind("connectionDetached", function(info, originalEvent) {
updateConnectionData(info.connection, true); updateConnectionData(info.connection, true);
}); });
priv.onDataChange();
priv.draggable(); priv.draggable();
}; };
...@@ -90,7 +91,6 @@ ...@@ -90,7 +91,6 @@
var coordinate = preference.coordinate || {}; var coordinate = preference.coordinate || {};
coordinate.x = x; coordinate.x = x;
coordinate.y = y; coordinate.y = y;
console.log("jsonPlumb, updateElementCoordinate, preference", priv.preference_container);
preference["coordinate"] = coordinate; preference["coordinate"] = coordinate;
priv.preference_container[element_id] = preference; priv.preference_container[element_id] = preference;
priv.onDataChange(); priv.onDataChange();
...@@ -109,7 +109,7 @@ ...@@ -109,7 +109,7 @@
}; };
priv.addElementToContainer = function(element) { priv.addElementToContainer = function(element) {
// Now update the container of elements // Now update the container of elements
var element_data = {_class: element.class, var element_data = {_class: element._class,
id: element.id, id: element.id,
name: element.id, name: element.id,
}; };
...@@ -122,7 +122,9 @@ ...@@ -122,7 +122,9 @@
}; };
priv.getData = function() { priv.getData = function() {
return {"element": priv.element_container, "preference": priv.preference_container}; return { "element": priv.element_container,
"preference": priv.preference_container,
"general": priv.general_container };
}; };
priv.removeElement = function(element_id) { priv.removeElement = function(element_id) {
...@@ -150,6 +152,7 @@ ...@@ -150,6 +152,7 @@
value: function () { value: function () {
priv.element_container = {}; priv.element_container = {};
priv.preference_container = {}; priv.preference_container = {};
priv.general_container = {};
priv.initJsPlumb(); priv.initJsPlumb();
} }
}); });
...@@ -178,11 +181,20 @@ ...@@ -178,11 +181,20 @@
enumerable: false, enumerable: false,
writable: false, writable: false,
value: function (source_id, target_id) { value: function (source_id, target_id) {
console.log("jsonPlumb.connect", source_id, target_id);
jsPlumb.connect({source: source_id, target: target_id}); jsPlumb.connect({source: source_id, target: target_id});
} }
}); });
Object.defineProperty(that, "setGeneralProperties", {
configurable: false,
enumerable: false,
writable: false,
value: function (properties) { // XXX or k, v ?
priv.general_container = properties;
priv.onDataChange();
},
});
Object.defineProperty(that, "newElement", { Object.defineProperty(that, "newElement", {
configurable: false, configurable: false,
enumerable: false, enumerable: false,
...@@ -218,7 +230,7 @@ ...@@ -218,7 +230,7 @@
var color = "#00f"; var color = "#00f";
var gradient_color = "#09098e"; var gradient_color = "#09098e";
// Different endpoint color for Repairman // Different endpoint color for Repairman
if (element.class === "Dream.Repairman") { if (element._class === "Dream.Repairman") {
color = "rgb(189,11,11)"; color = "rgb(189,11,11)";
gradient_color = "rgb(255,0,0)"; gradient_color = "rgb(255,0,0)";
}; };
...@@ -241,7 +253,6 @@ ...@@ -241,7 +253,6 @@
_.each(_.pairs(option.anchor), function(value, key, list) { _.each(_.pairs(option.anchor), function(value, key, list) {
var anchor = value[0], var anchor = value[0],
endpoint_configuration = value[1]; endpoint_configuration = value[1];
console.log("jsonPlub, addEntPoint", element.id, anchor, endpoint);
jsPlumb.addEndpoint(element.id, { anchor: anchor }, endpoint); jsPlumb.addEndpoint(element.id, { anchor: anchor }, endpoint);
}) })
priv.addElementToContainer(element); priv.addElementToContainer(element);
...@@ -280,4 +291,4 @@ ...@@ -280,4 +291,4 @@
value: JsonPlumbNamespace value: JsonPlumbNamespace
}); });
}(window, jQuery, jsPlumb, console, _)); }(window, jQuery, jsPlumb, console, _));
\ No newline at end of file
...@@ -186,7 +186,6 @@ def createObjects(): ...@@ -186,7 +186,6 @@ def createObjects():
#defines the topology (predecessors and successors for all the objects) #defines the topology (predecessors and successors for all the objects)
def setTopology(): def setTopology():
#loop through all the objects #loop through all the objects
for core_object in G.ObjList: for core_object in G.ObjList:
next=[] next=[]
...@@ -258,29 +257,32 @@ def activateObjects(): ...@@ -258,29 +257,32 @@ def activateObjects():
pass pass
#the main script that is ran #the main script that is ran
def main(argv=[]): def main(argv=[], input_data=None):
argv = argv or sys.argv[1:] argv = argv or sys.argv[1:]
#create an empty list to store all the objects in #create an empty list to store all the objects in
G.ObjList=[] G.ObjList=[]
# user passes the topology filename as first argument to the program if input_data is None:
filename = argv[0] # user passes the topology filename as first argument to the program
try: filename = argv[0]
G.JSONFile=open(filename, "r") try:
except IOError: G.JSONFile=open(filename, "r")
print "%s could not be open" % filename except IOError:
return "ERROR" print "%s could not be open" % filename
return "ERROR"
G.InputData=G.JSONFile.read()
else:
G.InputData = input_data
start=time.time() #start counting execution time start=time.time() #start counting execution time
#read the input from the JSON file and create the line #read the input from the JSON file and create the line
G.InputData=G.JSONFile.read()
G.JSONData=json.loads(G.InputData) G.JSONData=json.loads(G.InputData)
readGeneralInput() readGeneralInput()
createObjects() createObjects()
setTopology() setTopology()
#run the experiment (replications) #run the experiment (replications)
for i in range(G.numberOfReplications): for i in range(G.numberOfReplications):
print "start run number "+str(i+1) print "start run number "+str(i+1)
...@@ -351,6 +353,8 @@ def main(argv=[]): ...@@ -351,6 +353,8 @@ def main(argv=[]):
G.outputFile.save("output.xls") G.outputFile.save("output.xls")
print "execution time="+str(time.time()-start) print "execution time="+str(time.time()-start)
if input_data:
return outputJSONString
if __name__ == '__main__': if __name__ == '__main__':
main() main()
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment