ptcal.py 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515
  1. '''This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
  2. Copyright 2011 by the AToMPM team and licensed under the LGPL
  3. See COPYING.lesser and README.md in the root of this project for full details'''
  4. import re, json, uuid, threading, itertools, traceback, logging, sys, time, os
  5. if sys.version_info[0] < 3:
  6. import cPickle as pickle
  7. import StringIO as StringIO
  8. from Queue import *
  9. from _abcoll import Iterable
  10. else:
  11. import pickle as pickle
  12. import io as StringIO
  13. from queue import *
  14. #from random import Random
  15. from .utils import Utilities as utils
  16. from .tcontext import ModelTransformationContext, ExhaustContext
  17. from .tconstants import TConstants as TC
  18. from .compiler import ModelAndRuleCompiler
  19. from .pytcore.core.himesis import HConstants as HC
  20. from .pytcore.rules.ndarule import NDARule
  21. from .pytcore.tcore.messages import Packet
  22. #import cProfile, pstats
  23. ''' hergin :: motif-integration start '''
  24. from .motifcontext import MotifContext
  25. from .tcorecontext import TCoreContext
  26. from .pytcore.tcore.messages import Pivots
  27. ''' hergin :: motif-integration end '''
  28. import igraph as ig
  29. #import pydot
  30. #import datetime
  31. from random import *
  32. #from threading import *
  33. #from .barrier import *
  34. from .synchgraph import *
  35. #from petrinet import *
  36. #from pprint import isreadable
  37. #from math import *
  38. '''
  39. py-t-core abstraction layer
  40. _lock used to synchronize access to self._changelogs
  41. _changelogs used to hold asworker changelogs
  42. _M the himesis graph we're transforming
  43. _mtContexts the current transformation contexts
  44. _transfData a mapping between transformation filenames and
  45. their data
  46. _userTransfs stores the transformations loaded by the user
  47. (needed to return to the pre-run state after
  48. running)
  49. _execmode the current execution mode
  50. _debugOn indicates whether or not debugging is enabled
  51. _debugProgrammedBreak a blocking flag used to freeze the execution of a
  52. transformation until the user explicitly resumes,
  53. at which point we continue precisely where we left
  54. off
  55. _mtContexts2debugClients used to map ModelTransformationContexts to their
  56. associated atompm debugging window, if any
  57. _aswCommTools bundle of properties and functions that enable and
  58. facilitate sending requests to our parent
  59. mtworker's asworker
  60. _aswNextSequenceNumber used to determine if a changelog is received out
  61. of order, and if a pending changelog is now ready
  62. to be handled
  63. username the user's username
  64. defaultDCL the user's preferred designer code language '''
  65. class PyTCoreAbstractionLayer :
  66. def __init__(self,aswCommTools,mtwid) :
  67. self._lock = threading.Condition()
  68. self._changelogs = []
  69. self._M = None
  70. ''' hergin :: motif-integration start '''
  71. self.packet = None
  72. self.globalDeltas = []
  73. self.incUpdates = True
  74. self.sendDeltas = True
  75. ''' hergin :: motif-integration end '''
  76. self._mtContexts = []
  77. self._transfData = {}
  78. self._userTransfs = []
  79. self._execmode = 'STOPPED'
  80. self._debugOn = False
  81. self._debugProgrammedBreak = threading.Event()
  82. self._debugProgrammedBreak.set()
  83. self._mtContexts2debugClients = {}
  84. self._aswCommTools = aswCommTools
  85. self._aswNextSequenceNumber = None
  86. self.username = None
  87. self.defaultDCL = TC.PYTHON
  88. self._mtwid = mtwid
  89. self.start_time = time.time()
  90. self.clock = None
  91. ''' Used only in COMP 522 and comp 621
  92. Petri Net Modules, docomposition of disconnected
  93. _M graph '''
  94. self.modules = {}
  95. ''' Synchronization graph for modular state spaces '''
  96. self.SG = None
  97. self.modStart = None
  98. self.modEnd = None
  99. self.flatStart = None
  100. self.flatEnd = None
  101. ''' State spaces for individual modules '''
  102. self.modIDtoPOS= {}
  103. self.SSs = {}
  104. #Enactment vars
  105. self.bdapiQueue = Queue()
  106. #Enactment, If this is true the OpenModel will append model to the canvas, else reload.
  107. self.loadedModel=False
  108. #Enactment, set of formalisms we load automatically to do the cleanups.
  109. self._loadedMMs = set()
  110. def processQuery(self,query):
  111. result = ""
  112. query = query['query'].replace('"',"'")
  113. qValue = query.split('(')[0].strip()
  114. if qValue == "getCount":
  115. typ = query.split("'")[1].strip()
  116. def f(e):
  117. return e['$ft__'].endswith(typ)
  118. result = "Number of '" + typ +"' in the resulting graph: " + str(len(filter(f,self.packet.graph.vs)))
  119. # I tried to use self.packet.graph.vs.select(tokens_eq=3) but the attribute names starting with $ didnt let me
  120. elif qValue == "toggleSendDelta":
  121. self.sendDeltas = not self.sendDeltas
  122. if self.sendDeltas:
  123. result = "Deltas will be sent at the end!"
  124. else:
  125. result = "Deltas won't be sent at the end!"
  126. elif qValue == "toggleIncUpdate":
  127. self.incUpdates = not self.incUpdates
  128. if self.incUpdates:
  129. result = "Incremental updates are on!"
  130. else:
  131. result = "Incremental updates are off!"
  132. self._aswPrintReq(result)
  133. ''' Use this to put the BDAPI response from client'''
  134. def _queueBDAPI(self,resp):
  135. self.bdapiQueue.put(resp)
  136. ''' send a PUT /GET/console request to the asworker '''
  137. def _aswPrintReq(self,msg) :
  138. return self._aswCommTools['httpReq']('PUT','/GET/console',{'text':msg})
  139. '''
  140. do 'callback()' once we've received the feedback for the last step that
  141. ran, if any, checking for the said feedback and handling any newly
  142. received feedback every TC.WAIT_ON_CHLOG_DELAY seconds '''
  143. def _doWhenLastStepFeedbackReceived(self,callback) :
  144. if self.incUpdates:
  145. def condition() :
  146. self._handleChangelogs()
  147. return self._mtContexts[-1].isLastStepFeedbackReceived()
  148. utils.doWhen(
  149. condition,
  150. TC.WAIT_ON_CHLOG_DELAY,
  151. callback)
  152. else:
  153. callback()
  154. '''
  155. synchronously verify if any changelogs have been received, and if we are
  156. ready to handle them, remove them from self._changelogs and handle them
  157. 1. sort changelogs by ascending sequence#
  158. 2. do nothing if no self._changelogs is empty, if no model has been loaded
  159. yet (i.e., self._aswNextSequenceNumber == None), or if the oldest
  160. changelog is still too new to be handled
  161. 3. crash if we encouter an invalid sequence#
  162. 4. otherwise (we're ready to handle the oldest changelog), handle the
  163. oldest changelog, increment self._aswNextSequenceNumber and recurse
  164. back to step 1
  165. TBI: performance would benefit greatly from caches that map atompm ids to
  166. GUIDs '''
  167. def _handleChangelogs(self) :
  168. '''
  169. handle a single changelog '''
  170. def _handleChangelog(changelog) :
  171. def eq(a,b) : return str(a) == str(b)
  172. for c in changelog :
  173. if c['op'] == 'MKEDGE' :
  174. node1 = \
  175. self._M.vs.select(lambda v : eq(v['$atompmId'],c['id1']))[0]
  176. node2 = \
  177. self._M.vs.select(lambda v : eq(v['$atompmId'],c['id2']))[0]
  178. self._M.add_edges([(node1.index, node2.index)])
  179. elif c['op'] == 'RMEDGE' :
  180. pass
  181. elif c['op'] == 'MKNODE' :
  182. self._compiler.addNode(self._M, json.loads(c['node']), c['id'])
  183. elif c['op'] == 'RMNODE' :
  184. node = \
  185. self._M.vs.select(lambda v : eq(v['$atompmId'],c['id']))[0]
  186. self._M.delete_nodes([node.index])
  187. elif c['op'] == 'CHATTR' :
  188. node = \
  189. self._M.vs.select(lambda v : eq(v['$atompmId'],c['id']))[0]
  190. self._M.vs[node.index][c['attr']] = c['new_val']
  191. elif c['op'] == 'LOADMM' :
  192. self._compiler.parseMetamodel(
  193. c['name'],
  194. utils.fread(
  195. '/users/%s/%s.metamodel'%(self.username,c['name'])),
  196. loadMM=True)
  197. elif c['op'] == 'DUMPMM' :
  198. self._compiler.unloadMetamodel(c['name'])
  199. elif c['op'] == 'RESETM' :
  200. self._M = self._compiler.compileModel(c['new_model'])
  201. self._M.mmTypeData = self._compiler.getMMTypeData()
  202. elif c['op'] == 'SYSOUT' :
  203. ''' hergin :: motif-integration :: modify :: added startsWith functions '''
  204. if c['text'].startswith(TC.RULE_SUCCESS_MSG) or \
  205. c['text'].startswith(TC.RULE_NOT_APPLICABLE_MSG) or \
  206. c['text'].startswith(TC.RULE_FAILURE_MSG) or \
  207. c['text'].startswith(TC.TRANSFORMATION_DONE) or \
  208. c['text'].startswith(TC.REMOTE_APPLICATION_FAILURE) :
  209. self._mtContexts[-1].setLastStepFeedbackReceived()
  210. self._lock.acquire()
  211. self._changelogs.sort(key=lambda c : utils.sn2int(c['sequence#']))
  212. if len(self._changelogs) == 0 or \
  213. self._aswNextSequenceNumber == None or \
  214. utils.sn2int(self._changelogs[0]['sequence#']) > \
  215. utils.sn2int(self._aswNextSequenceNumber) :
  216. self._lock.release()
  217. else :
  218. sn = self._changelogs[0]['sequence#']
  219. if utils.sn2int(sn) < utils.sn2int(self._aswNextSequenceNumber) :
  220. raise ValueError('invalid changelog sequence# :: '+sn)
  221. else :
  222. logging.debug('++ ('+sn+') '+str(self._changelogs[0]['changelog']))
  223. _handleChangelog(self._changelogs.pop(0)['changelog'])
  224. self._aswNextSequenceNumber = \
  225. utils.incrementSequenceNumber(self._aswNextSequenceNumber)
  226. self._lock.release()
  227. self._handleChangelogs()
  228. '''
  229. load a model (and its metamodels)
  230. 1. compile the provided model into a himesis graph and save it to self._M
  231. 2. synchronize self._M's mmTypeData with that of self._compiler's so that
  232. it gets updated as new metamodels are loaded
  233. 3. initialize self._aswNextSequenceNumber based on the sequence# 'sn' of
  234. the provided model, and forget any already received out-of-date
  235. changelogs
  236. NOTE: this function should only get called once (when the asworker
  237. initially sets up this mtworker) '''
  238. def loadModel(self,m,mms,sn) :
  239. assert self._M == None, 'ptcal.loadModel() should only be called once'
  240. self._compiler = ModelAndRuleCompiler(
  241. self.username,
  242. self._aswCommTools['wid'],
  243. self.defaultDCL,
  244. self._mtwid)
  245. self._M = self._compiler.compileModel(m,mmsData=mms)
  246. self._M.mmTypeData = self._compiler.getMMTypeData()
  247. ''' hergin :: motif-integration start '''
  248. self.packet = Packet(self._M)
  249. ''' hergin :: motif-integration end '''
  250. self._aswNextSequenceNumber = utils.incrementSequenceNumber(sn)
  251. self._lock.acquire()
  252. self._changelogs = \
  253. [c for c in self._changelogs if utils.sn2int(sn) < utils.sn2int(c['sequence#'])]
  254. self._lock.release()
  255. '''
  256. load a PN model (and its metamodels)
  257. 1. compile the provided model into a himesis graph and save it to self._M
  258. 2. synchronize self._M's mmTypeData with that of self._compiler's so that
  259. it gets updated as new metamodels are loaded
  260. 3. initialize self._aswNextSequenceNumber based on the sequence# 'sn' of
  261. the provided model, and forget any already received out-of-date
  262. changelogs
  263. NOTE: this function should only get called once (when the asworker
  264. initially sets up this mtworker) '''
  265. def loadModelPN(self,m,mms,sn) :
  266. assert self._M == None, 'ptcal.loadModel() should only be called once'
  267. self._compiler = ModelAndRuleCompiler(self.username)
  268. self._M = self._compiler.compileModelPN(m,mmsData=mms)
  269. disjoint = self._M.decompose(mode=ig.WEAK)
  270. #create dictionary of modules
  271. for mod in disjoint:
  272. self.modules [ uuid.uuid4()] = mod
  273. self._M.mmTypeData = self._compiler.getMMTypeData()
  274. self._aswNextSequenceNumber = utils.incrementSequenceNumber(sn)
  275. self._lock.acquire()
  276. self._changelogs = \
  277. [c for c in self._changelogs if utils.sn2int(sn) < utils.sn2int(c['sequence#'])]
  278. self._lock.release()
  279. ''' setup internal state to reflect given runtime configuration '''
  280. def _loadRuntimeConfiguration(self,rc) :
  281. if 'looseSubtypingMM' in rc :
  282. self._compiler.RC__looseSubtypingMM = rc['looseSubtypingMM']
  283. '''
  284. read in some json that describes a model transformation from file 'fname',
  285. store in self._transfData, and push a new ModelTransformationContext onto
  286. self._mtContexts '''
  287. def _loadTransform(self,fname) :
  288. if fname not in self._transfData :
  289. self._transfData[fname] = \
  290. utils.fread('/users/%s/%s'%(self.username,fname))
  291. ''' hergin :: motif-integration start '''
  292. if TC.MOTIFMM in self._transfData[fname]['metamodels']:
  293. self._mtContexts.append(MotifContext(fname,self))
  294. elif TC.TCOREMM in self._transfData[fname]['metamodels']:
  295. self._mtContexts.append(TCoreContext(fname,self))
  296. elif TC.TRANSFMM in self._transfData[fname]['metamodels']:
  297. self._mtContexts.append(ModelTransformationContext(self._transfData[fname],fname))
  298. ''' hergin :: motif-integration end '''
  299. '''
  300. load a set of user-specified transformations and forget anything
  301. previously loaded
  302. 1. forget previously loaded transformations and compiled rules
  303. 2. reset 'session' area
  304. 3. load transformations
  305. 4. remember loaded transformations '''
  306. def loadTransforms(self,fnames) :
  307. self._transfData = {}
  308. self._mtContexts = []
  309. self._compiler.forgetCompiledRules()
  310. self._M.session = {}
  311. for fname in fnames :
  312. self._loadTransform(fname)
  313. self._userTransfs = fnames
  314. '''
  315. returns the filename and compiled form of the next rule to run
  316. 1. fetch the current transformation context
  317. 2. retrieve and load runtime configuration options, if any
  318. 3. if transformatio debugging is enabled and we're entering a
  319. ModelTransformationContext for the first time, we
  320. a) remember self._execmode and set self._execmode to PAUSE
  321. b) notify the user of the impending "programmed debugging pause"
  322. c) request a new atompm instance loaded with the transformation model
  323. corresponding to the current transformation context
  324. d) unset the _debugProgrammedBreak flag and make a blocking call that
  325. waits for another thread to reset it (via
  326. self._startDebugProgrammedBreak())... this may occur in a number of
  327. cases if when this occurs
  328. i. user presses stop --> self._execmode == 'STOPPING' :
  329. _nextRule() returns an error which in turn triggers the
  330. stopping of the current transformation
  331. ii. user disables debugging --> self._execmode == 'PAUSE' :
  332. self._execmode is restored to its previous value and execution
  333. continues as planned (i.e., _nextRule() returns with the next
  334. rule to run)
  335. iii. user presses play/step --> self._execmode == 'PLAY/STEP' :
  336. same behaviour as ii.
  337. 4. call its nextStep() function to get the next transformation step
  338. a) if the step is not an object (i.e., is an application code)
  339. i. if there is more than 1 loaded transformation context,
  340. j. pop the newly completed transformation context
  341. jj. if the next context (which may be a "parent" transformation
  342. or the next of multiple loaded transformations) is a parent,
  343. update its last step application info
  344. jjj. make a recursive call to get the next rule to run from
  345. within the "next" context
  346. ii. otherwise, simply return the said application code
  347. b) if the step is an error, return it
  348. c) otherwise, determine the type of the step (via the node's $type
  349. attribute or by inspecting the 'metamodels' array in the provided
  350. .model file)
  351. i. Rules get stored in 'nr' to be later returned
  352. ii. Transformations and Exhausts[Randoms] cause the pushing of a
  353. new transformation context onto self._mtContexts, and of a
  354. recursive call to get the next rule to run from within that
  355. new context
  356. 5. return the rule name and compiled form
  357. NOTE:: in step 4c), while in debug mode, we highlight transformations,
  358. exhausts and rules before recursing on them or returning them,
  359. respectively '''
  360. def _nextRule(self) :
  361. mtc = self._mtContexts[-1]
  362. self._loadRuntimeConfiguration(mtc.getRuntimeConfiguration())
  363. if self._debugOn and not mtc.isTransformationUnderWay() and \
  364. (type(mtc) == MotifContext or type(mtc) == TCoreContext) : # hergin :: motif-integration modify
  365. _execmode = self._execmode
  366. self._execmode = 'PAUSE'
  367. self._aswPrintReq(TC.DEBUGGING_HALT)
  368. self._requestClientDebugWindow(mtc.fname)
  369. self._startDebugProgrammedBreak()
  370. if self._execmode == 'STOPPING' :
  371. return {'$err':'transformation stopped during debugging pause'}
  372. elif self._execmode == 'PAUSE' or \
  373. self._execmode == 'PLAY' or \
  374. self._execmode == 'STEP' :
  375. self._execmode = _execmode
  376. self.bdapiQueue = Queue()
  377. ns = mtc.nextStep()
  378. if ns.__class__ != {}.__class__ :
  379. if len(self._mtContexts) > 1 :
  380. self._mtContexts = self._mtContexts[:-1]
  381. if self._mtContexts[-1].isTransformationUnderWay() :
  382. self._mtContexts[-1].setLastStepApplicationInfo(ns)
  383. return self._nextRule()
  384. else :
  385. return ns
  386. elif '$err' in ns :
  387. return ns['$err']
  388. else :
  389. def highlightUpcomingStep() :
  390. for _mtc in reversed(self._mtContexts) :
  391. if id(_mtc) in self._mtContexts2debugClients :
  392. debugClient = self._mtContexts2debugClients[id(_mtc)]
  393. self._requestNodeHighlight(
  394. debugClient['host'],
  395. debugClient['aswid'],
  396. _mtc.getCurrentStepId())
  397. break
  398. if 'id' in ns :
  399. fulltype = mtc.t['nodes'][ns['id']]['$type']
  400. ''' hergin :: motif-integration start '''
  401. if fulltype == mtc.metamodel+"/CRule":
  402. if self._debugOn :
  403. highlightUpcomingStep()
  404. self._loadTransform(ns['rule'])
  405. return self._nextRule()
  406. elif fulltype.startswith(TC.TCOREMM) or \
  407. fulltype.startswith(TC.MOTIFMM):
  408. if self._debugOn :
  409. highlightUpcomingStep()
  410. return ns
  411. ''' hergin :: motif-integration end '''
  412. elif fulltype == TC.TRANSFMM+'/Rule' :
  413. if self._debugOn :
  414. highlightUpcomingStep()
  415. return {'fname':ns['fname'],
  416. 'cr':self._compiler.compileRule(None,ns['fname'])}
  417. #Enactment OpenModel blob, pathToFormalism is present is MM, but not used here,
  418. #for functionality of opening window with formalisms is in WriteModel.
  419. #pathToFormalism should be removed from MM for OpenModel (was not removed due to
  420. #language evolution).
  421. elif fulltype == TC.TRANSFMM+'/OpenModel' :
  422. if self._debugOn :
  423. highlightUpcomingStep()
  424. fname = mtc.t['nodes'][ns['id']]['pathToModel']['value']
  425. #formalism = mtc.t['nodes'][ns['id']]['pathToFormalism']['value']
  426. formalism = ""
  427. return {'fname':fname,'formalism':formalism,'rtype':'OpenModel'}
  428. #Enactment WriteModel blob
  429. elif fulltype == TC.TRANSFMM+'/WriteModel' :
  430. if self._debugOn :
  431. highlightUpcomingStep()
  432. fname = mtc.t['nodes'][ns['id']]['pathToModel']['value']
  433. formalism = mtc.t['nodes'][ns['id']]['pathToFormalism']['value']
  434. return {'fname':fname,'formalism':formalism,'rtype':'WriteModel'}
  435. elif fulltype == TC.TRANSFMM+'/Transformation' :
  436. if self._debugOn :
  437. highlightUpcomingStep()
  438. self._loadTransform(ns['fname'])
  439. return self._nextRule()
  440. elif fulltype == TC.TRANSFMM+'/Exhaust' :
  441. self._mtContexts.append( ExhaustContext(mtc.t,ns['id']) )
  442. return self._nextRule()
  443. elif fulltype == TC.TRANSFMM+'/ExhaustRandom' :
  444. self._mtContexts.append( ExhaustContext(mtc.t,ns['id'],self._randomGen) )
  445. return self._nextRule()
  446. else :
  447. ''' hergin :: motif-integration start '''
  448. if 'trafoResult' in ns:
  449. return ns;
  450. ''' hergin :: motif-integration end '''
  451. contents = utils.fread('/users/%s/%s'%(self.username,ns['fname']))
  452. if self._debugOn :
  453. highlightUpcomingStep()
  454. if TC.RULEMM in contents['metamodels'] :
  455. return {'fname':ns['fname'],
  456. 'cr':self._compiler.compileRule(contents,ns['fname'])}
  457. elif TC.TRANSFMM in contents['metamodels'] :
  458. self._transfData[ns['fname']] = contents
  459. self._loadTransform(ns['fname'])
  460. return self._nextRule()
  461. raise ValueError( \
  462. 'file does not contain valid rule or transformation '+ \
  463. 'model :: '+ns['fname'])
  464. ''' Enactment do OpenModel magic
  465. '''
  466. def runOpenModelRule(self, fname="",formalism=""):
  467. unload = ""
  468. if not fname:
  469. return (None,TC.FAILED)
  470. else:
  471. if not formalism:
  472. self._aswPrintReq('auto loading model :: '+fname)
  473. try:
  474. with open(os.getcwd()+'/users/'+self.username+fname) as f:
  475. pass
  476. except IOError as e:
  477. self._aswPrintReq('failed opening a file :: '+fname)
  478. return (None,TC.FAILED)
  479. if not self.loadedModel:
  480. method = '_loadModelForTransform'
  481. if len(self._loadedMMs) == 0:
  482. self._loadedMMs = self._compiler._loadedMMs.copy()
  483. diff = self._compiler._loadedMMs.difference(self._loadedMMs)
  484. for u in diff:
  485. unload += u+'.defaultIcons.metamodel,'
  486. else:
  487. method = '_appendModelForTransform'
  488. resp = self._aswCommTools['httpReq'](
  489. 'PUT',
  490. '/GET/console',
  491. {'text':'CLIENT_BDAPI :: '+
  492. '{"func":"'+method+'",'+
  493. ' "args":'+
  494. '{"fname":"'+fname+'",'+
  495. '"unload":"'+unload+'",'+
  496. ' "callback-url":"/__mt/bdapiresp?wid='+
  497. self._aswCommTools['wid']+'"}}'})
  498. resp = self.bdapiQueue.get(block=True,timeout=5000)
  499. if not resp['resp'] == 'ok':
  500. return (None,TC.FAILED)
  501. else:
  502. if not self.loadedModel:
  503. self.loadedModel = True
  504. return (None,TC.SUCCEEDED)
  505. #Was used to open new window with loaded formalisms and pause the transform, now
  506. #this functionality is in WriteMOdel.
  507. else:
  508. pass
  509. # Keep for now....
  510. # self._aswPrintReq('pausing transform')
  511. # self._execmode = 'PAUSE'
  512. # self._aswPrintReq('opening new window for manual step:: '+fname)
  513. # try:
  514. # with open(os.getcwd()+'/users/'+self.username+fname) as f:
  515. # exists = 'true'
  516. # except IOError as e:
  517. # exists = 'false'
  518. # resp = self._aswCommTools['httpReq'](
  519. # 'PUT',
  520. # '/GET/console',
  521. # {'text':'CLIENT_BDAPI :: '+
  522. # '{"func":"_createEmptyModelInNewWindow",'+
  523. # ' "args":'+
  524. # '{"fname":"'+fname+'","exists":"'+exists+'",'+'"formalism":"'+formalism+'",'
  525. # ' "callback-url":"/__mt/bdapiresp?wid='+
  526. # self._aswCommTools['wid']+'"}}'})
  527. # self.loadedModel = False
  528. # return (None,TC.SUCCEEDED)
  529. ''' Enactment do WriteModel magic
  530. '''
  531. def runWriteModelRule(self,fname="",formalism=""):
  532. if not fname:
  533. #this makes next openmodel call a load model instead of append.
  534. #basically use this trick to clean up canvas and have new model:
  535. #first place WriteModel blob without fname,
  536. #followed by OpenModel.
  537. self.loadedModel = False
  538. return (None,TC.SUCCEEDED)
  539. else:
  540. #No formalism specified, save model
  541. if not formalism:
  542. self._aswPrintReq('auto saving model :: '+fname)
  543. resp = self._aswCommTools['httpReq'](
  544. 'PUT',
  545. '/GET/console',
  546. {'text':'CLIENT_BDAPI :: '+
  547. '{"func":"_writeModelAfterTransform",'+
  548. ' "args":'+
  549. '{"fname":"'+fname+'",'+
  550. ' "callback-url":"/__mt/bdapiresp?wid='+
  551. self._aswCommTools['wid']+'"}}'})
  552. #Need to wait for the model to load.
  553. resp = self.bdapiQueue.get(block=True,timeout=5000)
  554. if resp['resp'] == 'ok':
  555. self.loadedModel = False
  556. return (None,TC.SUCCEEDED)
  557. else:
  558. (None,TC.FAILED)
  559. #Formalism specified, open new window, with loaded formalism and/or model.
  560. else:
  561. self._aswPrintReq('pausing transform')
  562. self._execmode = 'PAUSE'
  563. self._aswPrintReq('opening new window for manual step:: '+fname)
  564. try:
  565. with open(os.getcwd()+'/users/'+self.username+fname) as f:
  566. #open existing model
  567. exists = 'true'
  568. except IOError as e:
  569. #or save model with the fname provided
  570. exists = 'false'
  571. resp = self._aswCommTools['httpReq'](
  572. 'PUT',
  573. '/GET/console',
  574. {'text':'CLIENT_BDAPI :: '+
  575. '{"func":"_createEmptyModelInNewWindow",'+
  576. ' "args":'+
  577. '{"fname":"'+fname+'","exists":"'+exists+'",'+'"formalism":"'+formalism+'",'
  578. ' "callback-url":"/__mt/bdapiresp?wid='+
  579. self._aswCommTools['wid']+'"}}'})
  580. self.loadedModel = False
  581. return (None,TC.SUCCEEDED)
  582. '''
  583. synchronously save 1 changelog into self._changelogs '''
  584. def onchangelog(self,c) :
  585. self._lock.acquire()
  586. self._changelogs.append(c)
  587. self._lock.release()
  588. '''
  589. causes the execution of the current transformation(s) to pause (by
  590. preventing _play()'s next call to _step(), if any) '''
  591. def pause(self) :
  592. self._execmode = 'PAUSE'
  593. if not self.incUpdates:
  594. req = self.buildEditHttpReq(self.globalDeltas)
  595. self.globalDeltas = []
  596. resp = self._aswCommTools['httpReq']('POST','/batchEdit',req)
  597. if not utils.isHttpSuccessCode(resp['statusCode']) :
  598. self.stop()
  599. self._aswPrintReq(TC.REMOTE_APPLICATION_FAILURE + resp['reason'])
  600. return
  601. self._handleChangelogs()
  602. '''
  603. play()
  604. calls _play() if it isn't already running (i.e., if we're already in PLAY
  605. mode, a timed call to _play() has already been placed) and if there isn't
  606. already another thread currently paused on _debugProgrammedBreak... if
  607. there is such a thread, it is unpaused (via _stopDebugProgrammedBreak())
  608. and the current thread terminates immediately
  609. _play()
  610. schedules an action for when feedback from the last step is received...
  611. the action is
  612. 1. return if we're no longer in PLAY mode
  613. 2. take one _step()
  614. 3. schedule a recursive call to _play() in TC.INTER_RULE_DELAY
  615. seconds '''
  616. def play(self) :
  617. self.start_time = time.time()
  618. if self._execmode == 'STOPPED':
  619. self._randomGen = Random(0)
  620. if self._execmode != 'PLAY' :
  621. self._execmode = 'PLAY'
  622. if not self._stopDebugProgrammedBreak() :
  623. self._play()
  624. def _play(self) :
  625. if self.incUpdates:
  626. self._doWhenLastStepFeedbackReceived(
  627. lambda : self._execmode == 'PLAY' and \
  628. self._step() and \
  629. utils.setTimeout(TC.INTER_RULE_DELAY,self._play))
  630. else:
  631. self._doWhenLastStepFeedbackReceived(
  632. lambda : self._execmode == 'PLAY' and \
  633. self._step() and \
  634. self._play())
  635. '''
  636. associate the newly created debugging window described by 'clientInfo'
  637. to the ModelTransformationContext that requested its creation '''
  638. def registerDebugClient(self,clientInfo) :
  639. clientInfo = json.loads(clientInfo)
  640. for mtc in reversed(self._mtContexts) :
  641. if hasattr(mtc,'fname') and mtc.fname == clientInfo['fname'] :
  642. self._mtContexts2debugClients[id(mtc)] = clientInfo
  643. '''
  644. request a new atompm client via the client backdoor API... the new client
  645. will be loaded with the specified model and sufficient information to
  646. identify and communicate with the client will be POSTed to the callback
  647. url '''
  648. def _requestClientDebugWindow(self,fname) :
  649. return self._aswCommTools['httpReq'](
  650. 'PUT',
  651. '/GET/console',
  652. {'text':'CLIENT_BDAPI :: '+
  653. '{"func":"_loadModelInNewWindow",'+
  654. ' "args":'+
  655. '{"fname":"'+fname+'",'+
  656. ' "callback-url":"/__mt/debugClient?wid='+
  657. self._aswCommTools['wid']+'"}}'})
  658. '''
  659. request that the specified node from the specified atompm instance be
  660. highlighted '''
  661. def _requestNodeHighlight(self,host,aswid,asid,timeout=1000) :
  662. return utils.httpReq(
  663. 'PUT',
  664. host,
  665. '/GET/console?wid='+aswid,
  666. {'text':'CLIENT_BDAPI :: '+
  667. '{"func":"_highlight",'+
  668. ' "args":'+
  669. '{"asid":"'+asid+'",'+
  670. ' "timeout":'+str(timeout)+'}}'})
  671. ''' hergin :: motif-integration :: START :: put this to outside of step function '''
  672. ''' also added self '''
  673. '''
  674. go through a rule's deltas and (1) produce a batchEdit request, and
  675. (2) undo them
  676. NOTE: we undo the deltas for 2 reasons
  677. 1. so that changes become driven by asworker changelogs (like in
  678. csworkers)
  679. 2. so that we don't need to figure out which entries in received
  680. changelogs correspond to user-operations and which ones
  681. correspond to the effects of the constructed batchEdit
  682. NOTE: since we sometimes need to use the result from one request as the
  683. parameter of another (i.e., create a node, update *it*), we use
  684. the 'mknodes' map to remember which requests created which new
  685. nodes... this also allows to know which nodes already exist and
  686. which ones were created by the last rule
  687. NOTE: because creation of connector nodes and their linking to their
  688. ends is described in non-contiguous deltas, we use the 'mknodes'
  689. map to remember incomplete connector creation requests until the
  690. appropriate MKEDGE deltas are encountered '''
  691. def buildEditHttpReq(self,deltas) :
  692. reqs = []
  693. mknodes = {}
  694. neighborhood = None
  695. '''
  696. construct an atompmId given a node... the result will be
  697. a) a 'macro' to be replaced by the result of an earlier request
  698. within the batchEdit, if the node was created by the last rule
  699. b) the atompmId stored within the node, if the node already has
  700. a counter-part in atompm '''
  701. def atompmInstanceId(node) :
  702. if node[HC.GUID] in mknodes :
  703. return '$'+str(mknodes[node[HC.GUID]])+'$'
  704. else :
  705. return node['$atompmId']
  706. for d in deltas :
  707. if d['op'] == 'RMNODE' :
  708. reqs.append({ \
  709. 'method':'DELETE',
  710. 'uri':d['attrs'][HC.FULLTYPE]+'/'+ \
  711. d['attrs']['$atompmId']+'.instance'})
  712. elif d['op'] == 'MKNODE' :
  713. mknodes[d['guid']] = len(reqs)
  714. node = self._M.vs[self._M.get_node(d['guid'])]
  715. if neighborhood is None :
  716. neighborhood = [n[HC.FULLTYPE]+'/'+n['$atompmId']+'.instance' for n in d['neighborhood'] if '$atompmId' in n]
  717. if node[HC.CONNECTOR_TYPE] :
  718. reqs.append({ \
  719. 'method':'POST',
  720. 'uri':node[HC.FULLTYPE]+'.type',
  721. 'reqData':
  722. {'src':None,
  723. 'dest':None,
  724. 'hitchhiker':
  725. {'segments':None,
  726. 'asSrc':None,
  727. 'asDest':None,
  728. 'neighborhood':neighborhood}}})
  729. else :
  730. reqs.append({ \
  731. 'method':'POST',
  732. 'uri':node[HC.FULLTYPE]+'.type',
  733. 'reqData':{'hitchhiker':{'neighborhood':neighborhood}}})
  734. elif d['op'] == 'RMEDGE' :
  735. pass
  736. elif d['op'] == 'MKEDGE' :
  737. def isConnectorMKNODE(req):
  738. return 'dest' in req['reqData']
  739. if d['guid1'] in mknodes :
  740. req = reqs[ mknodes[d['guid1']] ]
  741. if isConnectorMKNODE(req) :
  742. node2 = self._M.vs[self._M.get_node(d['guid2'])]
  743. id = atompmInstanceId(node2)
  744. req['reqData']['dest'] = \
  745. req['reqData']['hitchhiker']['asDest'] = \
  746. node2[HC.FULLTYPE]+'/'+id+'.instance'
  747. if d['guid2'] in mknodes :
  748. req = reqs[ mknodes[d['guid2']] ]
  749. if isConnectorMKNODE(req) :
  750. node1 = self._M.vs[self._M.get_node(d['guid1'])]
  751. id = atompmInstanceId(node1)
  752. req['reqData']['src'] = \
  753. req['reqData']['hitchhiker']['asSrc'] = \
  754. node1[HC.FULLTYPE]+'/'+id+'.instance'
  755. elif d['op'] == 'CHATTR' :
  756. node = self._M.vs[self._M.get_node(d['guid'])]
  757. id = atompmInstanceId(node)
  758. reqs.append({ \
  759. 'method':'PUT',
  760. 'uri':node[HC.FULLTYPE]+'/'+id+'.instance',
  761. 'reqData':{'changes':{d['attr']:d['new_val']}}})
  762. elif d['op'] == 'LOADMM' :
  763. reqs.append({ \
  764. 'method':'PUT',
  765. 'uri':'/current.metamodels',
  766. 'reqData':
  767. {'mm':'/%s%s.metamodel'%(self.username,d['name'])}})
  768. if self.incUpdates:
  769. for d in reversed(deltas) :
  770. if d['op'] == 'RMNODE' :
  771. newNodeIndex = self._M.add_node(newNodeGuid=d['attrs'][HC.GUID])
  772. for attr,val in d['attrs'].items() :
  773. self._M.vs[newNodeIndex][attr] = val
  774. elif d['op'] == 'MKNODE' :
  775. node = self._M.vs[self._M.get_node(d['guid'])]
  776. self._M.delete_nodes([node.index])
  777. elif d['op'] == 'RMEDGE' :
  778. node1 = self._M.vs[self._M.get_node(d['guid1'])]
  779. node2 = self._M.vs[self._M.get_node(d['guid2'])]
  780. self._M.add_edges([(node1.index, node2.index)])
  781. elif d['op'] == 'MKEDGE' :
  782. pass
  783. elif d['op'] == 'CHATTR' :
  784. node = self._M.vs[self._M.get_node(d['guid'])]
  785. node[d['attr']] = d['old_val']
  786. elif d['op'] == 'LOADMM' :
  787. pass
  788. ''' hergin :: motif-integration modify: succeeded rule name + time '''
  789. #reqs.append({\
  790. # 'method':'PUT',
  791. # 'uri':'/GET/console',
  792. # 'reqData':{'text':TC.RULE_SUCCESS_MSG+" ("+self._mtContexts[-1]._lastStep['alias']+":"+self._mtContexts[-1]._lastStep['name']+") in "+str(self._mtContexts[-1]._lastStep['time'])}})
  793. # 'reqData':{'text':TC.RULE_SUCCESS_MSG}})
  794. return reqs
  795. ''' hergin :: motif-integration :: END :: put this to outside of step function '''
  796. '''
  797. author: hergin
  798. sendAndApplyDelta()
  799. If debug mode:
  800. Sends and applies the inputted deltas to the model and UI instance.
  801. else:
  802. Collect deltas in a globalDeltas variable to handle later
  803. '''
  804. def sendAndApplyDelta(self,deltas):
  805. if self.incUpdates:
  806. req = self.buildEditHttpReq(deltas)
  807. resp = self._aswCommTools['httpReq']('POST','/batchEdit',req)
  808. if not utils.isHttpSuccessCode(resp['statusCode']) :
  809. self.stop()
  810. self._aswPrintReq(TC.REMOTE_APPLICATION_FAILURE + resp['reason'])
  811. return
  812. self._handleChangelogs()
  813. else:
  814. self.globalDeltas.extend(deltas)
  815. self.packet.deltas = []
  816. '''
  817. step()
  818. wrapper around _step() that ensures that step requests from user are
  819. ignored when in PLAY mode, and that valid requests only go through (i.e.,
  820. actually call _step()) when feedback for the last step is received...
  821. moreover, as is the case for play(), if there is already another thread
  822. currently paused on _debugProgrammedBreak, it is unpaused (via
  823. _stopDebugProgrammedBreak()) and the current thread terminates immediately
  824. _step()
  825. fetch and run next rule
  826. 1. fetch next rule
  827. a) if next rule is not a {} (i.e., all available transformations have
  828. terminated and _nextRule() returned the resulting application code),
  829. report application code and stop()
  830. b) if an error is returned, report it and stop()
  831. c) otherwise,
  832. i. run rule (returns (deltas|error,applicationInfo))
  833. ii. set ran rule's application info
  834. iii. if rule was n/a, report this
  835. iii. if rule failed, report this and error
  836. iii. otherwise,
  837. j. construct a batchEdit operation based on the rule's effects,
  838. and unfo the said effects
  839. jj. send off the batchEdit
  840. jjj. stop() if the batchEdit fails
  841. NOTE: this function assumes that feedback for the last step has already
  842. been received '''
  843. def step(self) :
  844. self.start_time = time.time()
  845. if self._execmode == 'PLAY' :
  846. pass
  847. else :
  848. if self._execmode == 'STOPPED':
  849. self._randomGen = Random(0)
  850. self._execmode = 'STEP'
  851. if not self._stopDebugProgrammedBreak() :
  852. self._doWhenLastStepFeedbackReceived(self._step)
  853. def _step(self) :
  854. '''
  855. run the specified rule and return a tuple describing its execution '''
  856. def runRule(r) :
  857. ''' hergin :: motif-integration start '''
  858. #self._aswPrintReq('launching rule :: '+r['fname'])
  859. #ar = NDARule(r['cr']['lhs'],r['cr']['rhs'],rng=self._randomGen)
  860. mtc = self._mtContexts[-1]
  861. if mtc.metamodel == TC.MOTIFMM or mtc.metamodel == TC.TCOREMM:
  862. ar = r['rule']
  863. else:
  864. ar = NDARule(r['cr']['lhs'],r['cr']['rhs'],rng=self._randomGen,sendAndApplyDeltaFunc=self.sendAndApplyDelta)
  865. startTime = time.time()
  866. if mtc.nextInput == "packetIn":
  867. self.packet = ar.packet_in(self.packet)
  868. mtc.setLastStepExecTime(time.time()-startTime)
  869. elif mtc.nextInput == "nextIn":
  870. self.packet = ar.next_in(self.packet)
  871. mtc.setLastStepExecTime(time.time()-startTime)
  872. elif mtc.nextInput == "cancelIn":
  873. self.packet = ar.cancelIn(self.packet)
  874. mtc.setLastStepExecTime(time.time()-startTime)
  875. elif mtc.nextInput == "successIn":
  876. self.packet = ar.success_in(self.packet)
  877. mtc.setLastStepExecTime(time.time()-startTime)
  878. ''' hergin :: motif-integration end '''
  879. if ar.is_success :
  880. return (self.packet.deltas,TC.SUCCEEDED)
  881. elif not ar.is_success :
  882. ''' hergin :: motif-integration start (Some terminology fixed) '''
  883. if ar.exception :
  884. return (str(ar.exception),TC.EXCEPTION)
  885. else :
  886. return (None,TC.FAILED)
  887. ''' hergin :: motif-integration end '''
  888. try :
  889. nr = self._nextRule()
  890. except Exception :
  891. print(traceback.format_exc())
  892. nr = {'$err':traceback.format_exc()}
  893. ''' hergin :: motif-integration start TRAFO RESULT: in case of a CRule_end, pop it from context and continue the rest '''
  894. while 'trafoResult' in nr:
  895. if len(self._mtContexts)==1:
  896. if not self.incUpdates and self.sendDeltas:
  897. ''' hergin TO BE MODIFIED - release mode will change '''
  898. req = self.buildEditHttpReq(self.globalDeltas)
  899. self.globalDeltas = []
  900. resp = self._aswCommTools['httpReq']('POST','/batchEdit',req)
  901. if not utils.isHttpSuccessCode(resp['statusCode']) :
  902. self.stop()
  903. self._aswPrintReq(TC.REMOTE_APPLICATION_FAILURE + resp['reason'])
  904. return
  905. self._handleChangelogs()
  906. exec_time = self._mtContexts[-1].totalExecutionTime/1000.0
  907. total_time = (time.time()-self.start_time)/1000.0
  908. self._aswPrintReq(TC.TRANSFORMATION_DONE+nr['trafoResult']+" in "+str(exec_time)+" seconds, in total "+str(total_time))
  909. self.stop()
  910. return
  911. else:
  912. prevTrafo=self._mtContexts.pop()
  913. self._mtContexts[-1].setLastStepExecTime(prevTrafo.totalExecutionTime)
  914. self._mtContexts[-1].setLastStepApplicationInfo(nr['trafoResult'])
  915. try :
  916. nr = self._nextRule()
  917. except Exception :
  918. nr = {'$err':traceback.format_exc()}
  919. if nr.__class__ != {}.__class__ :
  920. self._aswPrintReq(TC.TRANSFORMATION_DONE + nr)
  921. self.stop()
  922. return
  923. elif '$err' in nr :
  924. self._aswPrintReq(TC.NO_NEXT_RULE+nr['$err'])
  925. self._stop()
  926. return
  927. else :
  928. if 'rtype' in nr:
  929. type = nr['rtype']
  930. if type == 'OpenModel':
  931. (res,ai) = self.runOpenModelRule(nr['fname'],nr['formalism'])
  932. elif type == 'WriteModel':
  933. (res,ai) = self.runWriteModelRule(nr['fname'],nr['formalism'])
  934. self._mtContexts[-1].setLastStepApplicationInfo(ai)
  935. self._mtContexts[-1].setLastStepFeedbackReceived()
  936. return True
  937. else:
  938. (res,ai) = runRule(nr)
  939. self._mtContexts[-1].setLastStepApplicationInfo(ai)
  940. if ai == TC.FAILED and self.incUpdates:
  941. ''' hergin :: motif-integration modify (which rule is not succeeded) '''
  942. self._aswPrintReq(TC.RULE_FAILURE_MSG+" ("+self._mtContexts[-1]._lastStep['alias']+":"+self._mtContexts[-1]._lastStep['name']+")")
  943. elif ai == TC.EXCEPTION and self.incUpdates:
  944. self._aswPrintReq(TC.RULE_EXCEPTION_MSG + res)
  945. else :
  946. ''' hergin :: motif-integration :: start '''
  947. mtc = self._mtContexts[-1]
  948. if self.incUpdates:
  949. if mtc.metamodel == TC.MOTIFMM or mtc.metamodel == TC.TCOREMM:
  950. self._aswPrintReq(TC.RULE_SUCCESS_MSG+" ("+self._mtContexts[-1]._lastStep['alias']+":"+self._mtContexts[-1]._lastStep['name']+")")
  951. else:
  952. self._aswPrintReq(TC.RULE_SUCCESS_MSG)
  953. self._mtContexts[-1].setLastStepFeedbackReceived()
  954. ''' hergin :: motif-integration :: end '''
  955. return True
  956. '''
  957. stop()
  958. sets self._execmode to STOPPING and schedules a call to _stop() for when
  959. feedback from the last step is received... being in STOPPING mode implies
  960. that the _play() loop, if any, will be broken, and that incoming user
  961. requests will be rejected... in the case where there is already another
  962. thread currently paused on _debugProgrammedBreak, it is unpaused (via
  963. _stopDebugProgrammedBreak()) which leads to the transformation being
  964. stopped from within that thread; the current thread terminates immediately
  965. _stop()
  966. 1. restores self._mtContexts to right after the user loaded his
  967. transformation(s) (i.e., to before we actually [partially] ran it)
  968. 2. resets self._mtContexts2debugClients
  969. 3. sends a console message to notify the user that the transformation has
  970. stopped
  971. 4. sets self._execmode to STOPPED (i.e., we're done STOPPING and can
  972. handle new requests) '''
  973. def isStopped(self) : return self._execmode == 'STOPPED'
  974. def isStopping(self) : return self._execmode == 'STOPPING'
  975. def stop(self) :
  976. if not self.incUpdates:
  977. req = self.buildEditHttpReq(self.globalDeltas)
  978. self.globalDeltas = []
  979. resp = self._aswCommTools['httpReq']('POST','/batchEdit',req)
  980. if not utils.isHttpSuccessCode(resp['statusCode']) :
  981. self.stop()
  982. self._aswPrintReq(TC.REMOTE_APPLICATION_FAILURE + resp['reason'])
  983. return
  984. self._handleChangelogs()
  985. self._execmode = 'STOPPING'
  986. #Used for enactment, prevents open being append.
  987. self.loadedModel = False
  988. if not self._stopDebugProgrammedBreak() :
  989. self._doWhenLastStepFeedbackReceived(self._stop)
  990. def _stop(self) :
  991. self._mtContexts = []
  992. for fname in self._userTransfs :
  993. self._loadTransform(fname)
  994. self._mtContexts2debugClients = {}
  995. self._aswPrintReq(TC.TRANSFORMATION_STOPPED)
  996. self._execmode = 'STOPPED'
  997. '''
  998. enter a "programmed debugging pause" (i.e. unset the _debugProgrammedBreak
  999. flag and block until another thread resets it '''
  1000. def _startDebugProgrammedBreak(self) :
  1001. self._debugProgrammedBreak.clear()
  1002. self._debugProgrammedBreak.wait()
  1003. '''
  1004. if the _debugProgrammedBreak flag is not set (this can only happen when
  1005. another thread unset it to enter a programmed debugging pause), set it and
  1006. return true, otherwise do nothing and return false
  1007. NOTE:: this function returns true iff there is a thread waiting on
  1008. _debugProgrammedBreak '''
  1009. def _stopDebugProgrammedBreak(self) :
  1010. if not self._debugProgrammedBreak.isSet() :
  1011. self._debugProgrammedBreak.set()
  1012. return True
  1013. return False
  1014. '''
  1015. toggle the _debugOn flag and report debugger status to atompm... when
  1016. disabling debugging, any current programmed debugging pauses are stopped
  1017. (and execution resumes normally)
  1018. while in DEBUG MODE,
  1019. . entering a ModelTransformationContext for the first time triggers
  1020. a) setting self._execmode to PAUSE
  1021. b) notifying the user of the "programmed debugging pause"
  1022. c) spawning of a new atompm instance loaded with the relevant
  1023. transformation model
  1024. d) entering programmed debugging pause that can be broken by
  1025. _stopDebugProgrammedBreak() which is triggered by
  1026. i. disabling transformation debugging; OR
  1027. ii. pressing "play", "step" or "stop"
  1028. . before running a rule, it or its enclosing ExhaustContext's associated
  1029. atompm node is highlighted '''
  1030. def toggleDebugMode(self) :
  1031. self._debugOn = not self._debugOn
  1032. if self._debugOn :
  1033. self._aswPrintReq(TC.DEBUGGING_ON)
  1034. else :
  1035. self._stopDebugProgrammedBreak()
  1036. self._aswPrintReq(TC.DEBUGGING_OFF)
  1037. '''
  1038. #Perform flat reachability analysis
  1039. #This is what creates the simple reachability graph.
  1040. #If the Petri nets are disjoint there will be several PNs "modules" that will be calculated in parallel.
  1041. def PNFull(self,fname='',dot=False):
  1042. #if not self.modules:
  1043. self._handleChangelogs()
  1044. self.modules = {}
  1045. self.modStart = time()
  1046. disjoint = self._M.decompose(mode=ig.WEAK)
  1047. #Let's compile PN graph out of generic himesis graph and create dictionary with unique IDs
  1048. barier = barrier(len(disjoint)+1) #barier, modules + synch thread
  1049. for mod in disjoint:
  1050. queue = Queue()
  1051. uid = uuid.uuid4()
  1052. key = str(uid)[:str(uid).index('-')]
  1053. module = PnModule(self.toPN(mod),queue, barier,True)
  1054. self.modules [ key] = module
  1055. module.start()
  1056. barier.wait()
  1057. print 'Time elapsed flat analysis %f'%(time() - self.modStart)
  1058. self.modules [ key].summary()
  1059. self.modStart = time()
  1060. #do the test of reachability here.
  1061. #self.reachabilityTestFlat()
  1062. print 'Find place elapsed flat analysis %f'%(time() - self.modStart)
  1063. for key,mod in self.modules.items():
  1064. if dot:
  1065. #can take too long to plot for large state space and/or hand dot binary
  1066. #here we output the reacability graph in svg
  1067. mod.graph(key=key,fname=fname)
  1068. else:
  1069. #here we output reachability graph in xml
  1070. mod.reachtoxml(fname,key)
  1071. #peroform modular analysis, use at your own risk. Toolbar does not enable this, experimental
  1072. def analyzePN(self):
  1073. #First lets break model into submodels
  1074. self.modStart = time()
  1075. #if not self.modules:
  1076. self.modules = {}
  1077. disjoint = self._M.decompose(mode=ig.WEAK)
  1078. barier = barrier(len(disjoint)+1) #barier, modules + synch thread
  1079. for mod in disjoint:
  1080. queue = Queue()
  1081. module = PnModule(self.toPN(mod),queue, barier)
  1082. self.modules [ module.getKey()] = module
  1083. module.start()
  1084. barier.wait() #wait till all threads stop doing first phase.
  1085. M0 = []
  1086. TFenabled = []
  1087. TF = {}
  1088. work = []
  1089. tofire = []
  1090. for key,mod in self.modules.items():
  1091. TF[key] = mod.TFS
  1092. M0.append('%s-%d'%(key,0))
  1093. ind=0
  1094. self.sg = synchgraph(len(self.modules),M0)
  1095. work.append(M0)
  1096. res={}
  1097. while work:
  1098. M = work.pop()
  1099. for key,mod in self.modules.items():
  1100. TFenabled.append( mod.getEnabledTFs())
  1101. tofire = reduce(set.intersection,map(set,TFenabled))
  1102. for key,mod in self.modules.items():
  1103. mod.que.put(tofire)
  1104. barier.wait() #lets wait for threads, they may building local graphs still
  1105. end = False
  1106. for key,mod in self.modules.items():
  1107. if not mod.result:
  1108. end = True
  1109. res[key] = mod.result #got results now produce new states for syngraph and archs.
  1110. if not end:
  1111. work.append(M)
  1112. else:
  1113. #self.sg.graph()
  1114. for key,mod in self.modules.items():
  1115. mod.SC()
  1116. mod.graph()
  1117. mod.que.put(['@exit'])
  1118. self.sg.markSCC(self.modules)
  1119. self.sg.graph()
  1120. print '---------------------------'
  1121. print 'Time elapsed modular analysis %f'%(time() - self.modStart)
  1122. for key,mod in self.modules.items():
  1123. mod.summary()
  1124. print '---------------------------'
  1125. print 'Synch graph:'
  1126. self.sg.summary()
  1127. print '---------------------------'
  1128. self.modStart = time()
  1129. self.reachabilityTestModular()
  1130. print 'Find place elapsed modular analysis %f'%(time() - self.modStart)
  1131. return
  1132. #main result
  1133. fr ={}
  1134. to = {}
  1135. for key,value in res.items():
  1136. for k,v in value.items():
  1137. if not k in fr:
  1138. fr[k] = []
  1139. fr[k].append([])
  1140. fr[k].append([])
  1141. fr[k][0].append(v[0])
  1142. fr[k][1].append(v[1])
  1143. from_prod=[]
  1144. to_prod = []
  1145. T=None
  1146. for key,value in fr.items():
  1147. T = key
  1148. #res = list(list(itertools.product(*value[0]))[0])
  1149. from_prod.append(list( list(itertools.product(*value[0]))))
  1150. to_prod.append(list (list(itertools.product (*value[1]))))
  1151. self.sg.addMarkingBatch(T,from_prod,to_prod)
  1152. #ENABLE
  1153. self.sg.graph(ind)
  1154. ind+=1;
  1155. #
  1156. # self.sg.addMarking(from_prod[i],to_prod[i],T)
  1157. res.clear()
  1158. TFenabled = []
  1159. #ENABLE
  1160. #self.sg.graph()
  1161. TM = {} #dict by tf transition inside slists of lists of start and end states
  1162. #compile into our PN representation
  1163. def toPN(self,mod):
  1164. oldtonew = {}
  1165. g = ig.Graph(0,directed=True)
  1166. for node in mod.vs:
  1167. if not node['$type'].find('Place') == -1 or not node['$type'].find('Transition') == -1:
  1168. g.add_vertices(1)
  1169. index = g.vcount()-1
  1170. oldtonew[node.index]=index
  1171. g.vs[index]['name'] = node['name']
  1172. if not node['$type'].find('Place') == -1:
  1173. g.vs[index]['type'] = 'P'
  1174. g.vs[index]['nbTokens'] = node['nbTokens']
  1175. elif not node['$type'].find('Transition') == -1:
  1176. g.vs[index]['type'] = 'T'
  1177. g.vs[index]['fusion'] = node['fusion']
  1178. elif not node['$type'].find('P2T') == -1:
  1179. node['type'] = 'P2T'
  1180. elif not node['$type'].find('T2P') == -1:
  1181. node['type'] = 'T2P'
  1182. #Let's connect
  1183. P2T = mod.vs.select(type_eq = 'P2T')
  1184. T2P = mod.vs.select(type_eq = 'T2P')
  1185. for p2t in P2T:
  1186. to = mod.successors(p2t.index)
  1187. fr = mod.predecessors(p2t.index)
  1188. try:
  1189. p2tid = g.get_eid(oldtonew[fr[0]],oldtonew[to[0]])
  1190. except:
  1191. g.add_edges([(oldtonew[fr[0]],oldtonew[to[0]])])
  1192. p2tid = g.get_eid(oldtonew[fr[0]],oldtonew[to[0]])
  1193. g.es[p2tid]['weight'] = p2t['weight']
  1194. else:
  1195. old = int(g.es[p2tid]['weight'])
  1196. g.es[p2tid]['weight'] = old + int(p2t['weight'])
  1197. for t2p in T2P:
  1198. to = mod.successors(t2p.index)
  1199. fr = mod.predecessors(t2p.index)
  1200. try:
  1201. t2pid = g.get_eid(oldtonew[fr[0]],oldtonew[to[0]])
  1202. except:
  1203. g.add_edges([(oldtonew[fr[0]],oldtonew[to[0]])])
  1204. t2pid = g.get_eid(oldtonew[fr[0]],oldtonew[to[0]])
  1205. g.es[t2pid]['weight'] = t2p['weight']
  1206. else:
  1207. old = int(g.es[t2pid]['weight'])
  1208. g.es[t2pid]['weight'] = old + int(t2p['weight'])
  1209. #dot graph of our petri net, not quite himesis.
  1210. #self.graphPN('pn', g)
  1211. return g
  1212. def isReachableFlat(self,state,key=None):
  1213. if not key:
  1214. if self.modules.values()[0].reachable(state):
  1215. return True
  1216. else:
  1217. return False
  1218. else:
  1219. if self.modules[key].reachable(state):
  1220. return True
  1221. else:
  1222. return False
  1223. def reachabilityTestModular(self):
  1224. aa = 'a'
  1225. bb = 'b'
  1226. moda = {}
  1227. modb = {}
  1228. moda['a2'] = 1
  1229. #moda['a4'] = 4
  1230. #moda['a3'] = 1
  1231. modb['b1'] = 1
  1232. modb['b3'] = 1
  1233. statea = []
  1234. stateb = []
  1235. statea.append(moda)
  1236. stateb.append(modb)
  1237. if not self.isReachableFlat(statea,aa):
  1238. print 'Modular state %s%s not reachable'%(statea,stateb)
  1239. return False
  1240. if not self.isReachableFlat(stateb,bb):
  1241. print 'Modular state %s%s not reachable'%(statea,stateb)
  1242. return False
  1243. scca = self.modules[aa].reachableMod(statea)
  1244. print 'A SCC of ancestors %s'%scca
  1245. sccb = self.modules[bb].reachableMod(stateb)
  1246. print 'B SCC of ancestors %s'%sccb
  1247. result = list( list(itertools.product(scca,sccb)))
  1248. for node in result:
  1249. v = []
  1250. a = 'a-%d'%node[0]
  1251. b = 'b-%d'%node[1]
  1252. v.append(a)
  1253. v.append(b)
  1254. id = self.sg.statePresentReach(v)
  1255. if not id == -1:
  1256. print 'Modular state %s%s reachable'%(statea,stateb)
  1257. return True
  1258. print 'Modular state %s%s not reachable'%(statea,stateb)
  1259. return False
  1260. def reachabilityTestFlat(self):
  1261. moda = {}
  1262. modb = {}
  1263. moda['a1'] = 1
  1264. moda['a4'] = 2
  1265. #moda['a3'] = 1
  1266. #modb['b3'] = 2
  1267. modb['b5'] = 3
  1268. state = []
  1269. state.append(moda)
  1270. state.append(modb)
  1271. if self.isReachableFlat(state):
  1272. print 'Flat state %s reachable'%state
  1273. else:
  1274. print 'Flat state %s not reachable'%state
  1275. def graph(self,key,g):
  1276. vattr=''
  1277. eattr = ''
  1278. nodes = {}
  1279. graph = pydot.Dot(key, graph_type='digraph')
  1280. dateTag = datetime.datetime.now().strftime("%Y-%b-%d_%H-%M-%S")
  1281. for v in g.vs:
  1282. vattr +='('
  1283. i = len(v['M'])
  1284. for key,value in v['M'].items():
  1285. vattr += '%s-%s'%(key,value)
  1286. if not i-1 == 0:
  1287. vattr+=','
  1288. i -=1
  1289. vattr +=')'
  1290. nodes[v.index] = pydot.Node(vattr)
  1291. graph.add_node(nodes[v.index])
  1292. vattr = ''
  1293. for e in g.es:
  1294. graph.add_edge(pydot.Edge(nodes[e.source],nodes[e.target],label=e['T']))
  1295. graph.write_svg('graphs/STATE%s%s.svg'%(key,dateTag))
  1296. #graph.write_png('graphs/STATE%s%s.png'%(key,dateTag))
  1297. #use this one to output your PN net in a svg graph to analyze structure
  1298. #and verify that compilation from Himesis to PN went fine, since we collaps
  1299. #repeated edges.
  1300. def graphPN(self,key,g):
  1301. vattr=''
  1302. eattr = ''
  1303. nodes = {}
  1304. graph = pydot.Dot(key, graph_type='digraph')
  1305. dateTag = datetime.datetime.now().strftime("%Y-%b-%d_%H-%M-%S")
  1306. for v in g.vs:
  1307. for at in v.attributes():
  1308. if not v[at] == None:
  1309. vattr += '%s->%s\n'%(at,v[at])
  1310. nodes[v.index] = pydot.Node(vattr)
  1311. graph.add_node(nodes[v.index])
  1312. vattr = ''
  1313. for e in g.es:
  1314. graph.add_edge(pydot.Edge(nodes[e.source],nodes[e.target],label=e['weight']))
  1315. graph.write_svg('graphs/PN%s%s.svg'%(key,dateTag))
  1316. '''