onelab.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. """
  2. ONELAB - Copyright (C) 2011-2024 Universite de Liege - Universite catholique
  3. de Louvain
  4. Permission is hereby granted, free of charge, to any person obtaining a copy of
  5. this software and associated documentation files (the "Software"), to deal in
  6. the Software without restriction, including without limitation the rights to
  7. use, copy, modify, merge, publish, distribute, and/or sell copies of the
  8. Software, and to permit persons to whom the Software is furnished to do so,
  9. provided that the above copyright notice(s) and this permission notice appear in
  10. all copies of the Software and that both the above copyright notice(s) and this
  11. permission notice appear in supporting documentation.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  14. FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT
  15. SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY
  16. CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
  17. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
  18. CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  19. WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  20. """
  21. #!/usr/bin/env python
  22. import socket, struct, os, sys, subprocess, time
  23. _VERSION = '1.3'
  24. def path(dirname, inp):
  25. # dirname is a directory, can be empty
  26. # inp is an optional file or subdirectory name
  27. # returns the path to 'inp' in the same directory as 'ref'
  28. if dirname:
  29. dirname = os.path.dirname(dirname + os.sep)
  30. if not inp:
  31. return dirname
  32. if inp[0] == '/' or inp[0] == '\\' or (len(inp) > 2 and inp[1] == '\:'):
  33. return inp # do nothing, inp is an absolute path
  34. if inp[0] == '.' :
  35. inp = inp[2:] # cut off heading './' or '.\'
  36. if dirname:
  37. return dirname + os.sep + inp # append inp to the path of the reference file
  38. else:
  39. return inp
  40. class _parameter() :
  41. _membersbase = [
  42. ('name', 'string'), ('label', 'string', ''), ('help', 'string', ''),
  43. ('changedValue', 'int', 31), ('visible', 'int', 1), ('readOnly', 'int', 0),
  44. ('attributes', ('dict', 'string', 'string'), {}),
  45. ('clients', ('dict', 'string', 'int'), {})
  46. ]
  47. _members = {
  48. 'string' : _membersbase + [
  49. ('values', ('list', 'string'), ['']), ('kind', 'string', 'generic'),
  50. ('choices', ('list', 'string'), [])
  51. ],
  52. 'number' : _membersbase + [
  53. ('values', ('list', 'float'), [0.]),
  54. ('min', 'float', -sys.float_info.max), ('max', 'float', sys.float_info.max),
  55. ('step', 'float', 0.), ('index', 'int', -1), ('choices', ('list', 'float'), []),
  56. ('labels', ('dict', 'float', 'string'), {})
  57. ]
  58. }
  59. def __init__(self, type, **values) :
  60. self.type = type
  61. for i in _parameter._members[self.type] :
  62. setattr(self, i[0], values[i[0]] if i[0] in values else i[2])
  63. def tochar(self) :
  64. def tocharitem(l, t, v) :
  65. if t == 'string' : l.append(v)
  66. elif t =='int': l.append(str(v))
  67. elif t == 'float' : l.append('%.16g' % v)
  68. elif t[0] == 'list' :
  69. l.append(str(len(v)))
  70. for i in v : tocharitem(l, t[1], i)
  71. elif t[0] == 'dict' :
  72. l.append(str(len(v)))
  73. for i, j in v.items() :
  74. tocharitem(l, t[1], i)
  75. tocharitem(l, t[2], j)
  76. msg = [_VERSION, self.type]
  77. for i in _parameter._members[self.type] :
  78. tocharitem(msg, i[1], getattr(self, i[0]))
  79. return '\0'.join(msg)
  80. def fromchar(self, msg) :
  81. def fromcharitem(l, t) :
  82. if t == 'string' : return l.pop()
  83. elif t =='int': return int(l.pop())
  84. elif t == 'float' : return float(l.pop())
  85. elif t[0] == 'list' : return [fromcharitem(l, t[1]) for i in range(int(l.pop()))]
  86. elif t[0] == 'dict' : return dict([(fromcharitem(l, t[1]),fromcharitem(l, t[2]))
  87. for i in range(int(l.pop()))])
  88. l = msg.split('\0')
  89. l.reverse()
  90. if l.pop() != _VERSION :
  91. print('onelab version mismatch')
  92. if l.pop() != self.type :
  93. print('onelab parameter type mismatch')
  94. for p in _parameter._members[self.type]:
  95. setattr(self, p[0], fromcharitem(l, p[1]))
  96. return self
  97. def modify(self, **param) :
  98. ## updates the parameter with the content of param, attributes are merged
  99. for i in _parameter._members[self.type] :
  100. if i[0] in param :
  101. if i[0] == 'attributes' :
  102. self.attributes.update(param['attributes'])
  103. else :
  104. setattr(self, i[0], param[i[0]])
  105. class client :
  106. _GMSH_START = 1
  107. _GMSH_STOP = 2
  108. _GMSH_INFO = 10
  109. _GMSH_WARNING = 11
  110. _GMSH_ERROR = 12
  111. _GMSH_PROGRESS = 13
  112. _GMSH_MERGE_FILE = 20
  113. _GMSH_PARSE_STRING = 21
  114. _GMSH_PARAMETER = 23
  115. _GMSH_PARAMETER_QUERY = 24
  116. _GMSH_PARAMETER_QUERY_ALL = 25
  117. _GMSH_PARAMETER_QUERY_END = 26
  118. _GMSH_CONNECT = 27
  119. _GMSH_OLPARSE = 28
  120. _GMSH_PARAMETER_NOT_FOUND = 29
  121. _GMSH_PARAMETER_CLEAR = 31
  122. _GMSH_PARAMETER_UPDATE = 32
  123. _GMSH_OPEN_PROJECT = 33
  124. _GMSH_CLIENT_CHANGED = 34
  125. def _createSocket(self) :
  126. addr = self.addr
  127. if '/' in addr or '\\' in addr or ':' not in addr :
  128. self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  129. self.socket.connect(addr)
  130. else :
  131. self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  132. s = addr.split(':')
  133. self.socket.connect((s[0], int(s[1])))
  134. def _receive(self) :
  135. def buffered_receive(l) :
  136. msg = b''
  137. while len(msg) < l:
  138. chunk = self.socket.recv(l - len(msg))
  139. if not chunk :
  140. RuntimeError('onelab socket closed')
  141. msg += chunk
  142. return msg
  143. msg = buffered_receive(struct.calcsize('ii'))
  144. t, l = struct.unpack('ii', msg)
  145. msg = buffered_receive(l).decode('utf-8')
  146. if t == self._GMSH_INFO :
  147. print('onelab info : %s' % msg)
  148. return t, msg
  149. def _send(self, t, msg) :
  150. if not self.socket :
  151. return
  152. m = msg.encode('utf-8')
  153. try:
  154. if self.socket.send(struct.pack('ii%is' %len(m), t, len(m), m)) == 0 :
  155. RuntimeError('onelab socket closed')
  156. except socket.error:
  157. self.socket.close()
  158. self._createSocket()
  159. self.socket.send(struct.pack('ii%is' %len(m), t, len(m), m))
  160. def _defineParameter(self, p) :
  161. if not self.socket :
  162. return p.values
  163. self._send(self._GMSH_PARAMETER_QUERY, p.tochar())
  164. (t, msg) = self._receive()
  165. if t == self._GMSH_PARAMETER :
  166. self._send(self._GMSH_PARAMETER_UPDATE, p.tochar())
  167. return p.fromchar(msg).values
  168. elif t == self._GMSH_PARAMETER_NOT_FOUND :
  169. self._send(self._GMSH_PARAMETER, p.tochar())
  170. return p.values
  171. def _getParameter(self, param, warn_if_not_found=True) :
  172. if not self.socket :
  173. return
  174. self._send(self._GMSH_PARAMETER_QUERY, param.tochar())
  175. (t, msg) = self._receive()
  176. if t == self._GMSH_PARAMETER :
  177. param.fromchar(msg)
  178. elif t == self._GMSH_PARAMETER_NOT_FOUND and warn_if_not_found :
  179. print ('Unknown parameter %s' %(param.name))
  180. def _getAllParameters(self, type, lst) :
  181. if not self.socket :
  182. return
  183. self._send(self._GMSH_PARAMETER_QUERY_ALL,
  184. _parameter(type, name='dummy').tochar())
  185. (t, msg) = self._receive()
  186. while t == self._GMSH_PARAMETER_QUERY_ALL:
  187. lst.append(_parameter(type, name='dummy').fromchar(msg))
  188. (t, msg) = self._receive()
  189. def defineNumber(self, name, **param):
  190. if 'value' in param :
  191. param["values"] = [param["value"]]
  192. del param["value"]
  193. if 'labels' in param :
  194. param["choices"] = param["labels"].keys()
  195. p = _parameter('number', name=name, **param)
  196. values = self._defineParameter(p)
  197. return values[0] if len(values) else 0
  198. def defineString(self, name, **param):
  199. if 'value' in param :
  200. param["values"] = [param["value"]]
  201. del param["value"]
  202. p = _parameter('string', name=name, **param)
  203. values = self._defineParameter(p)
  204. return values[0] if len(values) else ''
  205. def setNumber(self, name, **param):
  206. if not self.socket :
  207. return
  208. if 'value' in param :
  209. param["values"] = [param["value"]]
  210. del param["value"]
  211. p = _parameter('number', name=name)
  212. self._send(self._GMSH_PARAMETER_QUERY, p.tochar())
  213. (t, msg) = self._receive()
  214. if t == self._GMSH_PARAMETER :
  215. p.fromchar(msg).modify(**param)
  216. elif t == self._GMSH_PARAMETER_NOT_FOUND :
  217. p.modify(**param)
  218. self._send(self._GMSH_PARAMETER, p.tochar())
  219. def setString(self, name, **param):
  220. if not self.socket :
  221. return
  222. if 'value' in param :
  223. param["values"] = [param["value"]]
  224. del param["value"]
  225. p = _parameter('string', name=name)
  226. self._send(self._GMSH_PARAMETER_QUERY, p.tochar())
  227. (t, msg) = self._receive()
  228. if t == self._GMSH_PARAMETER : #modify an existing parameter
  229. p.fromchar(msg).modify(**param)
  230. elif t == self._GMSH_PARAMETER_NOT_FOUND : #create a new parameter
  231. p.modify(**param)
  232. self._send(self._GMSH_PARAMETER, p.tochar())
  233. def clear(self, name) :
  234. if not self.socket :
  235. return
  236. self._send(self._GMSH_PARAMETER_CLEAR, str(name))
  237. def _setNumberChoices(self, name, val):
  238. if not self.socket :
  239. return
  240. p = _parameter('number', name=name)
  241. self._send(self._GMSH_PARAMETER_QUERY, p.tochar())
  242. (t, msg) = self._receive()
  243. if t == self._GMSH_PARAMETER :
  244. if len(val) : # add new choices
  245. p.fromchar(msg).values = val
  246. p.choices.extend(val)
  247. else : # reset choices list
  248. p.fromchar(msg).choices = ()
  249. elif t == self._GMSH_PARAMETER_NOT_FOUND :
  250. print ('Unknown parameter %s' %(param.name))
  251. self._send(self._GMSH_PARAMETER, p.tochar())
  252. def resetNumberChoices(self, name):
  253. self._setNumberChoices(name,[])
  254. def addNumberChoice(self, name, value):
  255. self._setNumberChoices(name,[value])
  256. def getNumber(self, name, warn_if_not_found=True):
  257. param = _parameter('number', name=name)
  258. self._getParameter(param, warn_if_not_found)
  259. return param.values[0] if len(param.values) else 0
  260. def getNumbers(self, name, warn_if_not_found=True):
  261. param = _parameter('number', name=name)
  262. self._getParameter(param, warn_if_not_found)
  263. return param.values
  264. def getString(self, name, warn_if_not_found=True):
  265. param = _parameter('string', name=name)
  266. self._getParameter(param, warn_if_not_found)
  267. return param.values[0] if len(param.values) else ''
  268. def getStrings(self, name, warn_if_not_found=True):
  269. param = _parameter('string', name=name)
  270. self._getParameter(param, warn_if_not_found)
  271. return param.values
  272. def getAllParameters(self):
  273. lst = []
  274. self._getAllParameters('number', lst)
  275. self._getAllParameters('string', lst)
  276. dic = {}
  277. for p in lst:
  278. dic[p.name] = {a[0]: getattr(p, a[0])
  279. for a in _parameter._members[p.type]}
  280. return dic
  281. def getNumberChoices(self, name, warn_if_not_found=True):
  282. param = _parameter('number', name=name)
  283. self._getParameter(param, warn_if_not_found)
  284. return param.choices
  285. def getStringChoices(self, name, warn_if_not_found=True):
  286. param = _parameter('string', name=name)
  287. self._getParameter(param, warn_if_not_found)
  288. return param.choices
  289. def getNumberRange(self, name, warn_if_not_found=True):
  290. param = _parameter('number', name=name)
  291. self._getParameter(param, warn_if_not_found)
  292. return [param.values[0] if len(param.values) else 0, param.min, param.max]
  293. def show(self, name) :
  294. if not self.socket or not name:
  295. return
  296. param = _parameter('number', name=name)
  297. self._send(self._GMSH_PARAMETER_QUERY, param.tochar())
  298. (t, msg) = self._receive()
  299. if t == self._GMSH_PARAMETER :
  300. print (msg.replace('\0','|'))
  301. elif t == self._GMSH_PARAMETER_NOT_FOUND :
  302. param = _parameter('string', name=name)
  303. self._send(self._GMSH_PARAMETER_QUERY, param.tochar())
  304. (t, msg) = self._receive()
  305. if t == self._GMSH_PARAMETER :
  306. print (msg.replace('\0','|'))
  307. elif t == self._GMSH_PARAMETER_NOT_FOUND :
  308. print('Unknown parameter %s' %(name))
  309. def sendCommand(self, command) :
  310. if not self.socket :
  311. return
  312. self._send(self._GMSH_PARSE_STRING, command)
  313. def mergeFile(self, filename) :
  314. if not self.socket or not filename :
  315. return
  316. self._send(self._GMSH_MERGE_FILE, filename)
  317. def openProject(self, filename) :
  318. if not self.socket or not filename :
  319. return
  320. self._send(self._GMSH_OPEN_PROJECT, filename)
  321. def sendInfo(self, msg) :
  322. if not self.socket :
  323. print (msg)
  324. return
  325. self._send(self._GMSH_INFO, str(msg))
  326. def sendWarning(self, msg) :
  327. if not self.socket :
  328. print (msg)
  329. return
  330. self._send(self._GMSH_WARNING, str(msg))
  331. def sendError(self, msg) :
  332. if not self.socket :
  333. print (msg)
  334. return
  335. self._send(self._GMSH_ERROR, str(msg))
  336. def preProcess(self, name, filename) :
  337. if not self.socket :
  338. return
  339. msg = [name, filename]
  340. self._send(self._GMSH_OLPARSE, '\0'.join(msg))
  341. (t, msg) = self._receive()
  342. if t == self._GMSH_OLPARSE :
  343. if msg == "true" :
  344. return True
  345. return False
  346. def isChanged(self, name) :
  347. if not self.socket :
  348. return
  349. msg = ["get", name]
  350. self._send(self._GMSH_CLIENT_CHANGED, '\0'.join(msg))
  351. (t, msg) = self._receive()
  352. if t == self._GMSH_CLIENT_CHANGED :
  353. if msg == "true" :
  354. return True
  355. return False
  356. def setChanged(self, name, changed) :
  357. if not self.socket :
  358. return
  359. msg = ["set", name, 'true' if changed else 'false']
  360. self._send(self._GMSH_CLIENT_CHANGED, '\0'.join(msg))
  361. def waitOnSubClients(self):
  362. if not self.socket :
  363. return
  364. while self._numSubClients > 0:
  365. (t, msg) = self._receive()
  366. if t == self._GMSH_STOP :
  367. self._numSubClients -= 1
  368. def runNonBlockingSubClient(self, name, command, arguments=''):
  369. if self.action == 'check':
  370. cmd = command
  371. else:
  372. cmd = command + ' ' + arguments
  373. if not self.socket :
  374. return os.system(cmd);
  375. msg = [name, cmd]
  376. self._send(self._GMSH_CONNECT, '\0'.join(msg))
  377. self._numSubClients +=1
  378. def runSubClient(self, name, command, arguments=''):
  379. self.runNonBlockingSubClient(name, command, arguments)
  380. self.waitOnSubClients() # makes the subclient blocking
  381. if self.action == 'compute':
  382. self.setChanged(name, False)
  383. def run(self, name, command, arguments=''):
  384. self.runSubClient(name, command, arguments)
  385. def __init__(self, ref=''):
  386. self.socket = None
  387. self.name = ""
  388. self.addr = ""
  389. self.wdir = os.path.dirname(ref)
  390. self._numSubClients = 0
  391. for i, v in enumerate(sys.argv) :
  392. if v == '-onelab':
  393. self.name = sys.argv[i + 1]
  394. self.addr = sys.argv[i + 2]
  395. self._createSocket()
  396. self._send(self._GMSH_START, str(os.getpid()))
  397. self.action = self.getString(self.name + '/Action', False)
  398. self.setNumber('IsPyMetamodel',values=[1],visible=0)
  399. self.loop = self.getNumber('0Metamodel/Loop', warn_if_not_found=False)
  400. self.batch = self.getNumber('0Metamodel/Batch', warn_if_not_found=False)
  401. self.sendInfo("Performing OneLab '" + self.action + "'")
  402. if self.action == "initialize":
  403. self.finalize()
  404. exit(0)
  405. def finalize(self):
  406. # code aster python interpreter does not call the destructor at exit, it is
  407. # necessary to call finalize() epxlicitely
  408. if self.socket :
  409. self.waitOnSubClients()
  410. self._send(self._GMSH_STOP, 'Goodbye!')
  411. self.socket.close()
  412. self.socket = None
  413. def __del__(self):
  414. self.finalize()
  415. def call(self, name, cmdline, remote='', rundir='', logfile='', poll=0):
  416. cwd = None
  417. if not remote :
  418. argv = cmdline.rsplit(' ')
  419. if rundir :
  420. cwd = rundir
  421. else :
  422. argv=['ssh', remote , "cd %s ; %s" %(rundir,cmdline) ]
  423. if poll and not logfile :
  424. logfile = os.devnull
  425. if logfile:
  426. call = subprocess.Popen(argv, bufsize=1, cwd=cwd,
  427. stdout=open(logfile,"w"),
  428. stderr=subprocess.STDOUT)
  429. while call.poll() == None :
  430. self.action = self.getString(self.name + '/Action', False)
  431. if self.action == 'stop':
  432. call.terminate()
  433. self._send(self._GMSH_WARNING, 'client killed')
  434. sys.exit(1)
  435. time.sleep(1) # check every second for the stop signal from Gmsh
  436. else:
  437. call = subprocess.Popen(argv, bufsize=1, cwd=cwd,
  438. stdout=subprocess.PIPE,
  439. stderr=subprocess.STDOUT)
  440. count = 0
  441. for line in iter(call.stdout.readline, b''):
  442. print(line.rstrip())
  443. count += 1
  444. if count == 50 : # check every 50 lines for the stop signal from Gmsh
  445. count = 0
  446. self.action = self.getString(self.name + '/Action', False)
  447. if self.action == 'stop':
  448. call.terminate()
  449. self._send(self._GMSH_WARNING, 'client killed')
  450. sys.exit(1)
  451. result = call.wait()
  452. if result == 0 :
  453. self._send(self._GMSH_INFO, 'done \"' + ' '.join(argv) + '\"')
  454. if self.action == 'compute':
  455. self.setChanged(name, False)
  456. else :
  457. self._send(self._GMSH_ERROR, 'error \"' + ' '.join(argv) + '\"')
  458. sys.exit(1)
  459. def copy(self, here, there):
  460. os.system('cp '+ here + ' ' + there)
  461. def upload(self, here, there, remote='') :
  462. if not here or not there :
  463. return
  464. if remote :
  465. argv=['rsync','-e','ssh','-auv', here, remote + ':' + there]
  466. else :
  467. argv=['cp','-f', here, there]
  468. call = subprocess.Popen(argv, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
  469. result = call.wait()
  470. if result == 0 :
  471. self._send(self._GMSH_INFO, 'upload: ' + ' '.join(argv))
  472. else :
  473. print(call.stderr.read())
  474. def download(self, there, here, remote='') :
  475. if not here or not there :
  476. return
  477. if remote :
  478. argv=['rsync','-e','ssh','-auv', remote + ':' + there, here]
  479. else :
  480. argv=['cp','-f', there, here]
  481. call = subprocess.Popen(argv, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
  482. result = call.wait()
  483. if result == 0 :
  484. self._send(self._GMSH_INFO, 'download: ' + ' '.join(argv))
  485. else :
  486. print(call.stderr.read())
  487. def getPath(self, inp='') :
  488. return path(self.wdir, inp)
  489. def fileExists(self, p) :
  490. return os.path.exists(p)
  491. def checkFile(self, p) :
  492. if not self.fileExists(p):
  493. self.sendError('path error: %s' %(p))
  494. exit(0)
  495. return True
  496. def checkPath(self, inp='') :
  497. p = path(self.wdir,inp)
  498. self.checkFile(p)
  499. return p
  500. def solutionFiles(self, client, list) :
  501. self.defineNumber('0Metamodel/9Use restored solution', values=[0], choices=[0,1])
  502. self.defineString('0Metamodel/9Tag', values=[''])
  503. if list :
  504. if self.getNumber('0Metamodel/9Use restored solution') :
  505. solFiles = self.getStringChoices('0Metamodel/9Solution files')
  506. for i in solFiles:
  507. self.checkFile(i)
  508. else :
  509. solFiles = list
  510. self.setString('0Metamodel/9Solution files', values=[solFiles[0]],
  511. choices=solFiles, readOnly=1)
  512. for i in solFiles:
  513. if not self.fileExists(i) :
  514. self.setChanged(client, 'true')
  515. return solFiles
  516. def needsCompute(self, client) :
  517. # Avoid recomputation when a database with restored solutions has just been loaded
  518. # Otherwise, stop using restored solutions when the client elmer has changed
  519. if self.useRestoredSolution() == 2: # we have just loaded a database
  520. self.setRestoredSolution(1)
  521. self.setChanged(client, 'false') # do not compute
  522. else :
  523. if self.isChanged(client):
  524. self.setRestoredSolution(0)
  525. return True
  526. return False
  527. def willCompute(self, client) : # Inform user about the value of needsCompute
  528. if self.useRestoredSolution() == 2: # special value
  529. return False
  530. else :
  531. return True if self.isChanged(client) else False
  532. def useRestoredSolution(self) :
  533. return self.getNumber('0Metamodel/9Use restored solution')
  534. def setRestoredSolution(self, val) :
  535. self.setNumber('0Metamodel/9Use restored solution', values=[val])
  536. def outputFiles(self, list) :
  537. if list :
  538. self.setString('0Metamodel/9Output files', values=[list[0]],
  539. choices=list, visible=1)
  540. # tool to extract the (i, j)th element in an array file
  541. # from rlcompleter import readline
  542. def extract(filename,i,j):
  543. input = open(filename,'r')
  544. all_lines = input.readlines()
  545. input.close()
  546. if i == -1:
  547. i = len(all_lines) # last line
  548. items = all_lines[i-1].split()
  549. return float(items[j-1])