exporttoppdevs.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. {
  2. 'interfaces': [{'method':'POST', 'url=':'/exportmtoppdevs'}],
  3. 'csworker':
  4. function(resp, method, uri, reqData, wcontext) {
  5. var actions = [__wHttpReq('GET', '/current.model?wid=' + wcontext.__aswid)];
  6. _do.chain(actions) (
  7. function(asdata) {
  8. var writeActions = [_fspp.mkdirs('./exported_to_pypdevs/')];
  9. _do.chain(writeActions) (
  10. function() {
  11. var file_contents = '',
  12. as = _utils.jsonp(asdata['data']),
  13. type_map = {},
  14. type_map_keys = {},
  15. incoming = {},
  16. outgoing = {};
  17. file_contents += 'import sys\n'
  18. file_contents += 'sys.path.append("../../pypdevs/src/")\n\n'
  19. file_contents += 'from DEVS import *\n'
  20. file_contents += 'from infinity import INFINITY\n'
  21. file_contents += 'from util import *\n\n'
  22. for (var key in as.nodes) {
  23. var node = as.nodes[key];
  24. if (!(node['$type'] in type_map)) {
  25. type_map[node['$type']] = [];
  26. type_map_keys[node['$type']] = [];
  27. }
  28. type_map[node['$type']].push(node);
  29. type_map_keys[node['$type']].push(key);
  30. node['$key'] = key;
  31. }
  32. function safe_add(l, el) {
  33. if (l.indexOf(el) == -1) {
  34. l.push(el);
  35. }
  36. }
  37. function calc_in_out_rel(rel_type) {
  38. for (var idx in type_map_keys[rel_type]) {
  39. key = type_map_keys[rel_type][idx];
  40. incoming[key] = [];
  41. outgoing[key] = [];
  42. for (var e_key in as.edges) {
  43. var e = as.edges[e_key];
  44. if (e['dest'] == key) {
  45. safe_add(incoming[key], e['src'])
  46. if (!(e['src'] in outgoing)) {
  47. outgoing[e['src']] = [];
  48. }
  49. safe_add(outgoing[e['src']], key);
  50. }
  51. if (e['src'] == key) {
  52. safe_add(outgoing[key], e['dest'])
  53. if (!(e['dest'] in incoming)) {
  54. incoming[e['dest']] = [];
  55. }
  56. safe_add(incoming[e['dest']], key);
  57. }
  58. }
  59. }
  60. }
  61. calc_in_out_rel('/Formalisms/ParallelDEVS/ParallelDEVS/states');
  62. calc_in_out_rel('/Formalisms/ParallelDEVS/ParallelDEVS/ports');
  63. calc_in_out_rel('/Formalisms/ParallelDEVS/ParallelDEVS/channel');
  64. calc_in_out_rel('/Formalisms/ParallelDEVS/ParallelDEVS/statedef');
  65. calc_in_out_rel('/Formalisms/ParallelDEVS/ParallelDEVS/submodels');
  66. calc_in_out_rel('/Formalisms/ParallelDEVS/ParallelDEVS/ExternalTransition');
  67. calc_in_out_rel('/Formalisms/ParallelDEVS/ParallelDEVS/InternalTransition');
  68. calc_in_out_rel('/Formalisms/ParallelDEVS/ParallelDEVS/ConfluentTransition');
  69. for (var key in type_map['/Formalisms/ParallelDEVS/ParallelDEVS/StateDefinition']) {
  70. var node = type_map['/Formalisms/ParallelDEVS/ParallelDEVS/StateDefinition'][key],
  71. list_of_params = ['name=""'].concat(node['parameters']['value'].map(function(el) {return el['name'] + '=None'})),
  72. list_of_param_names = ['name'].concat(node['parameters']['value'].map(function(el) {return el['name']})),
  73. list_of_attrs = [['name', '']].concat(node['attributes']['value'].map(function(el) {return [el['name'], el['default']]}));
  74. file_contents += 'class ' + node['name']['value'] + ':\n';
  75. file_contents += '\tdef __init__(self, ' + list_of_params.join(', ') + '):\n';
  76. file_contents += list_of_attrs.map(function(el) {return '\t\tself.' + el[0] + ' = ' + (list_of_param_names.indexOf(el[0]) != -1 ? el[0] : el[1])}).join('\n') + "\n";
  77. file_contents += node['__init__']['value'].split('\n').map(function(line) {return '\t\t' + line}).join('\n');
  78. file_contents += '\n\n';
  79. }
  80. for (var key in type_map['/Formalisms/ParallelDEVS/ParallelDEVS/Event']) {
  81. var node = type_map['/Formalisms/ParallelDEVS/ParallelDEVS/Event'][key],
  82. list_of_params = (node['parameters']['value'].map(function(el) {return el['name'] + '=None'})),
  83. list_of_param_names = (node['parameters']['value'].map(function(el) {return el['name']})),
  84. list_of_attrs = (node['attributes']['value'].map(function(el) {return [el['name'], el['default']]}));
  85. file_contents += 'class ' + node['name']['value'] + ':\n';
  86. file_contents += '\tdef __init__(self, ' + list_of_params.join(', ') + '):\n';
  87. file_contents += list_of_attrs.map(function(el) {return '\t\tself.' + el[0] + ' = ' + (list_of_param_names.indexOf(el[0]) != -1 ? el[0] : el[1])}).join('\n') + "\n";
  88. file_contents += node['__init__']['value'].split('\n').map(function(line) {return '\t\t' + line}).join('\n');
  89. file_contents += '\n\n';
  90. file_contents += '\tdef __str__(self):\n';
  91. file_contents += '\t\treturn "' + node['name']['value'] + '(" + ' + list_of_attrs.map(function(el) {return 'str(self.' + el[0] + ')'}).join(' + ", " + ') + ' + ")"';
  92. file_contents += '\n\n';
  93. }
  94. for (var idx in type_map['/Formalisms/ParallelDEVS/ParallelDEVS/AtomicDEVS']) {
  95. var node = type_map['/Formalisms/ParallelDEVS/ParallelDEVS/AtomicDEVS'][idx],
  96. list_of_params = (node['parameters']['value'].map(function(el) {return el['name'] + '=None'})),
  97. list_of_param_names = (node['parameters']['value'].map(function(el) {return el['name']})),
  98. list_of_attrs = (node['attributes']['value'].map(function(el) {return [el['name'], el['default']]}));
  99. file_contents += 'class ' + node['name']['value'] + '(AtomicDEVS):\n';
  100. file_contents += '\tdef __init__(' + (['self', 'name="' + node['name']['value'] + '"'].concat(list_of_params).join(', ')) + '):\n';
  101. file_contents += '\t\tAtomicDEVS.__init__(self, name)\n';
  102. file_contents += list_of_attrs.map(function(el) {return '\t\tself.' + el[0] + ' = ' + (list_of_param_names.indexOf(el[0]) != -1 ? el[0] + ' if ' + el[0] + ' is not None else ' + el[1] : el[1])}).join('\n');
  103. file_contents += '\n';
  104. key = type_map_keys['/Formalisms/ParallelDEVS/ParallelDEVS/AtomicDEVS'][idx];
  105. statedef = as.nodes[outgoing[outgoing[key].filter(function(el) {return as.nodes[el]['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/statedef'})[0]][0]];
  106. states = outgoing[key].filter(function(el) {return as.nodes[el]['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/states'}).map(function(statesid) {return outgoing[statesid][0]}).map(function(sid) {return as.nodes[sid]});
  107. defstate = states.filter(function(el) {return el['initial']['value']})[0]
  108. list_of_assigns = ['name="' + defstate['name']['value'] + '"'].concat(statedef['initial_binding']['value'].map(function(el) {return el['name'] + '=' + el['val']}))
  109. file_contents += '\t\tself.state = ' + statedef['name']['value'] + '(' + list_of_assigns.join(', ') + ')\n';
  110. file_contents += node['__init__']['value'].split('\n').map(function(line) {return '\t\t' + line}).join('\n') + "\n";
  111. ports = outgoing[key].filter(function(el) {return as.nodes[el]['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/ports'}).map(function(portsid) {return outgoing[portsid][0]}).map(function(pid) {return as.nodes[pid]});
  112. file_contents += '\t\tself.my_ports = {' + ports.map(function(el) {return '"' + el['name']['value'] + '": ' + (el['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/OutputPort' ? 'self.addOutPort("' : 'self.addInPort("') + el['name']['value'] + '")'}).join(', ') + '}\n\n'
  113. file_contents += '\tdef timeAdvance(self):\n'
  114. file_contents += states.map(function(s) {return '\t\tif self.state.name == "' + s['name']['value'] + '":\n' + s['time_advance']['value'].split('\n').map(function(line) {return '\t\t\t' + line}).join('\n')}).join('\n')
  115. file_contents += '\n\n';
  116. file_contents += '\tdef outputFnc(self):\n'
  117. file_contents += '\t\tdef subfunc(self):\n'
  118. file_contents += states.map(function(s) {return '\t\t\tif self.state.name == "' + s['name']['value'] + '":\n' + (s['output']['value'] == '' ? ['\t\t\t\treturn {}'] : s['output']['value'].split('\n').map(function(line) {return '\t\t\t\t' + line}).join('\n'))}).join('\n') + "\n";
  119. file_contents += '\t\treturn {self.my_ports[k]: v for k, v in subfunc(self).iteritems()}\n';
  120. file_contents += '\n\n';
  121. file_contents += '\tdef intTransition(self):\n'
  122. var content = false;
  123. for (var sidx in states) {
  124. s = states[sidx];
  125. if (outgoing[s['$key']]) {
  126. internals = outgoing[s['$key']].filter(function(el) {return as.nodes[el]['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/InternalTransition'}).map(function(tid) {return as.nodes[tid]});
  127. for (var iidx in internals) {
  128. content = true;
  129. internal = internals[iidx];
  130. var target = as.nodes[outgoing[internal['$key']][0]],
  131. cond_name = 'cond_int_' + s['name']['value'] + '_to_' + target['name']['value'],
  132. action_name = 'action_int_' + s['name']['value'] + '_to_' + target['name']['value'];
  133. file_contents += '\t\t\def ' + cond_name + '():\n';
  134. file_contents += internal['condition']['value'] == '' ? '\t\t\treturn True' : internal['condition']['value'].split('\n').map(function(line) {return '\t\t\t' + line}).join('\n');
  135. file_contents += '\n\t\t\def ' + action_name + '():\n';
  136. file_contents += internal['action']['value'] == '' ? '\t\t\treturn {}' : internal['action']['value'].split('\n').map(function(line) {return '\t\t\t' + line}).join('\n');
  137. file_contents += '\n\t\tif self.state.name == "' + s['name']['value'] + '" and ' + cond_name + '():\n';
  138. file_contents += '\t\t\treturn ' + statedef['name']['value'] + '(name="' + target['name']['value'] + '", **' + action_name + '())\n\n';
  139. }
  140. }
  141. }
  142. if (!content) {
  143. file_contents += '\t\treturn AtomicDEVS.intTransition(self)\n';
  144. } else {
  145. file_contents += '\t\telse:\n';
  146. file_contents += '\t\t\treturn AtomicDEVS.intTransition(self)\n';
  147. }
  148. file_contents += '\n';
  149. file_contents += '\tdef extTransition(self, my_inputs):\n'
  150. file_contents += '\t\tinputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}\n'
  151. content = false;
  152. for (var sidx in states) {
  153. s = states[sidx];
  154. if (outgoing[s['$key']]) {
  155. externals = outgoing[s['$key']].filter(function(el) {return as.nodes[el]['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/ExternalTransition'}).map(function(tid) {return as.nodes[tid]});
  156. for (var iidx in externals) {
  157. content = true;
  158. external = externals[iidx];
  159. var target = as.nodes[outgoing[external['$key']][0]],
  160. cond_name = 'cond_ext_' + s['name']['value'] + '_to_' + target['name']['value'],
  161. action_name = 'action_ext_' + s['name']['value'] + '_to_' + target['name']['value'];
  162. file_contents += '\t\t\def ' + cond_name + '():\n';
  163. file_contents += external['condition']['value'] == '' ? '\t\t\treturn True' : external['condition']['value'].split('\n').map(function(line) {return '\t\t\t' + line}).join('\n');
  164. file_contents += '\n\t\t\def ' + action_name + '():\n';
  165. file_contents += external['action']['value'] == '' ? '\t\t\treturn {}' : external['action']['value'].split('\n').map(function(line) {return '\t\t\t' + line}).join('\n');
  166. file_contents += '\n\t\tif self.state.name == "' + s['name']['value'] + '" and ' + cond_name + '():\n';
  167. file_contents += '\t\t\treturn ' + statedef['name']['value'] + '(name="' + target['name']['value'] + '", **' + action_name + '())\n\n';
  168. }
  169. }
  170. }
  171. if (!content) {
  172. file_contents += '\t\treturn AtomicDEVS.extTransition(self, my_inputs)\n';
  173. } else {
  174. file_contents += '\t\telse:\n';
  175. file_contents += '\t\t\treturn AtomicDEVS.extTransition(self, my_inputs)\n';
  176. }
  177. file_contents += '\n'
  178. file_contents += '\tdef confTransition(self, my_inputs):\n'
  179. file_contents += '\t\tinputs = {k.getPortName(): v for k, v in my_inputs.iteritems()}\n'
  180. content = false;
  181. for (var sidx in states) {
  182. s = states[sidx];
  183. confluents = outgoing[s['$key']].filter(function(el) {return as.nodes[el]['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/ConfluentTransition'}).map(function(tid) {return as.nodes[tid]});
  184. for (var iidx in confluents) {
  185. content = true;
  186. confluent = confluents[iidx];
  187. var target = as.nodes[outgoing[confluent['$key']][0]],
  188. cond_name = 'cond_conf_' + s['name']['value'] + '_to_' + target['name']['value'],
  189. action_name = 'action_conf_' + s['name']['value'] + '_to_' + target['name']['value'];
  190. file_contents += '\t\t\def ' + cond_name + '():\n';
  191. file_contents += confluent['condition']['value'] == '' ? '\t\t\treturn True' : confluent['condition']['value'].split('\n').map(function(line) {return '\t\t\t' + line}).join('\n');
  192. file_contents += '\n\t\t\def ' + action_name + '():\n';
  193. file_contents += confluent['action']['value'] == '' ? '\t\t\treturn {}' : confluent['action']['value'].split('\n').map(function(line) {return '\t\t\t' + line}).join('\n');
  194. file_contents += '\n\t\tif self.state.name == "' + s['name']['value'] + '" and ' + cond_name + '():\n';
  195. file_contents += '\t\t\treturn ' + statedef['name']['value'] + '(name="' + target['name']['value'] + '", **' + action_name + '())\n\n';
  196. }
  197. }
  198. if (!content) {
  199. file_contents += '\t\treturn AtomicDEVS.confTransition(self, my_inputs)\n';
  200. } else {
  201. file_contents += '\t\telse:\n';
  202. file_contents += '\t\t\treturn AtomicDEVS.confTransition(self, my_inputs)\n';
  203. }
  204. file_contents += '\n'
  205. }
  206. for (var idx in type_map['/Formalisms/ParallelDEVS/ParallelDEVS/CoupledDEVS']) {
  207. var node = type_map['/Formalisms/ParallelDEVS/ParallelDEVS/CoupledDEVS'][idx],
  208. list_of_params = (node['parameters']['value'].map(function(el) {return el['name'] + '=None'})),
  209. list_of_param_names = (node['parameters']['value'].map(function(el) {return el['name']})),
  210. list_of_attrs = (node['attributes']['value'].map(function(el) {return [el['name'], el['default']]}));
  211. file_contents += 'class ' + node['name']['value'] + '(CoupledDEVS):\n';
  212. file_contents += '\tdef __init__(' + (['self', 'name="' + node['name']['value'] + '"'].concat(list_of_params).join(', ')) + '):\n';
  213. file_contents += '\t\tCoupledDEVS.__init__(self, name)\n';
  214. file_contents += list_of_attrs.map(function(el) {return '\t\tself.' + el[0] + ' = ' + (list_of_param_names.indexOf(el[0]) != -1 ? el[0] : el[1])}).join('\n') + "\n";
  215. file_contents += node['__init__']['value'].split('\n').map(function(line) {return '\t\t' + line}).join('\n') + "\n";
  216. key = type_map_keys['/Formalisms/ParallelDEVS/ParallelDEVS/CoupledDEVS'][idx];
  217. ports = outgoing[key].filter(function(el) {return as.nodes[el]['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/ports'}).map(function(portsid) {return outgoing[portsid][0]}).map(function(pid) {return as.nodes[pid]});
  218. file_contents += '\t\tself.my_ports = {' + ports.map(function(el) {return '"' + el['name']['value'] + '": ' + (el['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/OutputPort' ? 'self.addOutPort("' : 'self.addInPort("') + el['name']['value'] + '")'}).join(', ') + '}\n'
  219. file_contents += '\t\tself.submodels = {}\n';
  220. submodels = outgoing[key].filter(function(el) {return as.nodes[el]['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/submodels'}).map(function(submodelsid) {return outgoing[submodelsid][0]}).map(function(mid) {return as.nodes[mid]});
  221. file_contents += submodels.map(function(m) {return '\t\tself.submodels["' + m['name']['value'] + '"] = self.addSubModel(' + m['devs_type']['value'] + '(' + ['name="' + m['name']['value'] + '"'].concat(m['parameter_binding']['value'].map(function(pb) {return pb['name'] + '=' + pb['val']})).join(', ') + '))'}).join('\n');
  222. file_contents += '\n\n';
  223. myportkeys = ports.map(function(port) {return port['$key']});
  224. port_to_m = {};
  225. m_to_ports = {};
  226. m_to_ports[key] = ports;
  227. ports.forEach(function(p) {port_to_m[p['$key']] = node});
  228. for (var skey in submodels) {
  229. var m = submodels[skey];
  230. m_to_ports[m['$key']] = [];
  231. ports = outgoing[m['$key']].filter(function(el) {return as.nodes[el]['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/ports'}).map(function(portsid) {return outgoing[portsid][0]}).map(function(pid) {return as.nodes[pid]});
  232. ports.forEach(function(p) {port_to_m[p['$key']] = m; m_to_ports[m['$key']].push(p);});
  233. }
  234. for (var mkey in m_to_ports) {
  235. for (var pidx in m_to_ports[mkey]) {
  236. var p = m_to_ports[mkey][pidx],
  237. pkey = p['$key'];
  238. if (pkey in outgoing) {
  239. var conns = outgoing[pkey].filter(function(el) {return as.nodes[el]['$type'] == '/Formalisms/ParallelDEVS/ParallelDEVS/channel'}).map(function(channelid) {return as.nodes[channelid]})
  240. for (var cidx in conns) {
  241. var conn = conns[cidx],
  242. target = as.nodes[outgoing[conn['$key']][0]],
  243. transfname = 'transfer_' + as.nodes[mkey]['name']['value'] + '_' + as.nodes[pkey]['name']['value'] + '_to_' + target['name']['value'],
  244. fromportstr = (mkey == key ? 'self' : 'self.submodels["' + as.nodes[mkey]['name']['value'] + '"]') + '.my_ports["' + as.nodes[pkey]['name']['value'] + '"]',
  245. toportstr = (port_to_m[target['$key']]['$key'] == key ? 'self' : 'self.submodels["' + port_to_m[target['$key']]['name']['value'] + '"]') + '.my_ports["' + target['name']['value'] + '"]';
  246. if (conn['transfer_function']['value'] != '') {
  247. file_contents += '\t\tdef ' + transfname + '(event):\n';
  248. file_contents += conn['transfer_function']['value'].split('\n').map(function(line) {return '\t\t\t' + line}).join('\n');
  249. file_contents += '\n\n';
  250. file_contents += '\t\tself.connectPorts(' + fromportstr + ', ' + toportstr + ', ' + transfname + ')\n\n';
  251. } else {
  252. file_contents += '\t\tself.connectPorts(' + fromportstr + ', ' + toportstr + ')\n';
  253. }
  254. }
  255. }
  256. }
  257. }
  258. file_contents += '\n';
  259. }
  260. _fs.writeFileSync('./exported_to_pypdevs/model.py', file_contents);
  261. file_contents = 'import sys\n';
  262. file_contents += 'sys.path.append("../../pypdevs/src/")\n\n';
  263. file_contents += 'from DEVS import *\n';
  264. file_contents += 'from model import *\n';
  265. file_contents += 'from python_runtime.statecharts_core import Event\n';
  266. file_contents += 'from sccd import Controller\n\n';
  267. file_contents += 'def termination_condition(time, model, transitioned):\n';
  268. file_contents += '\ttime = time[0]\n';
  269. file_contents += type_map['/Formalisms/ParallelDEVS/ParallelDEVS/Simulation'][0]['end_condition']['value'].split('\n').map(function(line) {return '\t' + line}).join('\n') + '\n';
  270. _fs.writeFileSync('./exported_to_pypdevs/experiment.py', file_contents);
  271. __postMessage({'statusCode': 200,
  272. 'respIndex': resp});
  273. },
  274. function(writeErr) {__postInternalErrorMsg(resp, writeErr);}
  275. );
  276. },
  277. function(err) {__postInternalErrorMsg(resp, err);}
  278. )
  279. },
  280. 'asworker':
  281. function(resp, method, uri, reqData, wcontext)
  282. {
  283. __postMessage(
  284. {'statusCode': 200,
  285. 'respIndex': resp});
  286. }
  287. }