scipion-pyworkflow 3.10.5__py3-none-any.whl → 3.11.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (127) hide show
  1. pyworkflow/config.py +131 -67
  2. pyworkflow/constants.py +12 -2
  3. pyworkflow/object.py +3 -2
  4. pyworkflow/plugin.py +93 -44
  5. pyworkflow/project/scripts/fix_links.py +4 -1
  6. pyworkflow/resources/showj/arrowDown.png +0 -0
  7. pyworkflow/resources/showj/arrowUp.png +0 -0
  8. pyworkflow/resources/showj/background_section.png +0 -0
  9. pyworkflow/resources/showj/colRowModeOff.png +0 -0
  10. pyworkflow/resources/showj/colRowModeOn.png +0 -0
  11. pyworkflow/resources/showj/delete.png +0 -0
  12. pyworkflow/resources/showj/doc_icon.png +0 -0
  13. pyworkflow/resources/showj/download_icon.png +0 -0
  14. pyworkflow/resources/showj/enabled_gallery.png +0 -0
  15. pyworkflow/resources/showj/galleryViewOff.png +0 -0
  16. pyworkflow/resources/showj/galleryViewOn.png +0 -0
  17. pyworkflow/resources/showj/goto.png +0 -0
  18. pyworkflow/resources/showj/menu.png +0 -0
  19. pyworkflow/resources/showj/separator.png +0 -0
  20. pyworkflow/resources/showj/tableViewOff.png +0 -0
  21. pyworkflow/resources/showj/tableViewOn.png +0 -0
  22. pyworkflow/resources/showj/ui-bg_glass_75_e6e6e6_1x400.png +0 -0
  23. pyworkflow/resources/showj/ui-bg_glass_95_fef1ec_1x400.png +0 -0
  24. pyworkflow/resources/showj/ui-bg_highlight-soft_75_cccccc_1x100.png +0 -0
  25. pyworkflow/resources/showj/volumeOff.png +0 -0
  26. pyworkflow/resources/showj/volumeOn.png +0 -0
  27. pyworkflow/viewer.py +23 -1
  28. pyworkflowtests/objects.py +2 -2
  29. pyworkflowtests/protocols.py +1 -3
  30. {scipion_pyworkflow-3.10.5.dist-info → scipion_pyworkflow-3.11.0.dist-info}/METADATA +21 -25
  31. scipion_pyworkflow-3.11.0.dist-info/RECORD +71 -0
  32. {scipion_pyworkflow-3.10.5.dist-info → scipion_pyworkflow-3.11.0.dist-info}/WHEEL +1 -1
  33. scipion_pyworkflow-3.11.0.dist-info/entry_points.txt +2 -0
  34. pyworkflow/apps/__init__.py +0 -29
  35. pyworkflow/apps/pw_manager.py +0 -37
  36. pyworkflow/apps/pw_plot.py +0 -51
  37. pyworkflow/apps/pw_project.py +0 -113
  38. pyworkflow/apps/pw_protocol_list.py +0 -143
  39. pyworkflow/apps/pw_protocol_run.py +0 -51
  40. pyworkflow/apps/pw_run_tests.py +0 -267
  41. pyworkflow/apps/pw_schedule_run.py +0 -322
  42. pyworkflow/apps/pw_sleep.py +0 -37
  43. pyworkflow/apps/pw_sync_data.py +0 -439
  44. pyworkflow/apps/pw_viewer.py +0 -78
  45. pyworkflow/gui/__init__.py +0 -36
  46. pyworkflow/gui/browser.py +0 -726
  47. pyworkflow/gui/canvas.py +0 -1190
  48. pyworkflow/gui/dialog.py +0 -977
  49. pyworkflow/gui/form.py +0 -2637
  50. pyworkflow/gui/graph.py +0 -247
  51. pyworkflow/gui/graph_layout.py +0 -271
  52. pyworkflow/gui/gui.py +0 -566
  53. pyworkflow/gui/matplotlib_image.py +0 -233
  54. pyworkflow/gui/plotter.py +0 -247
  55. pyworkflow/gui/project/__init__.py +0 -25
  56. pyworkflow/gui/project/base.py +0 -192
  57. pyworkflow/gui/project/constants.py +0 -139
  58. pyworkflow/gui/project/labels.py +0 -205
  59. pyworkflow/gui/project/project.py +0 -492
  60. pyworkflow/gui/project/searchprotocol.py +0 -154
  61. pyworkflow/gui/project/searchrun.py +0 -181
  62. pyworkflow/gui/project/steps.py +0 -171
  63. pyworkflow/gui/project/utils.py +0 -332
  64. pyworkflow/gui/project/variables.py +0 -179
  65. pyworkflow/gui/project/viewdata.py +0 -472
  66. pyworkflow/gui/project/viewprojects.py +0 -510
  67. pyworkflow/gui/project/viewprotocols.py +0 -2093
  68. pyworkflow/gui/project/viewprotocols_extra.py +0 -560
  69. pyworkflow/gui/text.py +0 -771
  70. pyworkflow/gui/tooltip.py +0 -185
  71. pyworkflow/gui/tree.py +0 -684
  72. pyworkflow/gui/widgets.py +0 -307
  73. pyworkflow/mapper/__init__.py +0 -26
  74. pyworkflow/mapper/mapper.py +0 -222
  75. pyworkflow/mapper/sqlite.py +0 -1578
  76. pyworkflow/mapper/sqlite_db.py +0 -145
  77. pyworkflow/project/__init__.py +0 -31
  78. pyworkflow/project/config.py +0 -454
  79. pyworkflow/project/manager.py +0 -180
  80. pyworkflow/project/project.py +0 -2010
  81. pyworkflow/protocol/__init__.py +0 -38
  82. pyworkflow/protocol/bibtex.py +0 -48
  83. pyworkflow/protocol/constants.py +0 -87
  84. pyworkflow/protocol/executor.py +0 -455
  85. pyworkflow/protocol/hosts.py +0 -313
  86. pyworkflow/protocol/launch.py +0 -270
  87. pyworkflow/protocol/package.py +0 -42
  88. pyworkflow/protocol/params.py +0 -741
  89. pyworkflow/protocol/protocol.py +0 -2582
  90. pyworkflow/tests/__init__.py +0 -29
  91. pyworkflow/tests/test_utils.py +0 -25
  92. pyworkflow/tests/tests.py +0 -341
  93. pyworkflow/utils/__init__.py +0 -38
  94. pyworkflow/utils/dataset.py +0 -414
  95. pyworkflow/utils/echo.py +0 -104
  96. pyworkflow/utils/graph.py +0 -169
  97. pyworkflow/utils/log.py +0 -284
  98. pyworkflow/utils/path.py +0 -528
  99. pyworkflow/utils/process.py +0 -132
  100. pyworkflow/utils/profiler.py +0 -92
  101. pyworkflow/utils/progressbar.py +0 -154
  102. pyworkflow/utils/properties.py +0 -631
  103. pyworkflow/utils/reflection.py +0 -129
  104. pyworkflow/utils/utils.py +0 -879
  105. pyworkflow/utils/which.py +0 -229
  106. pyworkflow/webservices/__init__.py +0 -8
  107. pyworkflow/webservices/config.py +0 -11
  108. pyworkflow/webservices/notifier.py +0 -162
  109. pyworkflow/webservices/repository.py +0 -59
  110. pyworkflow/webservices/workflowhub.py +0 -74
  111. pyworkflowtests/tests/__init__.py +0 -0
  112. pyworkflowtests/tests/test_canvas.py +0 -72
  113. pyworkflowtests/tests/test_domain.py +0 -45
  114. pyworkflowtests/tests/test_logs.py +0 -74
  115. pyworkflowtests/tests/test_mappers.py +0 -392
  116. pyworkflowtests/tests/test_object.py +0 -507
  117. pyworkflowtests/tests/test_project.py +0 -42
  118. pyworkflowtests/tests/test_protocol_execution.py +0 -135
  119. pyworkflowtests/tests/test_protocol_export.py +0 -78
  120. pyworkflowtests/tests/test_protocol_output.py +0 -158
  121. pyworkflowtests/tests/test_streaming.py +0 -47
  122. pyworkflowtests/tests/test_utils.py +0 -210
  123. scipion_pyworkflow-3.10.5.dist-info/RECORD +0 -140
  124. scipion_pyworkflow-3.10.5.dist-info/dependency_links.txt +0 -1
  125. scipion_pyworkflow-3.10.5.dist-info/entry_points.txt +0 -5
  126. {scipion_pyworkflow-3.10.5.dist-info → scipion_pyworkflow-3.11.0.dist-info/licenses}/LICENSE.txt +0 -0
  127. {scipion_pyworkflow-3.10.5.dist-info → scipion_pyworkflow-3.11.0.dist-info}/top_level.txt +0 -0
@@ -1,2010 +0,0 @@
1
- #!/usr/bin/env python
2
- # **************************************************************************
3
- # *
4
- # * Authors: J.M. De la Rosa Trevin (delarosatrevin@scilifelab.se) [1]
5
- # *
6
- # * [1] SciLifeLab, Stockholm University
7
- # *
8
- # * This program is free software; you can redistribute it and/or modify
9
- # * it under the terms of the GNU General Public License as published by
10
- # * the Free Software Foundation; either version 3 of the License, or
11
- # * (at your option) any later version.
12
- # *
13
- # * This program is distributed in the hope that it will be useful,
14
- # * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
- # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
- # * GNU General Public License for more details.
17
- # *
18
- # * You should have received a copy of the GNU General Public License
19
- # * along with this program; if not, write to the Free Software
20
- # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21
- # * 02111-1307 USA
22
- # *
23
- # * All comments concerning this program package may be sent to the
24
- # * e-mail address 'scipion@cnb.csic.es'
25
- # *
26
- # **************************************************************************
27
- import logging
28
-
29
- from ..protocol.launch import _checkJobStatus
30
-
31
- ROOT_NODE_NAME = "PROJECT"
32
- logger = logging.getLogger(__name__)
33
- from pyworkflow.utils.log import LoggingConfigurator
34
- import datetime as dt
35
- import json
36
- import os
37
- import re
38
- import time
39
- import traceback
40
- from collections import OrderedDict
41
-
42
- import pyworkflow as pw
43
- from pyworkflow.constants import PROJECT_DBNAME, PROJECT_SETTINGS
44
- import pyworkflow.object as pwobj
45
- import pyworkflow.protocol as pwprot
46
- import pyworkflow.utils as pwutils
47
- from pyworkflow.mapper import SqliteMapper
48
- from pyworkflow.protocol.constants import (MODE_RESTART, MODE_RESUME,
49
- STATUS_INTERACTIVE, ACTIVE_STATUS,
50
- UNKNOWN_JOBID, INITIAL_SLEEP_TIME, STATUS_FINISHED)
51
- from pyworkflow.protocol.protocol import ProtImportBase, Protocol
52
-
53
- from . import config
54
-
55
-
56
- OBJECT_PARENT_ID = pwobj.OBJECT_PARENT_ID
57
- PROJECT_LOGS = 'Logs'
58
- PROJECT_RUNS = 'Runs'
59
- PROJECT_TMP = 'Tmp'
60
- PROJECT_UPLOAD = 'Uploads'
61
- PROJECT_CONFIG = '.config'
62
- PROJECT_CREATION_TIME = 'CreationTime'
63
-
64
- # Regex to get numbering suffix and automatically propose runName
65
- REGEX_NUMBER_ENDING = re.compile(r'(?P<prefix>.+)(?P<number>\(\d*\))\s*$')
66
- REGEX_NUMBER_ENDING_CP = re.compile(r'(?P<prefix>.+\s\(copy)(?P<number>.*)\)\s*$')
67
-
68
-
69
- class Project(object):
70
- """This class will handle all information
71
- related with a Project"""
72
-
73
- @classmethod
74
- def getDbName(cls):
75
- """ Return the name of the database file of projects. """
76
- return PROJECT_DBNAME
77
-
78
- def __init__(self, domain, path):
79
- """
80
- Create a new Project instance.
81
- :param domain: The application domain from where to get objects and
82
- protocols.
83
- :param path: Path where the project will be created/loaded
84
- """
85
- self._domain = domain
86
- self.name = path
87
- self.shortName = os.path.basename(path)
88
- self.path = os.path.abspath(path)
89
- self._isLink = os.path.islink(path)
90
- self._isInReadOnlyFolder = False
91
- self.pathList = [] # Store all related paths
92
- self.dbPath = self.__addPath(PROJECT_DBNAME)
93
- self.logsPath = self.__addPath(PROJECT_LOGS)
94
- self.runsPath = self.__addPath(PROJECT_RUNS)
95
- self.tmpPath = self.__addPath(PROJECT_TMP)
96
- self.uploadPath = self.__addPath(PROJECT_UPLOAD)
97
- self.settingsPath = self.__addPath(PROJECT_SETTINGS)
98
- self.configPath = self.__addPath(PROJECT_CONFIG)
99
- self.runs = None
100
- self._runsGraph = None
101
- self._transformGraph = None
102
- self._sourceGraph = None
103
- self.address = ''
104
- self.port = pwutils.getFreePort()
105
- self.mapper = None
106
- self.settings:config.ProjectSettings = None
107
- # Host configuration
108
- self._hosts = None
109
-
110
- # Creation time should be stored in project.sqlite when the project
111
- # is created and then loaded with other properties from the database
112
- self._creationTime = None
113
-
114
- # Time stamp with the last run has been updated
115
- self._lastRunTime = None
116
-
117
- def getObjId(self):
118
- """ Return the unique id assigned to this project. """
119
- return os.path.basename(self.path)
120
-
121
- def __addPath(self, *paths):
122
- """Store a path needed for the project"""
123
- p = self.getPath(*paths)
124
- self.pathList.append(p)
125
- return p
126
-
127
- def getPath(self, *paths):
128
- """Return path from the project root"""
129
- if paths:
130
- return os.path.join(*paths) # Why this is relative!!
131
- else:
132
- return self.path
133
-
134
- def isLink(self):
135
- """Returns if the project path is a link to another folder."""
136
- return self._isLink
137
-
138
- def getDbPath(self):
139
- """ Return the path to the sqlite db. """
140
- return self.dbPath
141
-
142
- def getDbLastModificationDate(self):
143
- """ Return the last modification date of the database """
144
- pwutils.getFileLastModificationDate(self.getDbPath())
145
-
146
- def getCreationTime(self):
147
- """ Return the time when the project was created. """
148
- # In project.create method, the first object inserted
149
- # in the mapper should be the creation time
150
- return self._creationTime.datetime()
151
-
152
-
153
- def getComment(self):
154
- """ Returns the project comment. Stored as CreationTime comment."""
155
- return self._creationTime.getObjComment()
156
-
157
- def setComment(self, newComment):
158
- """ Sets the project comment """
159
- self._creationTime.setObjComment(newComment)
160
-
161
- def getSettingsCreationTime(self):
162
- return self.settings.getCreationTime()
163
-
164
- def getElapsedTime(self):
165
- """ Returns the time elapsed from the creation to the last
166
- execution time. """
167
- if self._creationTime and self._lastRunTime:
168
- creationTs = self.getCreationTime()
169
- lastRunTs = self._lastRunTime.datetime()
170
- return lastRunTs - creationTs
171
- return None
172
-
173
- def getLeftTime(self):
174
- lifeTime = self.settings.getLifeTime()
175
- if lifeTime:
176
- td = dt.timedelta(hours=lifeTime)
177
- return td - self.getElapsedTime()
178
- else:
179
- return None
180
-
181
- def setDbPath(self, dbPath):
182
- """ Set the project db path.
183
- This function is used when running a protocol where
184
- a project is loaded but using the protocol own sqlite file.
185
- """
186
- # First remove from pathList the old dbPath
187
- self.pathList.remove(self.dbPath)
188
- self.dbPath = os.path.abspath(dbPath)
189
- self.pathList.append(self.dbPath)
190
-
191
- def getName(self):
192
- return self.name
193
-
194
- def getDomain(self):
195
- return self._domain
196
-
197
- # TODO: maybe it has more sense to use this behaviour
198
- # for just getName function...
199
- def getShortName(self):
200
- return self.shortName
201
-
202
- def getTmpPath(self, *paths):
203
- return self.getPath(PROJECT_TMP, *paths)
204
-
205
- def getLogPath(self, *paths):
206
- return self.getPath(PROJECT_LOGS, *paths)
207
-
208
- def getProjectLog(self):
209
- return os.path.join(self.path,self.getLogPath("project.log")) # For some reason getLogsPath is relative!
210
-
211
- def getSettings(self):
212
- return self.settings
213
-
214
- def saveSettings(self):
215
- # Read only mode
216
- if not self.openedAsReadOnly():
217
- self.settings.write()
218
-
219
- def createSettings(self, runsView=1, readOnly=False):
220
- self.settings = config.ProjectSettings()
221
- self.settings.setRunsView(runsView)
222
- self.settings.setReadOnly(readOnly)
223
- self.settings.write(self.settingsPath)
224
- return self.settings
225
-
226
- def createMapper(self, sqliteFn):
227
- """ Create a new SqliteMapper object and pass as classes dict
228
- all globals and update with data and protocols from em.
229
- """
230
- classesDict = pwobj.Dict(default=pwprot.LegacyProtocol)
231
- classesDict.update(self._domain.getMapperDict())
232
- classesDict.update(config.__dict__)
233
- return SqliteMapper(sqliteFn, classesDict)
234
-
235
- def load(self, dbPath=None, hostsConf=None, protocolsConf=None, chdir=True,
236
- loadAllConfig=True):
237
- """
238
- Load project data, configuration and settings.
239
-
240
- :param dbPath: the path to the project database.
241
- If None, use the project.sqlite in the project folder.
242
- :param hostsConf: where to read the host configuration.
243
- If None, check if exists in .config/hosts.conf
244
- or read from ~/.config/scipion/hosts.conf
245
- :param protocolsConf: Not used
246
- :param chdir: If True, os.cwd will be set to project's path.
247
- :param loadAllConfig: If True, settings from settings.sqlite will also be loaded
248
-
249
- """
250
-
251
- if not os.path.exists(self.path):
252
- raise Exception("Cannot load project, path doesn't exist: %s"
253
- % self.path)
254
-
255
- # If folder is read only, flag it and warn about it.
256
- if not os.access(self.path, os.W_OK):
257
- self._isInReadOnlyFolder = True
258
- logger.warning("Project \"%s\": you don't have write permissions "
259
- "for project folder. Loading asd READ-ONLY." % self.shortName)
260
-
261
- if chdir:
262
- os.chdir(self.path) # Before doing nothing go to project dir
263
-
264
- try:
265
- self._loadDb(dbPath)
266
- self._loadHosts(hostsConf)
267
-
268
- if loadAllConfig:
269
-
270
- # FIXME: Handle settings argument here
271
-
272
- # It is possible that settings does not exists if
273
- # we are loading a project after a Project.setDbName,
274
- # used when running protocols
275
- settingsPath = os.path.join(self.path, self.settingsPath)
276
-
277
- logger.debug("settingsPath: %s" % settingsPath)
278
-
279
- if os.path.exists(settingsPath):
280
- self.settings = config.ProjectSettings.load(settingsPath)
281
- else:
282
- logger.info("settings is None")
283
- self.settings = None
284
-
285
- self._loadCreationTime()
286
-
287
- # Catch DB not found exception (when loading a project from a folder
288
- # without project.sqlite
289
- except MissingProjectDbException as noDBe:
290
- # Raise it at before: This is a critical error and should be raised
291
- raise noDBe
292
-
293
- # Catch any less severe exception..to allow at least open the project.
294
- # except Exception as e:
295
- # logger.info("ERROR: Project %s load failed.\n"
296
- # " Message: %s\n" % (self.path, e))
297
-
298
- def configureLogging(self):
299
- LoggingConfigurator.setUpGUILogging(self.getProjectLog())
300
- def _loadCreationTime(self):
301
- # Load creation time, it should be in project.sqlite or
302
- # in some old projects it is found in settings.sqlite
303
-
304
- creationTime = self.mapper.selectBy(name=PROJECT_CREATION_TIME)
305
-
306
- if creationTime: # CreationTime was found in project.sqlite
307
- ctStr = creationTime[0] # This is our String type instance
308
-
309
- # We store it in mem as dateime
310
- self._creationTime = ctStr
311
-
312
- else:
313
- # We should read the creation time from settings.sqlite and
314
- # update the CreationTime in the project.sqlite
315
- self._creationTime = pwobj.String(self.getSettingsCreationTime())
316
- self._storeCreationTime()
317
-
318
- # ---- Helper functions to load different pieces of a project
319
- def _loadDb(self, dbPath):
320
- """ Load the mapper from the sqlite file in dbPath. """
321
- if dbPath is not None:
322
- self.setDbPath(dbPath)
323
-
324
- absDbPath = os.path.join(self.path, self.dbPath)
325
- if not os.path.exists(absDbPath):
326
- raise MissingProjectDbException(
327
- "Project database not found at '%s'" % absDbPath)
328
- self.mapper = self.createMapper(absDbPath)
329
-
330
- def closeMapper(self):
331
- if self.mapper is not None:
332
- self.mapper.close()
333
- self.mapper = None
334
-
335
- def getLocalConfigHosts(self):
336
- """ Return the local file where the project will try to
337
- read the hosts configuration. """
338
- return self.getPath(PROJECT_CONFIG, pw.Config.SCIPION_HOSTS)
339
-
340
- def _loadHosts(self, hosts):
341
- """ Loads hosts configuration from hosts file. """
342
- # If the host file is not passed as argument...
343
- configHosts = pw.Config.SCIPION_HOSTS
344
- projHosts = self.getLocalConfigHosts()
345
-
346
- if hosts is None:
347
- # Try first to read it from the project file .config./hosts.conf
348
- if os.path.exists(projHosts):
349
- hostsFile = projHosts
350
- else:
351
- localDir = os.path.dirname(pw.Config.SCIPION_LOCAL_CONFIG)
352
- hostsFile = os.path.join(localDir, configHosts)
353
- else:
354
- pwutils.copyFile(hosts, projHosts)
355
- hostsFile = hosts
356
-
357
- self._hosts = pwprot.HostConfig.load(hostsFile)
358
-
359
- def getHostNames(self):
360
- """ Return the list of host name in the project. """
361
- return list(self._hosts.keys())
362
-
363
- def getHostConfig(self, hostName):
364
- if hostName in self._hosts:
365
- hostKey = hostName
366
- else:
367
- hostKey = self.getHostNames()[0]
368
- logger.warning("Protocol host '%s' not found." % hostName)
369
- logger.warning(" Using '%s' instead." % hostKey)
370
-
371
- return self._hosts[hostKey]
372
-
373
- def getProtocolView(self):
374
- """ Returns de view selected in the tree when it was persisted"""
375
- return self.settings.getProtocolView()
376
-
377
- def create(self, runsView=1, readOnly=False, hostsConf=None,
378
- protocolsConf=None, comment=None):
379
- """Prepare all required paths and files to create a new project.
380
-
381
- :param runsView: default view to associate the project with
382
- :param readOnly: If True, project will be loaded as read only.
383
- :param hostsConf: Path to the host.conf to be used when executing protocols
384
- :param protocolsConf: Not used.
385
- """
386
- # Create project path if not exists
387
- pwutils.path.makePath(self.path)
388
- os.chdir(self.path) # Before doing nothing go to project dir
389
- self._cleanData()
390
- logger.info("Creating project at %s" % os.path.abspath(self.dbPath))
391
- # Create db through the mapper
392
- self.mapper = self.createMapper(self.dbPath)
393
- # Store creation time
394
- self._creationTime = pwobj.String(dt.datetime.now())
395
- self.setComment(comment)
396
- self._storeCreationTime()
397
- # Load settings from .conf files and write .sqlite
398
- self.settings = self.createSettings(runsView=runsView,
399
- readOnly=readOnly)
400
- # Create other paths inside project
401
- for p in self.pathList:
402
- pwutils.path.makePath(p)
403
-
404
- self._loadHosts(hostsConf)
405
-
406
- def _storeCreationTime(self, new=True):
407
- """ Store the creation time in the project db. """
408
- # Store creation time
409
- self._creationTime.setName(PROJECT_CREATION_TIME)
410
- self.mapper.store(self._creationTime)
411
- self.mapper.commit()
412
-
413
- def _cleanData(self):
414
- """Clean all project data"""
415
- pwutils.path.cleanPath(*self.pathList)
416
-
417
- def _continueWorkflow(self, errorsList, continuedProtList=None):
418
- """
419
- This function continue a workflow from a selected protocol.
420
- The previous results are preserved.
421
- Actions done here are:
422
- 1. if the protocol list exists (for each protocol)
423
- 1.1 if the protocol is not an interactive protocol
424
- 1.1.1. If the protocol is in streaming (CONTINUE ACTION):
425
- - 'dataStreaming' parameter if the protocol is an import
426
- protocol
427
- - check if the __stepsCheck function exist and it's not
428
- the same implementation of the base class
429
- (worksInStreaming function)
430
- 1.1.1.1 Open the protocol sets, store and save them in
431
- the database
432
- 1.1.1.2 Change the protocol status (SAVED)
433
- 1.1.1.3 Schedule the protocol
434
- Else Restart the workflow from that point (RESTART ACTION) if
435
- at least one protocol in streaming has been launched
436
- """
437
- if continuedProtList is not None:
438
- for protocol, level in continuedProtList.values():
439
- if not protocol.isInteractive():
440
- if protocol.isScheduled():
441
- continue
442
-
443
- # streaming ...
444
- if protocol.worksInStreaming() and not protocol.isSaved():
445
- attrSet = [attr for name, attr in
446
- protocol.iterOutputAttributes(pwprot.Set)]
447
- try:
448
- if attrSet:
449
- # Open output sets..
450
- for attr in attrSet:
451
- attr.setStreamState(attr.STREAM_OPEN)
452
- attr.write()
453
- attr.close()
454
- protocol.setStatus(pwprot.STATUS_SAVED)
455
- protocol._updateSteps(lambda step: step.setStatus(pwprot.STATUS_SAVED))
456
- protocol.setMapper(self.createMapper(protocol.getDbPath()))
457
- protocol._store()
458
- self._storeProtocol(protocol)
459
- self.scheduleProtocol(protocol,
460
- initialSleepTime=level*INITIAL_SLEEP_TIME)
461
- except Exception as ex:
462
- errorsList.append("Error trying to launch the "
463
- "protocol: %s\nERROR: %s\n" %
464
- (protocol.getObjLabel(), ex))
465
- break
466
- else:
467
- if level != 0:
468
- # Not in streaming and not the first protocol.
469
- if protocol.isActive():
470
- self.stopProtocol(protocol)
471
- self._restartWorkflow(errorsList,{protocol.getObjId(): (protocol, level)})
472
-
473
- else: # First protocol not in streaming
474
- if not protocol.isActive():
475
- self.scheduleProtocol(protocol)
476
-
477
-
478
-
479
- def _restartWorkflow(self, errorsList, restartedProtList=None):
480
- """
481
- This function restart a workflow from a selected protocol.
482
- All previous results will be deleted
483
- Actions done here are:
484
- 1. Set the protocol run mode (RESTART). All previous results will be
485
- deleted
486
- 2. Schedule the protocol if not is an interactive protocol
487
- 3. For each of the dependents protocols, repeat from step 1
488
- """
489
- if restartedProtList is not None:
490
- for protocol, level in restartedProtList.values():
491
- if not protocol.isInteractive():
492
- try:
493
- if protocol.isScheduled():
494
- continue
495
- elif protocol.isActive():
496
- self.stopProtocol(protocol)
497
- protocol.runMode.set(MODE_RESTART)
498
- self.scheduleProtocol(protocol,
499
- initialSleepTime=level*INITIAL_SLEEP_TIME)
500
- except Exception as ex:
501
- errorsList.append("Error trying to restart a protocol: %s"
502
- "\nERROR: %s\n" % (protocol.getObjLabel(),
503
- ex))
504
- break
505
- else:
506
- protocol.setStatus(pwprot.STATUS_SAVED)
507
- self._storeProtocol(protocol)
508
- protocol.runMode.set(MODE_RESTART)
509
- self._setupProtocol(protocol)
510
- protocol.makePathsAndClean() # Create working dir if necessary
511
- # Delete the relations created by this protocol
512
- self.mapper.deleteRelations(self)
513
- self.mapper.commit()
514
- self.mapper.store(protocol)
515
- self.mapper.commit()
516
-
517
- def _fixProtParamsConfiguration(self, protocol=None):
518
- """
519
- This function fix:
520
- 1. The old parameters configuration in the protocols.
521
- Now, dependent protocols have a pointer to the parent protocol, and
522
- the extended parameter has a parent output value
523
- """
524
- # Take the old configuration attributes and fix the pointer
525
- oldStylePointerList = [item for key, item in
526
- protocol.iterInputAttributes()
527
- if not isinstance(item.getObjValue(),
528
- pwprot.Protocol)]
529
- if oldStylePointerList:
530
- # Fix the protocol parameters
531
- for pointer in oldStylePointerList:
532
- auxPointer = pointer.getObjValue()
533
- pointer.set(self.getRunsGraph().getNode(str(pointer.get().getObjParentId())).run)
534
- pointer.setExtended(auxPointer.getLastName())
535
- protocol._store()
536
- self._storeProtocol(protocol)
537
- self._updateProtocol(protocol)
538
- self.mapper.commit()
539
-
540
- def stopWorkFlow(self, activeProtList):
541
- """
542
- This function can stop a workflow from a selected protocol
543
- :param initialProtocol: selected protocol
544
- """
545
- errorProtList = []
546
- for protocol in activeProtList.values():
547
- try:
548
- self.stopProtocol(protocol)
549
- except Exception:
550
- errorProtList.append(protocol)
551
- return errorProtList
552
-
553
- def resetWorkFlow(self, workflowProtocolList):
554
- """
555
- This function can reset a workflow from a selected protocol
556
- :param initialProtocol: selected protocol
557
- """
558
- errorProtList = []
559
- if workflowProtocolList:
560
- for protocol, level in workflowProtocolList.values():
561
- if protocol.getStatus() != pwprot.STATUS_SAVED:
562
- try:
563
- self.resetProtocol(protocol)
564
- except Exception:
565
- errorProtList.append(protocol)
566
- return errorProtList
567
-
568
- def launchWorkflow(self, workflowProtocolList, mode=MODE_RESUME):
569
- """
570
- This function can launch a workflow from a selected protocol in two
571
- modes depending on the 'mode' value (RESTART, CONTINUE)
572
- Actions done here are:
573
-
574
- 1. Check if the workflow has active protocols.
575
- 2. Fix the workflow if is not properly configured
576
- 3. Restart or Continue a workflow starting from the protocol depending
577
- on the 'mode' value
578
-
579
- """
580
- errorsList = []
581
- if mode == MODE_RESTART:
582
- self._restartWorkflow(errorsList, workflowProtocolList)
583
- else:
584
- self._continueWorkflow(errorsList,workflowProtocolList)
585
- return errorsList
586
-
587
- def launchProtocol(self, protocol, wait=False, scheduled=False,
588
- force=False):
589
- """ In this function the action of launching a protocol
590
- will be initiated. Actions done here are:
591
-
592
- 1. Store the protocol and assign name and working dir
593
- 2. Create the working dir and also the protocol independent db
594
- 3. Call the launch method in protocol.job to handle submission:
595
- mpi, thread, queue.
596
-
597
- If the protocol has some prerequisites (other protocols that
598
- needs to be finished first), it will be scheduled.
599
-
600
- :param protocol: Protocol instance to launch
601
- :param wait: Optional. If true, this method
602
- will wait until execution is finished. Used in tests.
603
- :param scheduled: Optional. If true, run.db and paths
604
- already exist and are preserved.
605
- :param force: Optional. If true, launch is forced, regardless
606
- latter dependent executions. Used when restarting many protocols a once.
607
-
608
- """
609
- if protocol.getPrerequisites() and not scheduled:
610
- return self.scheduleProtocol(protocol)
611
-
612
- isRestart = protocol.getRunMode() == MODE_RESTART
613
-
614
- if not force:
615
- if (not protocol.isInteractive() and not protocol.isInStreaming()) or isRestart:
616
- self._checkModificationAllowed([protocol],
617
- 'Cannot RE-LAUNCH protocol')
618
-
619
- protocol.setStatus(pwprot.STATUS_LAUNCHED)
620
- self._setupProtocol(protocol)
621
-
622
- # Prepare a separate db for this run if not from schedule jobs
623
- # Scheduled protocols will load the project db from the run.db file,
624
- # so there is no need to copy the database
625
-
626
- if not scheduled:
627
- protocol.makePathsAndClean() # Create working dir if necessary
628
- # Delete the relations created by this protocol
629
- if isRestart:
630
- self.mapper.deleteRelations(self)
631
- # Clean and persist execution attributes; otherwise, this would retain old job IDs and PIDs.
632
- protocol.cleanExecutionAttributes()
633
- protocol._store(protocol._jobId)
634
-
635
- self.mapper.commit()
636
-
637
- # NOTE: now we are simply copying the entire project db, this can be
638
- # changed later to only create a subset of the db need for the run
639
- pwutils.path.copyFile(self.dbPath, protocol.getDbPath())
640
-
641
- # Launch the protocol; depending on the case, either the pId or the jobId will be set in this call
642
- pwprot.launch(protocol, wait)
643
-
644
- # Commit changes
645
- if wait: # This is only useful for launching tests...
646
- self._updateProtocol(protocol)
647
- else:
648
- self.mapper.store(protocol)
649
- self.mapper.commit()
650
-
651
- def scheduleProtocol(self, protocol, prerequisites=[], initialSleepTime=0):
652
- """ Schedule a new protocol that will run when the input data
653
- is available and the prerequisites are finished.
654
-
655
- :param protocol: the protocol that will be scheduled.
656
- :param prerequisites: a list with protocols ids that the scheduled
657
- protocol will wait for.
658
- :param initialSleepTime: number of seconds to wait before
659
- checking input's availability
660
-
661
- """
662
- isRestart = protocol.getRunMode() == MODE_RESTART
663
-
664
- protocol.setStatus(pwprot.STATUS_SCHEDULED)
665
- protocol.addPrerequisites(*prerequisites)
666
-
667
- self._setupProtocol(protocol)
668
- protocol.makePathsAndClean() # Create working dir if necessary
669
- # Delete the relations created by this protocol if any
670
- if isRestart:
671
- self.mapper.deleteRelations(self)
672
- self.mapper.commit()
673
-
674
- # Prepare a separate db for this run
675
- # NOTE: now we are simply copying the entire project db, this can be
676
- # changed later to only create a subset of the db need for the run
677
- pwutils.path.copyFile(self.dbPath, protocol.getDbPath())
678
- # Launch the protocol, the jobId should be set after this call
679
- pwprot.schedule(protocol, initialSleepTime=initialSleepTime)
680
- self.mapper.store(protocol)
681
- self.mapper.commit()
682
-
683
- def _updateProtocol(self, protocol: Protocol, tries=0, checkPid=False,
684
- skipUpdatedProtocols=True):
685
-
686
- # If this is read only exit
687
- if self.openedAsReadOnly():
688
- return pw.NOT_UPDATED_READ_ONLY
689
-
690
- try:
691
-
692
- # Backup the values of 'jobId', 'label' and 'comment'
693
- # to be restored after the .copy
694
- jobId = protocol.getJobIds().clone() # Use clone to prevent this variable from being overwritten or cleared in the latter .copy() call
695
- label = protocol.getObjLabel()
696
- comment = protocol.getObjComment()
697
-
698
- if skipUpdatedProtocols:
699
- # If we are already updated, comparing timestamps
700
- if pwprot.isProtocolUpToDate(protocol):
701
-
702
- # Always check for the status of the process (queue job or pid)
703
- self.checkIsAlive(protocol)
704
- return pw.NOT_UPDATED_UNNECESSARY
705
-
706
-
707
- # If the protocol database has ....
708
- # Comparing date will not work unless we have a reliable
709
- # lastModificationDate of a protocol in the project.sqlite
710
- prot2 = pwprot.getProtocolFromDb(self.path,
711
- protocol.getDbPath(),
712
- protocol.getObjId())
713
-
714
- # Capture the db timestamp before loading.
715
- lastUpdateTime = pwutils.getFileLastModificationDate(protocol.getDbPath())
716
-
717
- # Copy is only working for db restored objects
718
- protocol.setMapper(self.mapper)
719
-
720
- localOutputs = list(protocol._outputs)
721
- protocol.copy(prot2, copyId=False, excludeInputs=True)
722
-
723
- # merge outputs: This is necessary when outputs are added from the GUI
724
- # e.g.: adding coordinates from analyze result and protocol is active (interactive).
725
- for attr in localOutputs:
726
- if attr not in protocol._outputs:
727
- protocol._outputs.append(attr)
728
-
729
- # Restore backup values
730
- if protocol.useQueueForProtocol() and jobId: # If jobId not empty then restore value as the db is empty
731
- # Case for direct protocol launch from the GUI. Without passing through a scheduling process.
732
- # In this case the jobid is obtained by the GUI and the job id should be preserved.
733
- protocol.setJobIds(jobId)
734
-
735
- # In case of scheduling a protocol, the jobid is obtained during the "scheduling job"
736
- # and it is written in the rub.db. Therefore, it should be taken from there.
737
-
738
- protocol.setObjLabel(label)
739
- protocol.setObjComment(comment)
740
- # Use the run.db timestamp instead of the system TS to prevent
741
- # possible inconsistencies.
742
- protocol.lastUpdateTimeStamp.set(lastUpdateTime)
743
-
744
- # Check pid at the end, once updated
745
- if checkPid:
746
- self.checkIsAlive(protocol)
747
-
748
- self.mapper.store(protocol)
749
-
750
- # Close DB connections
751
- prot2.getProject().closeMapper()
752
- prot2.closeMappers()
753
-
754
- except Exception as ex:
755
- if tries == 3: # 3 tries have been failed
756
- traceback.print_exc()
757
- # If any problem happens, the protocol will be marked
758
- # with a FAILED status
759
- try:
760
- protocol.setFailed(str(ex))
761
- self.mapper.store(protocol)
762
- except Exception:
763
- pass
764
- return pw.NOT_UPDATED_ERROR
765
- else:
766
- logger.warning("Couldn't update protocol %s(jobId=%s) from it's own database. ERROR: %s, attempt=%d"
767
- % (protocol.getObjName(), jobId, ex, tries))
768
- time.sleep(0.5)
769
- self._updateProtocol(protocol, tries + 1)
770
-
771
- return pw.PROTOCOL_UPDATED
772
-
773
- def checkIsAlive(self, protocol):
774
- """ Check if a protocol is alive based on its jobid or pid"""
775
- if protocol.getPid() == 0:
776
- self.checkJobId(protocol)
777
- else:
778
- self.checkPid(protocol)
779
-
780
- def stopProtocol(self, protocol):
781
- """ Stop a running protocol """
782
- try:
783
- if protocol.getStatus() in ACTIVE_STATUS:
784
- self._updateProtocol(protocol) # update protocol to have the latest rub.db values
785
- pwprot.stop(protocol)
786
- except Exception as e:
787
- logger.error("Couldn't stop the protocol: %s" % e)
788
- raise
789
- finally:
790
- protocol.setAborted()
791
- protocol.setMapper(self.createMapper(protocol.getDbPath()))
792
- protocol._store()
793
- self._storeProtocol(protocol)
794
- protocol.getMapper().close()
795
-
796
- def resetProtocol(self, protocol):
797
- """ Stop a running protocol """
798
- try:
799
- if protocol.getStatus() in ACTIVE_STATUS:
800
- pwprot.stop(protocol)
801
- except Exception:
802
- raise
803
- finally:
804
- protocol.setSaved()
805
- protocol.runMode.set(MODE_RESTART)
806
- protocol.makePathsAndClean() # Create working dir if necessary
807
- # Clean jobIds, Pid and StepsDone;
808
- protocol.cleanExecutionAttributes() # otherwise, this would retain old executions info
809
- protocol._store()
810
-
811
- def continueProtocol(self, protocol):
812
- """ This function should be called
813
- to mark a protocol that have an interactive step
814
- waiting for approval that can continue
815
- """
816
- protocol.continueFromInteractive()
817
- self.launchProtocol(protocol)
818
-
819
- def __protocolInList(self, prot, protocols):
820
- """ Check if a protocol is in a list comparing the ids. """
821
- for p in protocols:
822
- if p.getObjId() == prot.getObjId():
823
- return True
824
- return False
825
-
826
- def __validDependency(self, prot, child, protocols):
827
- """ Check if the given child is a true dependency of the protocol
828
- in order to avoid any modification.
829
- """
830
- return (not self.__protocolInList(child, protocols) and
831
- not child.isSaved() and not child.isScheduled())
832
-
833
- def _getProtocolsDependencies(self, protocols):
834
- error = ''
835
- runsGraph = self.getRunsGraph()
836
- for prot in protocols:
837
- node = runsGraph.getNode(prot.strId())
838
- if node:
839
- childs = [node.run for node in node.getChildren() if
840
- self.__validDependency(prot, node.run, protocols)]
841
- if childs:
842
- deps = [' ' + c.getRunName() for c in childs]
843
- error += '\n *%s* is referenced from:\n - ' % prot.getRunName()
844
- error += '\n - '.join(deps)
845
- return error
846
-
847
- def _getProtocolDescendents(self, protocol):
848
- """Getting the descendents protocols from a given one"""
849
- runsGraph = self.getRunsGraph()
850
- visitedNodes = dict()
851
- node = runsGraph.getNode(protocol.strId())
852
- if node is None:
853
- return visitedNodes
854
-
855
- visitedNodes[int(node.getName())] = node
856
-
857
- def getDescendents(rootNode):
858
- for child in rootNode.getChildren():
859
- if int(child.getName()) not in visitedNodes:
860
- visitedNodes[int(child.getName())] = child
861
- getDescendents(child)
862
-
863
- getDescendents(node)
864
- return visitedNodes
865
-
866
- def getProtocolCompatibleOutputs(self, protocol, classes, condition):
867
- """Getting the outputs compatible with an object type. The outputs of the child protocols are excluded. """
868
- objects = []
869
- maxNum = 200
870
- protocolDescendents = self._getProtocolDescendents(protocol)
871
- runs = self.getRuns(refresh=False)
872
-
873
- for prot in runs:
874
- # Make sure we don't include previous output of the same
875
- # and other descendent protocols
876
- if prot.getObjId() not in protocolDescendents:
877
- # Check if the protocol itself is one of the desired classes
878
- if any(issubclass(prot.getClass(), c) for c in classes):
879
- p = pwobj.Pointer(prot)
880
- objects.append(p)
881
-
882
- try:
883
- # paramName and attr must be set to None
884
- # Otherwise, if a protocol has failed and the corresponding output object of type XX does not exist
885
- # any other protocol that uses objects of type XX as input will not be able to choose then using
886
- # the magnifier glass (object selector of type XX)
887
- paramName = None
888
- attr = None
889
- for paramName, attr in prot.iterOutputAttributes(includePossible=True):
890
- def _checkParam(paramName, attr):
891
- # If attr is a subclasses of any desired one, add it to the list
892
- # we should also check if there is a condition, the object
893
- # must comply with the condition
894
- p = None
895
-
896
- match = False
897
- cancelConditionEval = False
898
- possibleOutput = isinstance(attr, type)
899
-
900
- # Go through all compatible Classes coming from in pointerClass string
901
- for c in classes:
902
- # If attr is an instance
903
- if isinstance(attr, c):
904
- match = True
905
- break
906
- # If it is a class already: "possibleOutput" case. In this case attr is the class and not
907
- # an instance of c. In this special case
908
- elif possibleOutput and attr == c:
909
- match = True
910
- cancelConditionEval = True
911
-
912
- # If attr matches the class
913
- if match:
914
- if cancelConditionEval or not condition or attr.evalCondition(condition):
915
- p = pwobj.Pointer(prot, extended=paramName)
916
- p._allowsSelection = True
917
- objects.append(p)
918
- return
919
-
920
- # JMRT: For all sets, we don't want to include the
921
- # subitems here for performance reasons (e.g. SetOfParticles)
922
- # Thus, a Set class can define EXPOSE_ITEMS = True
923
- # to enable the inclusion of its items here
924
- if getattr(attr, 'EXPOSE_ITEMS', False) and not possibleOutput:
925
- # If the ITEM type match any of the desired classes
926
- # we will add some elements from the set
927
- if (attr.ITEM_TYPE is not None and
928
- any(issubclass(attr.ITEM_TYPE, c) for c in classes)):
929
- if p is None: # This means the set have not be added
930
- p = pwobj.Pointer(prot, extended=paramName)
931
- p._allowsSelection = False
932
- objects.append(p)
933
- # Add each item on the set to the list of objects
934
- try:
935
- for i, item in enumerate(attr):
936
- if i == maxNum: # Only load up to NUM particles
937
- break
938
- pi = pwobj.Pointer(prot, extended=paramName)
939
- pi.addExtended(item.getObjId())
940
- pi._parentObject = p
941
- objects.append(pi)
942
- except Exception as ex:
943
- print("Error loading items from:")
944
- print(" protocol: %s, attribute: %s" % (prot.getRunName(), paramName))
945
- print(" dbfile: ", os.path.join(self.getPath(), attr.getFileName()))
946
- print(ex)
947
-
948
- _checkParam(paramName, attr)
949
- # The following is a dirty fix for the RCT case where there
950
- # are inner output, maybe we should consider extend this for
951
- # in a more general manner
952
- for subParam in ['_untilted', '_tilted']:
953
- if hasattr(attr, subParam):
954
- _checkParam('%s.%s' % (paramName, subParam),
955
- getattr(attr, subParam))
956
- except Exception as e:
957
- print("Cannot read attributes for %s (%s)" % (prot.getClass(), e))
958
-
959
- return objects
960
-
961
- def _checkProtocolsDependencies(self, protocols, msg):
962
- """ Check if the protocols have dependencies.
963
- This method is used before delete or save protocols to be sure
964
- it is not referenced from other runs. (an Exception is raised)
965
- Params:
966
- protocols: protocol list to be analyzed.
967
- msg: String message to be prefixed to Exception error.
968
- """
969
- # Check if the protocol have any dependencies
970
- error = self._getProtocolsDependencies(protocols)
971
- if error:
972
- raise ModificationNotAllowedException(msg + error)
973
-
974
- def _checkModificationAllowed(self, protocols, msg):
975
- """ Check if any modification operation is allowed for
976
- this group of protocols.
977
- """
978
- if self.openedAsReadOnly():
979
- raise Exception(msg + " Running in READ-ONLY mode.")
980
-
981
- self._checkProtocolsDependencies(protocols, msg)
982
-
983
- def _getSubworkflow(self, protocol, fixProtParam=True, getStopped=True):
984
- """
985
- This function get the workflow from "protocol" and determine the
986
- protocol level into the graph. Also, checks if there are active
987
- protocols excluding interactive protocols.
988
- :param protocol from where to start the subworkflow (included)
989
- :param fixProtParam fix the old parameters configuration in the protocols
990
- :param getStopped takes into account protocols that aren't stopped
991
- """
992
- affectedProtocols = {}
993
- affectedProtocolsActive = {}
994
- auxProtList = []
995
- # store the protocol and your level into the workflow
996
- affectedProtocols[protocol.getObjId()] = [protocol, 0]
997
- auxProtList.append([protocol.getObjId(), 0])
998
- runGraph = self.getRunsGraph()
999
-
1000
- while auxProtList:
1001
- protId, level = auxProtList.pop(0)
1002
- protocol = runGraph.getNode(str(protId)).run
1003
-
1004
- # Increase the level for the children
1005
- level = level + 1
1006
-
1007
- if fixProtParam:
1008
- self._fixProtParamsConfiguration(protocol)
1009
-
1010
- if not getStopped and protocol.isActive():
1011
- affectedProtocolsActive[protocol.getObjId()] = protocol
1012
- elif not protocol.getObjId() in affectedProtocolsActive.keys() and getStopped and \
1013
- not protocol.isSaved() and protocol.getStatus() != STATUS_INTERACTIVE:
1014
- affectedProtocolsActive[protocol.getObjId()] = protocol
1015
-
1016
- node = runGraph.getNode(protocol.strId())
1017
- dependencies = [node.run for node in node.getChildren()]
1018
- for dep in dependencies:
1019
- if not dep.getObjId() in auxProtList:
1020
- auxProtList.append([dep.getObjId(), level])
1021
-
1022
- if not dep.getObjId() in affectedProtocols.keys():
1023
- affectedProtocols[dep.getObjId()] = [dep, level]
1024
- elif level > affectedProtocols[dep.getObjId()][1]:
1025
- affectedProtocols[dep.getObjId()][1] = level
1026
-
1027
- return affectedProtocols, affectedProtocolsActive
1028
-
1029
- def deleteProtocol(self, *protocols):
1030
- self._checkModificationAllowed(protocols, 'Cannot DELETE protocols')
1031
-
1032
- for prot in protocols:
1033
- # Delete the relations created by this protocol
1034
- self.mapper.deleteRelations(prot)
1035
- # Delete from protocol from database
1036
- self.mapper.delete(prot)
1037
- wd = prot.workingDir.get()
1038
-
1039
- if wd.startswith(PROJECT_RUNS):
1040
- prot.cleanWorkingDir()
1041
- else:
1042
- logger.info("Can't delete protocol %s. Its workingDir %s does not starts with %s " % (prot, wd, PROJECT_RUNS))
1043
-
1044
- self.mapper.commit()
1045
-
1046
- def deleteProtocolOutput(self, protocol, output):
1047
- """ Delete a given object from the project.
1048
- Usually to clean up some outputs.
1049
- """
1050
- node = self.getRunsGraph().getNode(protocol.strId())
1051
- deps = []
1052
-
1053
- for node in node.getChildren():
1054
- for _, inputObj in node.run.iterInputAttributes():
1055
- value = inputObj.get()
1056
- if (value is not None and
1057
- value.getObjId() == output.getObjId() and
1058
- not node.run.isSaved()):
1059
- deps.append(node.run)
1060
-
1061
- if deps:
1062
- error = 'Cannot DELETE Object, it is referenced from:'
1063
- for d in deps:
1064
- error += '\n - %s' % d.getRunName()
1065
- raise Exception(error)
1066
- else:
1067
- protocol.deleteOutput(output)
1068
- pwutils.path.copyFile(self.dbPath, protocol.getDbPath())
1069
-
1070
- def __setProtocolLabel(self, newProt):
1071
- """ Set a readable label to a newly created protocol.
1072
- We will try to find another existing protocol with the default label
1073
- and then use an incremental labeling in parenthesis (<number>++)
1074
- """
1075
- defaultLabel = newProt.getClassLabel()
1076
- maxSuffix = 0
1077
-
1078
- for prot in self.getRuns(iterate=True, refresh=False):
1079
- otherProtLabel = prot.getObjLabel()
1080
- m = REGEX_NUMBER_ENDING.match(otherProtLabel)
1081
- if m and m.groupdict()['prefix'].strip() == defaultLabel:
1082
- stringSuffix = m.groupdict()['number'].strip('(').strip(')')
1083
- try:
1084
- maxSuffix = max(int(stringSuffix), maxSuffix)
1085
- except:
1086
- logger.error("Couldn't set protocol's label. %s" % stringSuffix)
1087
- elif otherProtLabel == defaultLabel: # When only we have the prefix,
1088
- maxSuffix = max(1, maxSuffix) # this REGEX don't match.
1089
-
1090
- if maxSuffix:
1091
- protLabel = '%s (%d)' % (defaultLabel, maxSuffix+1)
1092
- else:
1093
- protLabel = defaultLabel
1094
-
1095
- newProt.setObjLabel(protLabel)
1096
-
1097
- def newProtocol(self, protocolClass, **kwargs):
1098
- """ Create a new protocol from a given class. """
1099
- newProt = protocolClass(project=self, **kwargs)
1100
- # Only set a default label to the protocol if is was not
1101
- # set through the kwargs
1102
- if not newProt.getObjLabel():
1103
- self.__setProtocolLabel(newProt)
1104
-
1105
- newProt.setMapper(self.mapper)
1106
- newProt.setProject(self)
1107
-
1108
- return newProt
1109
-
1110
- def __getIOMatches(self, node, childNode):
1111
- """ Check if some output of node is used as input in childNode.
1112
- Return the list of attribute names that matches.
1113
- Used from self.copyProtocol
1114
- """
1115
- matches = []
1116
- for iKey, iAttr in childNode.run.iterInputAttributes():
1117
- # As this point iAttr should be always a Pointer that
1118
- # points to the output of other protocol
1119
- if iAttr.getObjValue() is node.run:
1120
- oKey = iAttr.getExtended()
1121
- matches.append((oKey, iKey))
1122
- else:
1123
- for oKey, oAttr in node.run.iterOutputAttributes():
1124
- # If node output is "real" and iAttr is still just a pointer
1125
- # the iAttr.get() will return None
1126
- pointed = iAttr.get()
1127
- if pointed is not None and oAttr.getObjId() == pointed.getObjId():
1128
- matches.append((oKey, iKey))
1129
-
1130
- return matches
1131
-
1132
- def __cloneProtocol(self, protocol):
1133
- """ Make a copy of the protocol parameters, not outputs.
1134
- We will label the new protocol with the same name adding the
1135
- parenthesis as follow -> (copy) -> (copy 2) -> (copy 3)
1136
- """
1137
- newProt = self.newProtocol(protocol.getClass())
1138
- oldProtName = protocol.getRunName()
1139
- maxSuffix = 0
1140
-
1141
- # if '(copy...' suffix is not in the old name, we add it in the new name
1142
- # and setting the newnumber
1143
- mOld = REGEX_NUMBER_ENDING_CP.match(oldProtName)
1144
- if mOld:
1145
- newProtPrefix = mOld.groupdict()['prefix']
1146
- if mOld.groupdict()['number'] == '':
1147
- oldNumber = 1
1148
- else:
1149
- oldNumber = int(mOld.groupdict()['number'])
1150
- else:
1151
- newProtPrefix = oldProtName + ' (copy'
1152
- oldNumber = 0
1153
- newNumber = oldNumber + 1
1154
-
1155
- # looking for "<old name> (copy" prefixes in the project and
1156
- # setting the newNumber as the maximum+1
1157
- for prot in self.getRuns(iterate=True, refresh=False):
1158
- otherProtLabel = prot.getObjLabel()
1159
- mOther = REGEX_NUMBER_ENDING_CP.match(otherProtLabel)
1160
- if mOther and mOther.groupdict()['prefix'] == newProtPrefix:
1161
- stringSuffix = mOther.groupdict()['number']
1162
- if stringSuffix == '':
1163
- stringSuffix = 1
1164
- maxSuffix = max(maxSuffix, int(stringSuffix))
1165
- if newNumber <= maxSuffix:
1166
- newNumber = maxSuffix + 1
1167
-
1168
- # building the new name
1169
- if newNumber == 1:
1170
- newProtLabel = newProtPrefix + ')'
1171
- else:
1172
- newProtLabel = '%s %d)' % (newProtPrefix, newNumber)
1173
-
1174
- newProt.setObjLabel(newProtLabel)
1175
- newProt.copyDefinitionAttributes(protocol)
1176
- newProt.copyAttributes(protocol, 'hostName', '_useQueue', '_queueParams')
1177
- newProt.runMode.set(MODE_RESTART)
1178
- newProt.cleanExecutionAttributes() # Clean jobIds and Pid; otherwise, this would retain old job IDs and PIDs.
1179
-
1180
- return newProt
1181
-
1182
- def copyProtocol(self, protocol):
1183
- """ Make a copy of the protocol,
1184
- Return a new instance with copied values. """
1185
- result = None
1186
-
1187
- if isinstance(protocol, pwprot.Protocol):
1188
- result = self.__cloneProtocol(protocol)
1189
-
1190
- elif isinstance(protocol, list):
1191
- # Handle the copy of a list of protocols
1192
- # for this case we need to update the references of input/outputs
1193
- newDict = {}
1194
-
1195
- for prot in protocol:
1196
- newProt = self.__cloneProtocol(prot)
1197
- newDict[prot.getObjId()] = newProt
1198
- self.saveProtocol(newProt)
1199
-
1200
- g = self.getRunsGraph()
1201
-
1202
- for prot in protocol:
1203
- node = g.getNode(prot.strId())
1204
- newProt = newDict[prot.getObjId()]
1205
-
1206
- for childNode in node.getChildren():
1207
- newChildProt = newDict.get(childNode.run.getObjId(), None)
1208
-
1209
- if newChildProt:
1210
- # Get the matches between outputs/inputs of
1211
- # node and childNode
1212
- matches = self.__getIOMatches(node, childNode)
1213
- # For each match, set the pointer and the extend
1214
- # attribute to reproduce the dependencies in the
1215
- # new workflow
1216
- for oKey, iKey in matches:
1217
- childPointer = getattr(newChildProt, iKey)
1218
-
1219
- # Scalar with pointer case: If is a scalar with a pointer
1220
- if isinstance(childPointer, pwobj.Scalar) and childPointer.hasPointer():
1221
- # In this case childPointer becomes the contained Pointer
1222
- childPointer = childPointer.getPointer()
1223
-
1224
- elif isinstance(childPointer, pwobj.PointerList):
1225
- for p in childPointer:
1226
- if p.getObjValue().getObjId() == prot.getObjId():
1227
- childPointer = p
1228
- childPointer.set(newProt)
1229
- childPointer.setExtended(oKey)
1230
- self.mapper.store(newChildProt)
1231
-
1232
- self.mapper.commit()
1233
- else:
1234
- raise Exception("Project.copyProtocol: invalid input protocol ' "
1235
- "'type '%s'." % type(protocol))
1236
-
1237
- return result
1238
-
1239
- def getProtocolsDict(self, protocols=None, namesOnly=False):
1240
- """ Creates a dict with the information of the given protocols.
1241
-
1242
- :param protocols: list of protocols or None to include all.
1243
- :param namesOnly: the output list will contain only the protocol names.
1244
-
1245
- """
1246
- protocols = protocols or self.getRuns()
1247
-
1248
- # If the nameOnly, we will simply return a json list with their names
1249
- if namesOnly:
1250
- return {i: prot.getClassName() for i, prot in enumerate(protocols)}
1251
-
1252
- # Handle the copy of a list of protocols
1253
- # for this case we need to update the references of input/outputs
1254
- newDict = OrderedDict()
1255
-
1256
- for prot in protocols:
1257
- newDict[prot.getObjId()] = prot.getDefinitionDict()
1258
-
1259
- g = self.getRunsGraph()
1260
-
1261
- for prot in protocols:
1262
- protId = prot.getObjId()
1263
- node = g.getNode(prot.strId())
1264
-
1265
- for childNode in node.getChildren():
1266
- childId = childNode.run.getObjId()
1267
- childProt = childNode.run
1268
- if childId in newDict:
1269
- childDict = newDict[childId]
1270
- # Get the matches between outputs/inputs of
1271
- # node and childNode
1272
- matches = self.__getIOMatches(node, childNode)
1273
- for oKey, iKey in matches:
1274
- inputAttr = getattr(childProt, iKey)
1275
- if isinstance(inputAttr, pwobj.PointerList):
1276
- childDict[iKey] = [p.getUniqueId() for p in
1277
- inputAttr]
1278
- else:
1279
- childDict[iKey] = '%s.%s' % (
1280
- protId, oKey) # equivalent to pointer.getUniqueId
1281
-
1282
- return newDict
1283
-
1284
- def getProtocolsJson(self, protocols=None, namesOnly=False):
1285
- """
1286
- Wraps getProtocolsDict to get a json string
1287
-
1288
- :param protocols: list of protocols or None to include all.
1289
- :param namesOnly: the output list will contain only the protocol names.
1290
-
1291
- """
1292
- newDict = self.getProtocolsDict(protocols=protocols, namesOnly=namesOnly)
1293
- return json.dumps(list(newDict.values()),
1294
- indent=4, separators=(',', ': '))
1295
-
1296
- def exportProtocols(self, protocols, filename):
1297
- """ Create a text json file with the info
1298
- to import the workflow into another project.
1299
- This method is very similar to copyProtocol
1300
-
1301
- :param protocols: a list of protocols to export.
1302
- :param filename: the filename where to write the workflow.
1303
-
1304
- """
1305
- jsonStr = self.getProtocolsJson(protocols)
1306
- f = open(filename, 'w')
1307
- f.write(jsonStr)
1308
- f.close()
1309
-
1310
- def loadProtocols(self, filename=None, jsonStr=None):
1311
- """ Load protocols generated in the same format as self.exportProtocols.
1312
-
1313
- :param filename: the path of the file where to read the workflow.
1314
- :param jsonStr:
1315
-
1316
- Note: either filename or jsonStr should be not None.
1317
-
1318
- """
1319
- importDir = None
1320
- if filename:
1321
- with open(filename) as f:
1322
- importDir = os.path.dirname(filename)
1323
- protocolsList = json.load(f)
1324
-
1325
- elif jsonStr:
1326
- protocolsList = json.loads(jsonStr)
1327
- else:
1328
- logger.error("Invalid call to loadProtocols. Either filename or jsonStr has to be passed.")
1329
- return
1330
-
1331
- emProtocols = self._domain.getProtocols()
1332
- newDict = OrderedDict()
1333
-
1334
- # First iteration: create all protocols and setup parameters
1335
- for i, protDict in enumerate(protocolsList):
1336
- protClassName = protDict['object.className']
1337
- protId = protDict['object.id']
1338
- protClass = emProtocols.get(protClassName, None)
1339
-
1340
- if protClass is None:
1341
- logger.error("Protocol with class name '%s' not found. Are you missing its plugin?." % protClassName)
1342
- else:
1343
- protLabel = protDict.get('object.label', None)
1344
- prot = self.newProtocol(protClass,
1345
- objLabel=protLabel,
1346
- objComment=protDict.get('object.comment', None))
1347
- protocolsList[i] = prot.processImportDict(protDict, importDir) if importDir else protDict
1348
-
1349
- prot._useQueue.set(protDict.get('_useQueue', pw.Config.SCIPION_USE_QUEUE))
1350
- prot._queueParams.set(protDict.get('_queueParams', None))
1351
- prot._prerequisites.set(protDict.get('_prerequisites', None))
1352
- prot.forceSchedule.set(protDict.get('forceSchedule', False))
1353
- newDict[protId] = prot
1354
- # This saves the protocol JUST with the common attributes. Is it necessary?
1355
- # Actually, if after this the is an error, the protocol appears.
1356
- self.saveProtocol(prot)
1357
-
1358
- # Second iteration: update pointers values
1359
- def _setPointer(pointer, value):
1360
- # Properly setup the pointer value checking if the
1361
- # id is already present in the dictionary
1362
- # Value to pointers could be None: Partial workflows
1363
- if value:
1364
- parts = value.split('.')
1365
-
1366
- protId = parts[0]
1367
- # Try to get the protocol holding the input form the dictionary
1368
- target = newDict.get(protId, None)
1369
-
1370
- if target is None:
1371
- # Try to use existing protocol in the project
1372
- logger.info("Protocol identifier (%s) not self contained. Looking for it in the project." % protId)
1373
-
1374
- try:
1375
- target = self.getProtocol(int(protId), fromRuns=True)
1376
- except:
1377
- # Not a protocol..
1378
- logger.info("%s is not a protocol identifier. Probably a direct pointer created by tests. This case is not considered." % protId)
1379
-
1380
- if target:
1381
- logger.info("Linking %s to existing protocol in the project: %s" % (prot, target))
1382
-
1383
- pointer.set(target)
1384
- if not pointer.pointsNone():
1385
- pointer.setExtendedParts(parts[1:])
1386
-
1387
- def _setPrerequisites(prot):
1388
- prerequisites = prot.getPrerequisites()
1389
- if prerequisites:
1390
- newPrerequisites = []
1391
- for prerequisite in prerequisites:
1392
- if prerequisite in newDict:
1393
- newProtId = newDict[prerequisite].getObjId()
1394
- newPrerequisites.append(newProtId)
1395
- else:
1396
- logger.info('"Wait for" id %s missing: ignored.' % prerequisite)
1397
- prot._prerequisites.set(newPrerequisites)
1398
-
1399
- for protDict in protocolsList:
1400
- protId = protDict['object.id']
1401
-
1402
- if protId in newDict:
1403
- prot = newDict[protId]
1404
- _setPrerequisites(prot)
1405
- for paramName, attr in prot.iterDefinitionAttributes():
1406
- if paramName in protDict:
1407
- # If the attribute is a pointer, we should look
1408
- # if the id is already in the dictionary and
1409
- # set the extended property
1410
- if attr.isPointer():
1411
- _setPointer(attr, protDict[paramName])
1412
- # This case is similar to Pointer, but the values
1413
- # is a list and we will setup a pointer for each value
1414
- elif isinstance(attr, pwobj.PointerList):
1415
- attribute = protDict[paramName]
1416
- if attribute is None:
1417
- continue
1418
- for value in attribute:
1419
- p = pwobj.Pointer()
1420
- _setPointer(p, value)
1421
- attr.append(p)
1422
- # For "normal" parameters we just set the string value
1423
- else:
1424
- try:
1425
- attr.set(protDict[paramName])
1426
- # Case for Scalars with pointers. So far this will work for Numbers. With Strings (still there are no current examples)
1427
- # We will need something different to test if the value look like a pointer: regex? ####.text
1428
- except ValueError as e:
1429
- newPointer = pwobj.Pointer()
1430
- _setPointer(newPointer, protDict[paramName])
1431
- attr.setPointer(newPointer)
1432
-
1433
- self.mapper.store(prot)
1434
-
1435
- self.mapper.commit()
1436
-
1437
- return newDict
1438
-
1439
- def saveProtocol(self, protocol):
1440
- self._checkModificationAllowed([protocol], 'Cannot SAVE protocol')
1441
-
1442
- if (protocol.isRunning() or protocol.isFinished()
1443
- or protocol.isLaunched()):
1444
- raise ModificationNotAllowedException('Cannot SAVE a protocol that is %s. '
1445
- 'Copy it instead.' % protocol.getStatus())
1446
-
1447
- protocol.setStatus(pwprot.STATUS_SAVED)
1448
- if protocol.hasObjId():
1449
- self._storeProtocol(protocol)
1450
- else:
1451
- self._setupProtocol(protocol)
1452
-
1453
- def getProtocolFromRuns(self, protId):
1454
- """ Returns the protocol with the id=protId from the runs list (memory) or None"""
1455
- if self.runs:
1456
- for run in self.runs:
1457
- if run.getObjId() == protId:
1458
- return run
1459
-
1460
- return None
1461
-
1462
- def getProtocol(self, protId, fromRuns=False):
1463
- """ Returns the protocol with the id=protId or raises an Exception
1464
-
1465
- :param protId: integer with an existing protocol identifier
1466
- :param fromRuns: If true, it tries to get it from the runs list (memory) avoiding querying the db."""
1467
-
1468
- protocol = self.getProtocolFromRuns(protId) if fromRuns else None
1469
-
1470
- if protocol is None:
1471
- protocol = self.mapper.selectById(protId)
1472
-
1473
- if not isinstance(protocol, pwprot.Protocol):
1474
- raise Exception('>>> ERROR: Invalid protocol id: %d' % protId)
1475
-
1476
- self._setProtocolMapper(protocol)
1477
-
1478
- return protocol
1479
-
1480
- # FIXME: this function just return if a given object exists, not
1481
- # if it is a protocol, so it is incorrect judging by the name
1482
- # Moreover, a more consistent name (comparing to similar methods)
1483
- # would be: hasProtocol
1484
- def doesProtocolExists(self, protId):
1485
- return self.mapper.exists(protId)
1486
-
1487
- def getProtocolsByClass(self, className):
1488
- return self.mapper.selectByClass(className)
1489
-
1490
- def getObject(self, objId):
1491
- """ Retrieve an object from the db given its id. """
1492
- return self.mapper.selectById(objId)
1493
-
1494
- def _setHostConfig(self, protocol):
1495
- """ Set the appropriate host config to the protocol
1496
- give its value of 'hostname'
1497
- """
1498
- hostName = protocol.getHostName()
1499
- hostConfig = self.getHostConfig(hostName)
1500
- protocol.setHostConfig(hostConfig)
1501
-
1502
- def _storeProtocol(self, protocol):
1503
- # Read only mode
1504
- if not self.openedAsReadOnly():
1505
- self.mapper.store(protocol)
1506
- self.mapper.commit()
1507
-
1508
- def _setProtocolMapper(self, protocol):
1509
- """ Set the project and mapper to the protocol. """
1510
-
1511
- # Tolerate loading errors. For support.
1512
- # When only having the sqlite, sometime there are exceptions here
1513
- # due to the absence of a set.
1514
- from pyworkflow.mapper.sqlite import SqliteFlatMapperException
1515
- try:
1516
-
1517
- protocol.setProject(self)
1518
- protocol.setMapper(self.mapper)
1519
- self._setHostConfig(protocol)
1520
-
1521
- except SqliteFlatMapperException:
1522
- protocol.addSummaryWarning(
1523
- "*Protocol loading problem*: A set related to this "
1524
- "protocol couldn't be loaded.")
1525
-
1526
- def _setupProtocol(self, protocol):
1527
- """Insert a new protocol instance in the database"""
1528
-
1529
- # Read only mode
1530
- if not self.openedAsReadOnly():
1531
- self._storeProtocol(protocol) # Store first to get a proper id
1532
- # Set important properties of the protocol
1533
- workingDir = self.getProtWorkingDir(protocol)
1534
- self._setProtocolMapper(protocol)
1535
-
1536
- protocol.setWorkingDir(self.getPath(PROJECT_RUNS, workingDir))
1537
- # Update with changes
1538
- self._storeProtocol(protocol)
1539
-
1540
- @staticmethod
1541
- def getProtWorkingDir(protocol):
1542
- """
1543
- Return the protocol working directory
1544
- """
1545
- return "%06d_%s" % (protocol.getObjId(), protocol.getClassName())
1546
-
1547
- def getRuns(self, iterate=False, refresh=True, checkPids=False):
1548
- """ Return the existing protocol runs in the project.
1549
- """
1550
- if self.runs is None or refresh:
1551
- # Close db open connections to db files
1552
- if self.runs is not None:
1553
- for r in self.runs:
1554
- r.closeMappers()
1555
-
1556
- # Use new selectAll Batch
1557
- # self.runs = self.mapper.selectAll(iterate=False,
1558
- # objectFilter=lambda o: isinstance(o, pwprot.Protocol))
1559
- self.runs = self.mapper.selectAllBatch(objectFilter=lambda o: isinstance(o, pwprot.Protocol))
1560
-
1561
- # Invalidate _runsGraph because the runs are updated
1562
- self._runsGraph = None
1563
-
1564
- for r in self.runs:
1565
-
1566
- self._setProtocolMapper(r)
1567
-
1568
- # Check for run warnings
1569
- r.checkSummaryWarnings()
1570
-
1571
- # Update nodes that are running and were not invoked
1572
- # by other protocols
1573
- if r.isActive():
1574
- if not r.isChild():
1575
- self._updateProtocol(r, checkPid=checkPids)
1576
-
1577
- self._annotateLastRunTime(r.endTime)
1578
-
1579
- self.mapper.commit()
1580
-
1581
- return self.runs
1582
-
1583
- def _annotateLastRunTime(self, protLastTS):
1584
- """ Sets _lastRunTime for the project if it is after current _lastRunTime"""
1585
- try:
1586
- if protLastTS is None:
1587
- return
1588
-
1589
- if self._lastRunTime is None:
1590
- self._lastRunTime = protLastTS
1591
- elif self._lastRunTime.datetime() < protLastTS.datetime():
1592
- self._lastRunTime = protLastTS
1593
- except Exception as e:
1594
- return
1595
-
1596
- def needRefresh(self):
1597
- """ True if any run is active and its timestamp is older than its
1598
- corresponding runs.db
1599
- NOTE: If an external script changes the DB this will fail. It uses
1600
- only in memory objects."""
1601
- for run in self.runs:
1602
- if run.isActive():
1603
- if not pwprot.isProtocolUpToDate(run):
1604
- return True
1605
- return False
1606
-
1607
- def checkPid(self, protocol):
1608
- """ Check if a running protocol is still alive or not.
1609
- The check will only be done for protocols that have not been sent
1610
- to a queue system.
1611
- """
1612
- from pyworkflow.protocol.launch import _runsLocally
1613
- pid = protocol.getPid()
1614
-
1615
- if pid == 0:
1616
- return
1617
-
1618
- # Include running and scheduling ones
1619
- # Exclude interactive protocols
1620
- # NOTE: This may be happening even with successfully finished protocols
1621
- # which PID is gone.
1622
- if (protocol.isActive() and not protocol.isInteractive() and _runsLocally(protocol)
1623
- and not pwutils.isProcessAlive(pid)):
1624
- protocol.setFailed("Process %s not found running on the machine. "
1625
- "It probably has died or been killed without "
1626
- "reporting the status to Scipion. Logs might "
1627
- "have information about what happened to this "
1628
- "process." % pid)
1629
-
1630
- def checkJobId(self, protocol):
1631
- """ Check if a running protocol is still alive or not.
1632
- The check will only be done for protocols that have been sent
1633
- to a queue system.
1634
- """
1635
-
1636
- if len(protocol.getJobIds()) == 0:
1637
- return
1638
-
1639
- jobid = protocol.getJobIds()[0]
1640
- hostConfig = protocol.getHostConfig()
1641
-
1642
- if jobid == UNKNOWN_JOBID:
1643
- return
1644
-
1645
- # Include running and scheduling ones
1646
- # Exclude interactive protocols
1647
- # NOTE: This may be happening even with successfully finished protocols
1648
- # which PID is gone.
1649
- if protocol.isActive() and not protocol.isInteractive():
1650
-
1651
- jobStatus = _checkJobStatus(hostConfig, jobid)
1652
-
1653
- if jobStatus == STATUS_FINISHED:
1654
- protocol.setFailed("Process %s not found running on the machine. "
1655
- "It probably has died or been killed without "
1656
- "reporting the status to Scipion. Logs might "
1657
- "have information about what happened to this "
1658
- "process." % jobid)
1659
-
1660
- def iterSubclasses(self, classesName, objectFilter=None):
1661
- """ Retrieve all objects from the project that are instances
1662
- of any of the classes in classesName list.
1663
- Params:
1664
- classesName: String with commas separated values of classes name.
1665
- objectFilter: a filter function to discard some of the retrieved
1666
- objects."""
1667
- for objClass in classesName.split(","):
1668
- for obj in self.mapper.selectByClass(objClass.strip(), iterate=True,
1669
- objectFilter=objectFilter):
1670
- yield obj
1671
-
1672
- def getRunsGraph(self, refresh=False, checkPids=False):
1673
- """ Build a graph taking into account the dependencies between
1674
- different runs, ie. which outputs serves as inputs of other protocols.
1675
- """
1676
-
1677
- if refresh or self._runsGraph is None:
1678
- runs = [r for r in self.getRuns(refresh=refresh, checkPids=checkPids)
1679
- if not r.isChild()]
1680
- self._runsGraph = self.getGraphFromRuns(runs)
1681
-
1682
- return self._runsGraph
1683
-
1684
- def getGraphFromRuns(self, runs):
1685
- """
1686
- This function will build a dependencies graph from a set
1687
- of given runs.
1688
-
1689
- :param runs: The input runs to build the graph
1690
- :return: The graph taking into account run dependencies
1691
-
1692
- """
1693
- outputDict = {} # Store the output dict
1694
- g = pwutils.Graph(rootName=ROOT_NODE_NAME)
1695
-
1696
- for r in runs:
1697
- n = g.createNode(r.strId())
1698
- n.run = r
1699
-
1700
- # Legacy protocols do not have a plugin!!
1701
- develTxt = ''
1702
- plugin = r.getPlugin()
1703
- if plugin and plugin.inDevelMode():
1704
- develTxt = '* '
1705
-
1706
- n.setLabel('%s%s' % (develTxt, r.getRunName()))
1707
- outputDict[r.getObjId()] = n
1708
- for _, attr in r.iterOutputAttributes():
1709
- # mark this output as produced by r
1710
- if attr is None:
1711
- logger.warning("Output attribute %s of %s is None" % (_, r))
1712
- else:
1713
- outputDict[attr.getObjId()] = n
1714
-
1715
- def _checkInputAttr(node, pointed):
1716
- """ Check if an attr is registered as output"""
1717
- if pointed is not None:
1718
- pointedId = pointed.getObjId()
1719
-
1720
- if pointedId in outputDict:
1721
- parentNode = outputDict[pointedId]
1722
- if parentNode is node:
1723
- logger.warning("WARNING: Found a cyclic dependence from node %s to itself, probably a bug. " % pointedId)
1724
- else:
1725
- parentNode.addChild(node)
1726
- if os.environ.get('CHECK_CYCLIC_REDUNDANCY') and self._checkCyclicRedundancy(parentNode, node):
1727
- conflictiveNodes = set()
1728
- for child in node.getChildren():
1729
- if node in child._parents:
1730
- child._parents.remove(node)
1731
- conflictiveNodes.add(child)
1732
- logger.warning("WARNING: Found a cyclic dependence from node %s to %s, probably a bug. "
1733
- % (node.getLabel() + '(' + node.getName() + ')',
1734
- child.getLabel() + '(' + child.getName() + ')'))
1735
-
1736
- for conflictNode in conflictiveNodes:
1737
- node._children.remove(conflictNode)
1738
-
1739
- return False
1740
- return True
1741
- return False
1742
-
1743
- for r in runs:
1744
- node = g.getNode(r.strId())
1745
- for _, attr in r.iterInputAttributes():
1746
- if attr.hasValue():
1747
- pointed = attr.getObjValue()
1748
- # Only checking pointed object and its parent, if more
1749
- # levels we need to go up to get the correct dependencies
1750
- if not _checkInputAttr(node, pointed):
1751
- parent = self.mapper.getParent(pointed)
1752
- _checkInputAttr(node, parent)
1753
- rootNode = g.getRoot()
1754
- rootNode.run = None
1755
- rootNode.label = ROOT_NODE_NAME
1756
-
1757
- for n in g.getNodes():
1758
- if n.isRoot() and n is not rootNode:
1759
- rootNode.addChild(n)
1760
- return g
1761
-
1762
- @staticmethod
1763
- def _checkCyclicRedundancy(parent, child):
1764
- visitedNodes = set()
1765
- recursionStack = set()
1766
-
1767
- def depthFirstSearch(node):
1768
- visitedNodes.add(node)
1769
- recursionStack.add(node)
1770
- for child in node.getChildren():
1771
- if child not in visitedNodes:
1772
- if depthFirstSearch(child):
1773
- return True
1774
- elif child in recursionStack and child != parent:
1775
- return True
1776
-
1777
- recursionStack.remove(node)
1778
- return False
1779
-
1780
- return depthFirstSearch(child)
1781
-
1782
-
1783
- def _getRelationGraph(self, relation=pwobj.RELATION_SOURCE, refresh=False):
1784
- """ Retrieve objects produced as outputs and
1785
- make a graph taking into account the SOURCE relation. """
1786
- relations = self.mapper.getRelationsByName(relation)
1787
- g = pwutils.Graph(rootName=ROOT_NODE_NAME)
1788
- root = g.getRoot()
1789
- root.pointer = None
1790
- runs = self.getRuns(refresh=refresh)
1791
-
1792
- for r in runs:
1793
- for paramName, attr in r.iterOutputAttributes():
1794
- p = pwobj.Pointer(r, extended=paramName)
1795
- node = g.createNode(p.getUniqueId(), attr.getNameId())
1796
- node.pointer = p
1797
- # The following alias if for backward compatibility
1798
- p2 = pwobj.Pointer(attr)
1799
- g.aliasNode(node, p2.getUniqueId())
1800
-
1801
- for rel in relations:
1802
- pObj = self.getObject(rel[OBJECT_PARENT_ID])
1803
-
1804
- # Duplicated ...
1805
- if pObj is None:
1806
- logger.warning("Relation seems to point to a deleted object. "
1807
- "%s: %s" % (OBJECT_PARENT_ID, rel[OBJECT_PARENT_ID]))
1808
- continue
1809
-
1810
- pExt = rel['object_parent_extended']
1811
- pp = pwobj.Pointer(pObj, extended=pExt)
1812
-
1813
- if pObj is None or pp.get() is None:
1814
- logger.error("project._getRelationGraph: pointer to parent is "
1815
- "None. IGNORING IT.\n")
1816
- for key in rel.keys():
1817
- logger.info("%s: %s" % (key, rel[key]))
1818
-
1819
- continue
1820
-
1821
- pid = pp.getUniqueId()
1822
- parent = g.getNode(pid)
1823
-
1824
- while not parent and pp.hasExtended():
1825
- pp.removeExtended()
1826
- parent = g.getNode(pp.getUniqueId())
1827
-
1828
- if not parent:
1829
- logger.error("project._getRelationGraph: parent Node "
1830
- "is None: %s" % pid)
1831
- else:
1832
- cObj = self.getObject(rel['object_child_id'])
1833
- cExt = rel['object_child_extended']
1834
-
1835
- if cObj is not None:
1836
- if cObj.isPointer():
1837
- cp = cObj
1838
- if cExt:
1839
- cp.setExtended(cExt)
1840
- else:
1841
- cp = pwobj.Pointer(cObj, extended=cExt)
1842
- child = g.getNode(cp.getUniqueId())
1843
-
1844
- if not child:
1845
- logger.error("project._getRelationGraph: child Node "
1846
- "is None: %s." % cp.getUniqueId())
1847
- logger.error(" parent: %s" % pid)
1848
- else:
1849
- parent.addChild(child)
1850
- else:
1851
- logger.error("project._getRelationGraph: child Obj "
1852
- "is None, id: %s " % rel['object_child_id'])
1853
- logger.error(" parent: %s" % pid)
1854
-
1855
- for n in g.getNodes():
1856
- if n.isRoot() and n is not root:
1857
- root.addChild(n)
1858
-
1859
- return g
1860
-
1861
- def getSourceChilds(self, obj):
1862
- """ Return all the objects have used obj
1863
- as a source.
1864
- """
1865
- return self.mapper.getRelationChilds(pwobj.RELATION_SOURCE, obj)
1866
-
1867
- def getSourceParents(self, obj):
1868
- """ Return all the objects that are SOURCE of this object.
1869
- """
1870
- return self.mapper.getRelationParents(pwobj.RELATION_SOURCE, obj)
1871
-
1872
- def getTransformGraph(self, refresh=False):
1873
- """ Get the graph from the TRANSFORM relation. """
1874
- if refresh or not self._transformGraph:
1875
- self._transformGraph = self._getRelationGraph(pwobj.RELATION_TRANSFORM,
1876
- refresh)
1877
-
1878
- return self._transformGraph
1879
-
1880
- def getSourceGraph(self, refresh=False):
1881
- """ Get the graph from the SOURCE relation. """
1882
- if refresh or not self._sourceGraph:
1883
- self._sourceGraph = self._getRelationGraph(pwobj.RELATION_SOURCE,
1884
- refresh)
1885
-
1886
- return self._sourceGraph
1887
-
1888
- def getRelatedObjects(self, relation, obj, direction=pwobj.RELATION_CHILDS,
1889
- refresh=False):
1890
- """ Get all objects related to obj by a give relation.
1891
-
1892
- :param relation: the relation name to search for.
1893
- :param obj: object from which the relation will be search,
1894
- actually not only this, but all other objects connected
1895
- to this one by the pwobj.RELATION_TRANSFORM.
1896
- :parameter direction: Not used
1897
- :param refresh: If True, cached objects will be refreshed
1898
-
1899
- """
1900
-
1901
- graph = self.getTransformGraph(refresh)
1902
- relations = self.mapper.getRelationsByName(relation)
1903
- connection = self._getConnectedObjects(obj, graph)
1904
-
1905
- objects = []
1906
- objectsDict = {}
1907
-
1908
- for rel in relations:
1909
- pObj = self.getObject(rel[OBJECT_PARENT_ID])
1910
-
1911
- if pObj is None:
1912
- logger.warning("Relation seems to point to a deleted object. "
1913
- "%s: %s" % (OBJECT_PARENT_ID, rel[OBJECT_PARENT_ID]))
1914
- continue
1915
- pExt = rel['object_parent_extended']
1916
- pp = pwobj.Pointer(pObj, extended=pExt)
1917
-
1918
- if pp.getUniqueId() in connection:
1919
- cObj = self.getObject(rel['object_child_id'])
1920
- cExt = rel['object_child_extended']
1921
- cp = pwobj.Pointer(cObj, extended=cExt)
1922
- if cp.hasValue() and cp.getUniqueId() not in objectsDict:
1923
- objects.append(cp)
1924
- objectsDict[cp.getUniqueId()] = True
1925
-
1926
- return objects
1927
-
1928
- def _getConnectedObjects(self, obj, graph):
1929
- """ Given a TRANSFORM graph, return the elements that
1930
- are connected to an object, either children, ancestors or siblings.
1931
- """
1932
- n = graph.getNode(obj.strId())
1933
- # Get the oldest ancestor of a node, before reaching the root node
1934
- while n is not None and not n.getParent().isRoot():
1935
- n = n.getParent()
1936
-
1937
- connection = {}
1938
-
1939
- if n is not None:
1940
- # Iterate recursively all descendants
1941
- for node in n.iterChildren():
1942
- connection[node.pointer.getUniqueId()] = True
1943
- # Add also
1944
- connection[node.pointer.get().strId()] = True
1945
-
1946
- return connection
1947
-
1948
- def isReadOnly(self):
1949
- if getattr(self, 'settings', None) is None:
1950
- return False
1951
-
1952
- return self.settings.getReadOnly()
1953
-
1954
- def isInReadOnlyFolder(self):
1955
- return self._isInReadOnlyFolder
1956
-
1957
- def openedAsReadOnly(self):
1958
- return self.isReadOnly() or self.isInReadOnlyFolder()
1959
-
1960
- def setReadOnly(self, value):
1961
- self.settings.setReadOnly(value)
1962
-
1963
- def fixLinks(self, searchDir):
1964
- logger.info("Fixing project links. Searching at %s" % searchDir)
1965
- runs = self.getRuns()
1966
-
1967
- for prot in runs:
1968
- print (prot)
1969
- broken = False
1970
- if isinstance(prot, ProtImportBase) or prot.getClassName() == "ProtImportMovies":
1971
- logger.info("Import detected")
1972
- for _, attr in prot.iterOutputAttributes():
1973
- for f in attr.getFiles():
1974
- if ':' in f:
1975
- f = f.split(':')[0]
1976
-
1977
- if not os.path.exists(f):
1978
- if not broken:
1979
- broken = True
1980
- logger.info("Found broken links in run: %s" %
1981
- pwutils.magenta(prot.getRunName()))
1982
- logger.info(" Missing: %s" % pwutils.magenta(f))
1983
-
1984
- if os.path.islink(f):
1985
- sourceFile = os.path.realpath(f)
1986
- logger.info(" -> %s" % pwutils.red(sourceFile))
1987
-
1988
- newFile = pwutils.findFile(os.path.basename(sourceFile),
1989
- searchDir,
1990
- recursive=True)
1991
- if newFile:
1992
- logger.info(" Found file %s, creating link... %s" % (newFile,
1993
- pwutils.green(" %s -> %s" % (f, newFile))))
1994
- pwutils.createAbsLink(newFile, f)
1995
-
1996
- @staticmethod
1997
- def cleanProjectName(projectName):
1998
- """ Cleans a project name to avoid common errors
1999
- Use it whenever you want to get the final project name pyworkflow will end up.
2000
- Spaces will be replaced by _ """
2001
-
2002
- return re.sub(r"[^\w\d\-\_]", "-", projectName)
2003
-
2004
-
2005
- class MissingProjectDbException(Exception):
2006
- pass
2007
-
2008
-
2009
- class ModificationNotAllowedException(Exception):
2010
- pass