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 request
from crossdomain import crossdomain
from util import deunicodeData
app = Flask(__name__)
global data
......@@ -21,8 +23,8 @@ def addModel():
def main(*args):
app.run(debug=True)
@app.route("/someTest", methods=["POST", "OPTIONS"])
@crossdomain(origin='*')
def someTest():
app.logger.debug('someTest')
app.logger.debug(request)
......@@ -33,7 +35,6 @@ def someTest():
return jsonify(request.json)
@app.route("/setModel", methods=["POST", "OPTIONS"])
@crossdomain(origin='*')
def setModel():
app.logger.debug('setModel')
data['model'] = request.json
......@@ -42,14 +43,12 @@ def setModel():
return "ok"
@app.route("/updateModel", methods=["POST", "OPTIONS"])
@crossdomain(origin='*')
def updateModel():
app.logger.debug('updateModel')
data['model'] = request.json
return "ok"
@app.route("/setSimulationParameters", methods=["POST", "OPTIONS"])
@crossdomain(origin='*')
def setSimulationParameters():
app.logger.debug('setSimulationParameters')
parameter_dict = request.json
......@@ -81,11 +80,25 @@ def _simulate():
data['model']["throughput"] = throughput
@app.route("/getModel", methods=["GET", "OPTIONS"])
@crossdomain(origin='*')
def getModel():
app.logger.debug('getModel')
_simulate()
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__":
main()
......@@ -76,7 +76,6 @@ li { margin: 3px;
font-size:13px;
}
/* demo elements */
.menu,#render, #explanation {
......@@ -182,16 +181,28 @@ path, ._jsPlumb_endpoint { cursor:pointer; }
border-radius: 10px;
}
#tools {
position: absolute;
width: 200px;
height: 500px;
height: 400px;
border: 2px solid;
margin-top: 20px;
margin-left: 35px;
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 {
border: 1px dotted gray;
/*margin-top: 20px;
......
......@@ -4,18 +4,33 @@
<title>jsPlumb 1.4.0 - flowchart connectors demonstration - jQuery</title>
<link rel="stylesheet" href="css/demo-new.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>
<body data-demo-id="flowchartConnectorsDemo" data-library="jquery">
<div id="headerWrapper"><div id="header"></div></div>
<div id="tools">
Tools
</div>
<div id="headerWrapper"><div id="header"></div></div>
<div id="tools">
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="render"></div>
</div>
<div id="sidebar">
<div id="render"></div>
</div>
<div id="sidebar">
<table>
<tr>
<td>Input</td>
......@@ -29,6 +44,8 @@
<textarea rows="20" cols="47" id="json_result" style="align:right">
</textarea></td>
</table>
<!--
<div id="explanation">
<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>
......@@ -36,10 +53,12 @@
<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>
</div>
-->
</div>
<!-- DEP -->
<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.touch-punch.min.js"></script>
<script type="text/javascript" src="lib/md5.js"></script>
......@@ -82,7 +101,7 @@
<!-- /JS -->
<div id="dialog-form" title="Change Througput">
<div id="dialog-form" title="Configure">
<p class="validateTips">All form fields are required.</p>
<form>
......@@ -93,8 +112,8 @@
<!-- demo code -->
<script src="src/dream.js"></script>
<!-- demo code -->
<script src="src/dream.js"></script>
<script src="src/jsonPlumb.js"></script>
<script src="src/dream_launcher.js"></script>
</body>
......
(function (scope, $, jsPlumb, console, _) {
"use strict";
var dream = function (configuration) {
var that = {}, priv = {};
var that = {}, priv = {}, general = {};
priv.onError = function(error) {
console.log("Error", error);
......@@ -35,9 +35,10 @@
priv.displayTool = function() {
var render_element = $("[id=tools]");
_.each(_.pairs(configuration), function(value, key, list) {
render_element.append('<div id="' + value[0] + '" class="tool">' +
value[0].split('-')[1] +
"<ul/></div>");
if (value[0] !== 'Dream-Configuration') { // XXX
render_element.append('<div id="' + value[0] + '" class="tool">' +
value[0].split('-')[1] + "<ul/></div>");
};
});
};
......@@ -45,10 +46,30 @@
priv.plumb.removeElement(element_id);
};
priv.initDialog = function(title, element_id) {
priv.initDialog = function() {
$( "#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) {
// code to allow changing values on connections. For now we assume
// that it is throughput. But we will need more generic code
......@@ -67,11 +88,9 @@
$("#dialog-fieldset").children().remove()
var element_id_prefix = element_id.split("_")[0];
var property_list = configuration[element_id_prefix].property_list || [];
console.log("getData on element_id", element_id);
var previous_data = priv.plumb.getData()["element"];
previous_data = previous_data[element_id] || {};
previous_data = previous_data.data || {};
console.log("previous_data", previous_data);
var previous_value;
var renderField = function(property_list, previous_data, prefix) {
if (prefix === undefined) {
......@@ -113,7 +132,6 @@
$( this ).dialog( "close" );
},
Delete: function() {
console.log("Going to delete $(this)", $(this));
if (confirm("Are you sure you want to delete " + element_id + " ?")) {
priv.removeElement(element_id);
}
......@@ -175,6 +193,16 @@
priv.plumb.start();
priv.displayTool();
priv.initDialog();
priv.initGeneralProperties();
}
});
Object.defineProperty(that, "initGeneralProperties", {
configurable: false,
enumerable: false,
writable: false,
value: function () {
priv.initGeneralProperties();
}
});
......@@ -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;
};
var DreamNamespace = (function () {
......@@ -227,4 +309,4 @@
value: DreamNamespace
});
}(window, jQuery, jsPlumb, console, _));
\ No newline at end of file
}(window, jQuery, jsPlumb, console, _));
......@@ -8,6 +8,7 @@
var element_id;
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"},
// XXX is it possible not to repeat id ?
mean: {id: "mean", type: "string", _class: "Dream.Property"},
distributionType: {id: "distributionType", type: "string", _class: "Dream.Property"},
stdev: {id: "stdev", type: "string", _class: "Dream.Property"},
......@@ -19,6 +20,9 @@
repairman: {id: "repairman", type: "string", _class: "Dream.Property"},
isDummy: {id: "isDummy", 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_list: [property_container["mean"], property_container["distributionType"]],
......@@ -36,31 +40,41 @@
_class: "Dream.PropertyList"};
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"]],
_class: 'Dream.Source',
},
"Dream-Machine": { anchor: {RightMiddle: {}, LeftMiddle: {}, TopCenter: {}, BottomCenter: {}},
property_list: [property_container["processingTime"], property_container["failures"]],
_class: 'Dream.Machine',
},
"Dream-Queue": { anchor: {RightMiddle: {}, LeftMiddle: {}},
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: {}},
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.start();
$( ".tool" ).draggable({ opacity: 0.7, helper: "clone",
stop: function(tool) {
var box_top, box_left;
var box_top, box_left, _class;
box_top = tool.clientY;
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],
coordinate: {y: box_top, x: box_left},
class: tool.target.id,
_class: _class,
});
window_id += 1;
},
......@@ -72,13 +86,11 @@
if (response !== undefined && response.data !== undefined) {
// Add all elements
_.each(response.data.element, function(value, key, list) {
console.log("value", value);
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) {
value[preference_value[0]] = preference_value[1];
});
console.log("going to add newElement", value);
dream_instance.newElement(value);
dream_instance.updateElementData(element_id, {data: value.data || {}});
});
......@@ -89,26 +101,42 @@
splitted_element_id = element_id.split("_");
prefix = splitted_element_id[0];
suffix = splitted_element_id[1];
console.log("suffix", suffix);
id_container[prefix] = Math.max((id_container[prefix] || 0), parseInt(suffix, 10));
console.log("id_container", id_container);
if (successor_list.length > 0) {
_.each(successor_list, function(successor_value, successor_key, list) {
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
$.subscribe("Dream.Gui.onDataChange", function(event, 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) {
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, _);
......@@ -82,6 +82,7 @@
jsPlumb.bind("connectionDetached", function(info, originalEvent) {
updateConnectionData(info.connection, true);
});
priv.onDataChange();
priv.draggable();
};
......@@ -90,7 +91,6 @@
var coordinate = preference.coordinate || {};
coordinate.x = x;
coordinate.y = y;
console.log("jsonPlumb, updateElementCoordinate, preference", priv.preference_container);
preference["coordinate"] = coordinate;
priv.preference_container[element_id] = preference;
priv.onDataChange();
......@@ -109,7 +109,7 @@
};
priv.addElementToContainer = function(element) {
// Now update the container of elements
var element_data = {_class: element.class,
var element_data = {_class: element._class,
id: element.id,
name: element.id,
};
......@@ -122,7 +122,9 @@
};
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) {
......@@ -150,6 +152,7 @@
value: function () {
priv.element_container = {};
priv.preference_container = {};
priv.general_container = {};
priv.initJsPlumb();
}
});
......@@ -178,11 +181,20 @@
enumerable: false,
writable: false,
value: function (source_id, target_id) {
console.log("jsonPlumb.connect", source_id, 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", {
configurable: false,
enumerable: false,
......@@ -218,7 +230,7 @@
var color = "#00f";
var gradient_color = "#09098e";
// Different endpoint color for Repairman
if (element.class === "Dream.Repairman") {
if (element._class === "Dream.Repairman") {
color = "rgb(189,11,11)";
gradient_color = "rgb(255,0,0)";
};
......@@ -241,7 +253,6 @@
_.each(_.pairs(option.anchor), function(value, key, list) {
var anchor = value[0],
endpoint_configuration = value[1];
console.log("jsonPlub, addEntPoint", element.id, anchor, endpoint);
jsPlumb.addEndpoint(element.id, { anchor: anchor }, endpoint);
})
priv.addElementToContainer(element);
......@@ -280,4 +291,4 @@
value: JsonPlumbNamespace
});
}(window, jQuery, jsPlumb, console, _));
\ No newline at end of file
}(window, jQuery, jsPlumb, console, _));
......@@ -186,7 +186,6 @@ def createObjects():
#defines the topology (predecessors and successors for all the objects)
def setTopology():
#loop through all the objects
for core_object in G.ObjList:
next=[]
......@@ -258,29 +257,32 @@ def activateObjects():
pass
#the main script that is ran
def main(argv=[]):
def main(argv=[], input_data=None):
argv = argv or sys.argv[1:]
#create an empty list to store all the objects in
G.ObjList=[]
# user passes the topology filename as first argument to the program
filename = argv[0]
try:
G.JSONFile=open(filename, "r")
except IOError:
print "%s could not be open" % filename
return "ERROR"
if input_data is None:
# user passes the topology filename as first argument to the program
filename = argv[0]
try:
G.JSONFile=open(filename, "r")
except IOError:
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
#read the input from the JSON file and create the line
G.InputData=G.JSONFile.read()
G.JSONData=json.loads(G.InputData)
readGeneralInput()
createObjects()
setTopology()
#run the experiment (replications)
for i in range(G.numberOfReplications):
print "start run number "+str(i+1)
......@@ -351,6 +353,8 @@ def main(argv=[]):
G.outputFile.save("output.xls")
print "execution time="+str(time.time()-start)
if input_data:
return outputJSONString
if __name__ == '__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