scipion-pyworkflow 3.10.6__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 (123) hide show
  1. pyworkflow/config.py +131 -67
  2. pyworkflow/constants.py +2 -1
  3. pyworkflow/plugin.py +93 -44
  4. pyworkflow/resources/showj/arrowDown.png +0 -0
  5. pyworkflow/resources/showj/arrowUp.png +0 -0
  6. pyworkflow/resources/showj/background_section.png +0 -0
  7. pyworkflow/resources/showj/colRowModeOff.png +0 -0
  8. pyworkflow/resources/showj/colRowModeOn.png +0 -0
  9. pyworkflow/resources/showj/delete.png +0 -0
  10. pyworkflow/resources/showj/doc_icon.png +0 -0
  11. pyworkflow/resources/showj/download_icon.png +0 -0
  12. pyworkflow/resources/showj/enabled_gallery.png +0 -0
  13. pyworkflow/resources/showj/galleryViewOff.png +0 -0
  14. pyworkflow/resources/showj/galleryViewOn.png +0 -0
  15. pyworkflow/resources/showj/goto.png +0 -0
  16. pyworkflow/resources/showj/menu.png +0 -0
  17. pyworkflow/resources/showj/separator.png +0 -0
  18. pyworkflow/resources/showj/tableViewOff.png +0 -0
  19. pyworkflow/resources/showj/tableViewOn.png +0 -0
  20. pyworkflow/resources/showj/ui-bg_glass_75_e6e6e6_1x400.png +0 -0
  21. pyworkflow/resources/showj/ui-bg_glass_95_fef1ec_1x400.png +0 -0
  22. pyworkflow/resources/showj/ui-bg_highlight-soft_75_cccccc_1x100.png +0 -0
  23. pyworkflow/resources/showj/volumeOff.png +0 -0
  24. pyworkflow/resources/showj/volumeOn.png +0 -0
  25. pyworkflow/viewer.py +23 -1
  26. pyworkflowtests/protocols.py +1 -3
  27. {scipion_pyworkflow-3.10.6.dist-info → scipion_pyworkflow-3.11.0.dist-info}/METADATA +13 -27
  28. scipion_pyworkflow-3.11.0.dist-info/RECORD +71 -0
  29. {scipion_pyworkflow-3.10.6.dist-info → scipion_pyworkflow-3.11.0.dist-info}/WHEEL +1 -1
  30. pyworkflow/apps/__init__.py +0 -29
  31. pyworkflow/apps/pw_manager.py +0 -37
  32. pyworkflow/apps/pw_plot.py +0 -51
  33. pyworkflow/apps/pw_project.py +0 -113
  34. pyworkflow/apps/pw_protocol_list.py +0 -143
  35. pyworkflow/apps/pw_protocol_run.py +0 -51
  36. pyworkflow/apps/pw_run_tests.py +0 -267
  37. pyworkflow/apps/pw_schedule_run.py +0 -322
  38. pyworkflow/apps/pw_sleep.py +0 -37
  39. pyworkflow/apps/pw_sync_data.py +0 -439
  40. pyworkflow/apps/pw_viewer.py +0 -78
  41. pyworkflow/gui/__init__.py +0 -36
  42. pyworkflow/gui/browser.py +0 -726
  43. pyworkflow/gui/canvas.py +0 -1190
  44. pyworkflow/gui/dialog.py +0 -977
  45. pyworkflow/gui/form.py +0 -2637
  46. pyworkflow/gui/graph.py +0 -247
  47. pyworkflow/gui/graph_layout.py +0 -271
  48. pyworkflow/gui/gui.py +0 -566
  49. pyworkflow/gui/matplotlib_image.py +0 -233
  50. pyworkflow/gui/plotter.py +0 -247
  51. pyworkflow/gui/project/__init__.py +0 -25
  52. pyworkflow/gui/project/base.py +0 -192
  53. pyworkflow/gui/project/constants.py +0 -139
  54. pyworkflow/gui/project/labels.py +0 -205
  55. pyworkflow/gui/project/project.py +0 -492
  56. pyworkflow/gui/project/searchprotocol.py +0 -154
  57. pyworkflow/gui/project/searchrun.py +0 -181
  58. pyworkflow/gui/project/steps.py +0 -171
  59. pyworkflow/gui/project/utils.py +0 -332
  60. pyworkflow/gui/project/variables.py +0 -179
  61. pyworkflow/gui/project/viewdata.py +0 -472
  62. pyworkflow/gui/project/viewprojects.py +0 -510
  63. pyworkflow/gui/project/viewprotocols.py +0 -2093
  64. pyworkflow/gui/project/viewprotocols_extra.py +0 -559
  65. pyworkflow/gui/text.py +0 -771
  66. pyworkflow/gui/tooltip.py +0 -185
  67. pyworkflow/gui/tree.py +0 -684
  68. pyworkflow/gui/widgets.py +0 -307
  69. pyworkflow/mapper/__init__.py +0 -26
  70. pyworkflow/mapper/mapper.py +0 -222
  71. pyworkflow/mapper/sqlite.py +0 -1581
  72. pyworkflow/mapper/sqlite_db.py +0 -145
  73. pyworkflow/project/__init__.py +0 -31
  74. pyworkflow/project/config.py +0 -454
  75. pyworkflow/project/manager.py +0 -180
  76. pyworkflow/project/project.py +0 -2007
  77. pyworkflow/protocol/__init__.py +0 -38
  78. pyworkflow/protocol/bibtex.py +0 -48
  79. pyworkflow/protocol/constants.py +0 -87
  80. pyworkflow/protocol/executor.py +0 -471
  81. pyworkflow/protocol/hosts.py +0 -314
  82. pyworkflow/protocol/launch.py +0 -270
  83. pyworkflow/protocol/package.py +0 -42
  84. pyworkflow/protocol/params.py +0 -741
  85. pyworkflow/protocol/protocol.py +0 -2641
  86. pyworkflow/tests/__init__.py +0 -29
  87. pyworkflow/tests/test_utils.py +0 -25
  88. pyworkflow/tests/tests.py +0 -341
  89. pyworkflow/utils/__init__.py +0 -38
  90. pyworkflow/utils/dataset.py +0 -414
  91. pyworkflow/utils/echo.py +0 -104
  92. pyworkflow/utils/graph.py +0 -169
  93. pyworkflow/utils/log.py +0 -284
  94. pyworkflow/utils/path.py +0 -528
  95. pyworkflow/utils/process.py +0 -153
  96. pyworkflow/utils/profiler.py +0 -92
  97. pyworkflow/utils/progressbar.py +0 -154
  98. pyworkflow/utils/properties.py +0 -631
  99. pyworkflow/utils/reflection.py +0 -129
  100. pyworkflow/utils/utils.py +0 -879
  101. pyworkflow/utils/which.py +0 -229
  102. pyworkflow/webservices/__init__.py +0 -8
  103. pyworkflow/webservices/config.py +0 -11
  104. pyworkflow/webservices/notifier.py +0 -162
  105. pyworkflow/webservices/repository.py +0 -59
  106. pyworkflow/webservices/workflowhub.py +0 -74
  107. pyworkflowtests/tests/__init__.py +0 -0
  108. pyworkflowtests/tests/test_canvas.py +0 -72
  109. pyworkflowtests/tests/test_domain.py +0 -45
  110. pyworkflowtests/tests/test_logs.py +0 -74
  111. pyworkflowtests/tests/test_mappers.py +0 -392
  112. pyworkflowtests/tests/test_object.py +0 -507
  113. pyworkflowtests/tests/test_project.py +0 -42
  114. pyworkflowtests/tests/test_protocol_execution.py +0 -142
  115. pyworkflowtests/tests/test_protocol_export.py +0 -78
  116. pyworkflowtests/tests/test_protocol_output.py +0 -158
  117. pyworkflowtests/tests/test_streaming.py +0 -47
  118. pyworkflowtests/tests/test_utils.py +0 -210
  119. scipion_pyworkflow-3.10.6.dist-info/RECORD +0 -140
  120. scipion_pyworkflow-3.10.6.dist-info/dependency_links.txt +0 -1
  121. {scipion_pyworkflow-3.10.6.dist-info → scipion_pyworkflow-3.11.0.dist-info}/entry_points.txt +0 -0
  122. {scipion_pyworkflow-3.10.6.dist-info → scipion_pyworkflow-3.11.0.dist-info}/licenses/LICENSE.txt +0 -0
  123. {scipion_pyworkflow-3.10.6.dist-info → scipion_pyworkflow-3.11.0.dist-info}/top_level.txt +0 -0
@@ -1,2641 +0,0 @@
1
- # **************************************************************************
2
- # *
3
- # * Authors: J.M. De la Rosa Trevin (delarosatrevin@scilifelab.se) [1]
4
- # *
5
- # * [1] SciLifeLab, Stockholm University
6
- # *
7
- # * This program is free software: you can redistribute it and/or modify
8
- # * it under the terms of the GNU General Public License as published by
9
- # * the Free Software Foundation, either version 3 of the License, or
10
- # * (at your option) any later version.
11
- # *
12
- # * This program is distributed in the hope that it will be useful,
13
- # * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
- # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
- # * GNU General Public License for more details.
16
- # *
17
- # * You should have received a copy of the GNU General Public License
18
- # * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
- # *
20
- # * All comments concerning this program package may be sent to the
21
- # * e-mail address 'scipion@cnb.csic.es'
22
- # *
23
- # **************************************************************************
24
- """
25
- This modules contains classes required for the workflow
26
- execution and tracking like: Step and Protocol
27
- """
28
- import os
29
- import json
30
- import threading
31
- import time
32
- from datetime import datetime
33
-
34
- import pyworkflow as pw
35
- from pyworkflow.exceptions import ValidationException, PyworkflowException
36
- from pyworkflow.object import *
37
- import pyworkflow.utils as pwutils
38
- from pyworkflow.utils.log import getExtraLogInfo, STATUS, setDefaultLoggingContext
39
- from pyworkflow.constants import PLUGIN_MODULE_VAR, QUEUE_FOR_JOBS
40
- from .executor import StepExecutor, ThreadStepExecutor, QueueStepExecutor
41
- from .constants import *
42
- from .params import Form, IntParam
43
- from ..utils import getFileSize
44
-
45
-
46
- import logging
47
-
48
- # Get the root logger
49
- logger = logging.getLogger(__name__)
50
-
51
-
52
- class Step(Object):
53
- """ Basic execution unit.
54
- It should define its Input, Output
55
- and define a run method.
56
- """
57
-
58
- def __init__(self, interactive=False, needsGPU=True, **kwargs):
59
- super().__init__()
60
- self._prerequisites = CsvList() # which steps needs to be done first
61
- self.status = String()
62
- self.initTime = String()
63
- self.endTime = String()
64
- self._error = String()
65
- self.interactive = Boolean(interactive)
66
- self._resultFiles = String()
67
- self._needsGPU = Boolean(needsGPU)
68
- self._index = None
69
-
70
- def needsGPU(self) -> bool:
71
- return self._needsGPU.get()
72
-
73
- def getIndex(self):
74
- return self._index
75
-
76
- def setIndex(self, newIndex):
77
- self._index = newIndex
78
-
79
- def getPrerequisites(self):
80
- return self._prerequisites
81
-
82
- def addPrerequisites(self, *newPrerequisites):
83
- for p in newPrerequisites:
84
- self._prerequisites.append(p)
85
-
86
- def setPrerequisites(self, *newPrerequisites):
87
- self._prerequisites.clear()
88
- self.addPrerequisites(*newPrerequisites)
89
-
90
- def _preconditions(self):
91
- """ Check if the necessary conditions to
92
- step execution are met"""
93
- return self._validate() == []
94
-
95
- def _postconditions(self):
96
- """ Check if the step have done well its task
97
- and accomplish its results"""
98
- return True
99
-
100
- def _run(self):
101
- """ This is the function that will do the real job.
102
- It should be override by sub-classes."""
103
- pass
104
-
105
- def setRunning(self):
106
- """ The the state as STATE_RUNNING and
107
- set the init and end times.
108
- """
109
- self.initTime.set(dt.datetime.now())
110
- self.endTime.set(None)
111
- self.status.set(STATUS_RUNNING)
112
- self._error.set(None) # Clean previous error message
113
-
114
- def getError(self):
115
- return self._error
116
-
117
- def getErrorMessage(self):
118
- return self.getError().get('')
119
-
120
- def setFailed(self, msg):
121
- """ Set the run failed and store an error message. """
122
- self._finalizeStep(STATUS_FAILED, msg=msg)
123
-
124
- def setAborted(self):
125
- """ Set the status to aborted and updates the endTime. """
126
- self._finalizeStep(STATUS_ABORTED, "Aborted by user.")
127
-
128
- def setFinished(self):
129
- """ Set the status to finish updates the end time """
130
- self._finalizeStep(STATUS_FINISHED)
131
-
132
- def _finalizeStep(self, status, msg=None):
133
- """ Closes the step, setting up the endTime and optionally an error message"""
134
- self.endTime.set(dt.datetime.now())
135
- if msg:
136
- self._error.set(msg)
137
- self.status.set(status)
138
-
139
- def setSaved(self):
140
- """ Set the status to saved and updated the endTime. """
141
- self.initTime.set(None)
142
- self.endTime.set(None)
143
- self.status.set(STATUS_SAVED)
144
- self._error.set(None) # Clean previous error message
145
-
146
- def getStatus(self):
147
- return self.status.get(STATUS_NEW)
148
-
149
- def getElapsedTime(self, default=dt.timedelta()):
150
- """ Return the time that took to run
151
- (or the actual running time if still is running )
152
- """
153
- elapsed = default
154
-
155
- if self.initTime.hasValue():
156
- t1 = self.initTime.datetime()
157
-
158
- if self.endTime.hasValue():
159
- t2 = self.endTime.datetime()
160
- else:
161
- t2 = dt.datetime.now()
162
-
163
- elapsed = t2 - t1
164
-
165
- return elapsed
166
-
167
- def setStatus(self, value):
168
- return self.status.set(value)
169
-
170
- def isNew(self):
171
- return self.getStatus() == STATUS_NEW
172
-
173
- def setInteractive(self, value):
174
- return self.interactive.set(value)
175
-
176
- def isActive(self):
177
- return self.getStatus() in ACTIVE_STATUS
178
-
179
- def isFinished(self):
180
- return self.getStatus() == STATUS_FINISHED
181
-
182
- def isRunning(self):
183
- return self.getStatus() == STATUS_RUNNING
184
-
185
- def isFailed(self):
186
- return self.getStatus() == STATUS_FAILED
187
-
188
- def isSaved(self):
189
- return self.getStatus() == STATUS_SAVED
190
-
191
- def isScheduled(self):
192
- return self.getStatus() == STATUS_SCHEDULED
193
-
194
- def isAborted(self):
195
- return self.getStatus() == STATUS_ABORTED
196
-
197
- def isLaunched(self):
198
- return self.getStatus() == STATUS_LAUNCHED
199
-
200
- def isInteractive(self):
201
- return self.interactive.get()
202
-
203
- def isWaiting(self):
204
- return self.getStatus() == STATUS_WAITING
205
-
206
- def run(self):
207
- """ Do the job of this step"""
208
- self.setRunning()
209
- try:
210
- self._run()
211
- self.endTime.set(dt.datetime.now())
212
- if self.status.get() == STATUS_RUNNING:
213
- if self.isInteractive():
214
- # If the Step is interactive, after run
215
- # it will be waiting for use to mark it as DONE
216
- status = STATUS_INTERACTIVE
217
- else:
218
- status = STATUS_FINISHED
219
- self.status.set(status)
220
-
221
- except PyworkflowException as e:
222
- logger.info(pwutils.redStr(str(e)))
223
- self.setFailed(str(e))
224
- except Exception as e:
225
- self.setFailed(str(e))
226
- import traceback
227
- traceback.print_exc()
228
- # raise #only in development
229
- # finally:
230
- # self.endTime.set(dt.datetime.now())
231
-
232
-
233
- class FunctionStep(Step):
234
- """ This is a Step wrapper around a normal function
235
- This class will ease the insertion of Protocol function steps
236
- through the function _insertFunctionStep"""
237
-
238
- def __init__(self, func=None, funcName=None, *funcArgs, wait=False, interactive=False, needsGPU=True):
239
- """
240
- Params:
241
- func: the function that will be executed.
242
- funcName: the name assigned to that function (will be stored)
243
- *funcArgs: argument list passed to the function (serialized and stored)
244
- **kwargs: extra parameters.
245
- """
246
- super().__init__(interactive=interactive, needsGPU=needsGPU)
247
- self._func = func # Function should be set before run
248
- self._args = funcArgs
249
- self.funcName = String(funcName)
250
- self.argsStr = String(json.dumps(funcArgs, default=lambda x: None))
251
- if wait:
252
- self.setStatus(STATUS_WAITING)
253
-
254
- def _runFunc(self):
255
- """ Return the possible result files after running the function. """
256
- return self._func(*self._args)
257
-
258
- def _run(self):
259
- """ Run the function and check the result files if any. """
260
- resultFiles = self._runFunc()
261
- if isinstance(resultFiles, str):
262
- resultFiles = [resultFiles]
263
- if resultFiles and len(resultFiles):
264
- missingFiles = pwutils.missingPaths(*resultFiles)
265
- if len(missingFiles):
266
- raise Exception('Missing filePaths: ' + ' '.join(missingFiles))
267
- self._resultFiles.set(json.dumps(resultFiles))
268
-
269
- def _postconditions(self):
270
- """ This type of Step, will simply check
271
- as postconditions that the result filePaths exists"""
272
- if not self._resultFiles.hasValue():
273
- return True
274
- filePaths = json.loads(self._resultFiles.get())
275
-
276
- return len(pwutils.missingPaths(*filePaths)) == 0
277
-
278
- def __eq__(self, other):
279
- """ Compare with other FunctionStep"""
280
- return (self.funcName == other.funcName and
281
- self.argsStr == other.argsStr)
282
-
283
- def __ne__(self, other):
284
- return not self.__eq__(other)
285
-
286
- def __str__(self):
287
- return "%s - %s" % (self._objId ,self.funcName.get())
288
-
289
-
290
- class RunJobStep(FunctionStep):
291
- """ This Step will wrapper the commonly used function runJob
292
- for launching specific programs with some parameters.
293
- The runJob function should be provided by the protocol
294
- when inserting a new RunJobStep"""
295
-
296
- def __init__(self, runJobFunc=None, programName=None, arguments=None,
297
- resultFiles=[], **kwargs):
298
- FunctionStep.__init__(self, runJobFunc, 'runJob', programName,
299
- arguments)
300
- # Number of mpi and threads used to run the program
301
- self.__runJob = runJobFunc # Store the current function to run the job
302
- self.mpi = 1
303
- self.threads = 1
304
-
305
- def _runFunc(self):
306
- """ Wrap around runJob function"""
307
- # We know that:
308
- # _func: is the runJob function
309
- # _args[0]: is the program name
310
- # _args[1]: is the arguments to the program
311
- return self._func(None, self._args[0], self._args[1],
312
- numberOfMpi=self.mpi, numberOfThreads=self.threads)
313
- # TODO: Add the option to return resultFiles
314
-
315
- def __str__(self):
316
- return self._args[0] # return program name
317
-
318
-
319
- class StepSet(Set):
320
- """ Special type of Set for storing steps. """
321
-
322
- def __init__(self, filename=None, prefix='',
323
- mapperClass=None, **kwargs):
324
- Set.__init__(self, filename, prefix, mapperClass, classesDict=globals(),
325
- **kwargs)
326
-
327
-
328
- class Protocol(Step):
329
- """ The Protocol is a higher type of Step.
330
- It also have the inputs, outputs and other Steps properties,
331
- but contains a list of steps that are executed
332
- """
333
-
334
- # Version where protocol appeared first time
335
- _stepsCheckSecs = pw.Config.getStepsCheckSeconds()
336
- # Protocol develop status: PROD, BETA, NEW
337
- _devStatus = pw.PROD
338
-
339
- """" Possible Outputs:
340
- This is an optional but recommended attribute to fill.
341
- It has to be an enum with names being the name of the output and value the class of the output:
342
-
343
- class MyOutput(enum.Enum):
344
- outputMicrographs = SetOfMicrographs
345
- outputMicrographDW = SetOfMicrographs
346
-
347
- When defining outputs you can, optionally, use this enum like:
348
- self._defineOutputs(**{MyOutput.outputMicrographs.name, setOfMics})
349
- It will help to keep output names consistently
350
-
351
- Alternative an inline dictionary will work:
352
- _possibleOutputs = {"outputMicrographs" : SetOfMicrographs}
353
-
354
- For a more fine detailed/dynamic output based on parameters, you can overwrite the getter:
355
- getPossibleOutputs() in your protocol.
356
-
357
- """
358
- _possibleOutputs = None
359
-
360
- # Cache package and plugin
361
- _package = None
362
- _plugin = None
363
-
364
- # Maybe this property can be inferred from the
365
- # prerequisites of steps, but is easier to keep it
366
- stepsExecutionMode = STEPS_SERIAL
367
-
368
- def modeSerial(self):
369
- """ Returns true if steps are run one after another"""
370
- # Maybe this property can be inferred from the
371
- # prerequisites of steps, but is easier to keep it
372
- return self.stepsExecutionMode == STEPS_SERIAL
373
-
374
- def modeParallel(self):
375
- """ Returns true if steps are run in parallel"""
376
- return not self.modeSerial()
377
-
378
- def __init__(self, **kwargs):
379
- Step.__init__(self, **kwargs)
380
- self._size = None
381
- self._steps = [] # List of steps that will be executed
382
- self._newSteps = False # Boolean to annotate when there are new steps added to the above list. And need persistence.
383
- # All generated filePaths should be inside workingDir
384
- self.workingDir = String(kwargs.get('workingDir', '.'))
385
- self.mapper = kwargs.get('mapper', None)
386
- self._inputs = []
387
- self._outputs = CsvList()
388
- # This flag will be used to annotate it output are already "migrated"
389
- # and available in the _outputs list. Therefore iterating
390
- self._useOutputList = Boolean(False)
391
- # Expert level needs to be defined before parsing params
392
- self.expertLevel = Integer(kwargs.get('expertLevel', LEVEL_NORMAL))
393
- self._definition = Form(self)
394
- self._defineParams(self._definition)
395
- self._createVarsFromDefinition(**kwargs)
396
- self._log = logger
397
- self._buffer = '' # text buffer for reading log files
398
- # Project to which the protocol belongs
399
- self.__project = kwargs.get('project', None)
400
- # Filename templates dict that will be used by _getFileName
401
- self.__filenamesDict = {}
402
-
403
- # This will be used at project load time to check if
404
- # we need to update the protocol with the data from run.db
405
- self.lastUpdateTimeStamp = String()
406
-
407
- # For non-parallel protocols mpi=1 and threads=1
408
- self.allowMpi = hasattr(self, 'numberOfMpi')
409
- if not self.allowMpi:
410
- self.numberOfMpi = Integer(1)
411
-
412
- self.allowThreads = hasattr(self, 'numberOfThreads')
413
-
414
- if not self.allowThreads:
415
- self.numberOfThreads = Integer(1)
416
-
417
- # Check if MPI or threads are passed in **kwargs, mainly used in tests
418
- if 'numberOfMpi' in kwargs:
419
- self.numberOfMpi.set(kwargs.get('numberOfMpi'))
420
-
421
- if 'numberOfThreads' in kwargs:
422
- self.numberOfThreads.set(kwargs.get('numberOfThreads'))
423
-
424
- if not hasattr(self, 'hostName'):
425
- self.hostName = String(kwargs.get('hostName', 'localhost'))
426
-
427
- if not hasattr(self, 'hostFullName'):
428
- self.hostFullName = String()
429
-
430
-
431
- # Run mode
432
- self.runMode = Integer(kwargs.get('runMode', MODE_RESUME))
433
- # Use queue system?
434
- self._useQueue = Boolean(pw.Config.SCIPION_USE_QUEUE)
435
- # Store a json string with queue name
436
- # and queue parameters (only meaningful if _useQueue=True)
437
- self._queueParams = String()
438
- self.queueShown = False
439
- self._jobId = CsvList() # Store queue job ids
440
- self._pid = Integer()
441
- self._stepsExecutor = None
442
- self._stepsDone = Integer(0)
443
- self._cpuTime = Integer(0)
444
- self._numberOfSteps = Integer(0)
445
- # For visualization
446
- self.allowHeader = Boolean(True)
447
- # Create an String variable to allow some protocol to precompute
448
- # the summary message
449
- self.summaryVar = String()
450
- self.methodsVar = String()
451
- # Create a variable to know if the protocol has expert params
452
- self._hasExpert = None
453
-
454
- # Store warnings here
455
- self.summaryWarnings = []
456
- # Get a lock for threading execution
457
- self._lock = threading.RLock() # Recursive locks allows a thread to acquire lock on same object more
458
- # than one time, thus avoiding deadlock situation. This fixed the concurrency problems we had before.
459
- self.forceSchedule = Boolean(False)
460
-
461
- def _storeAttributes(self, attrList, attrDict):
462
- """ Store all attributes in attrDict as
463
- attributes of self, also store the key in attrList.
464
- """
465
- for key, value in attrDict.items():
466
- if key not in attrList:
467
- attrList.append(key)
468
- setattr(self, key, value)
469
-
470
- def _defineInputs(self, **kwargs):
471
- """ This function should be used to define
472
- those attributes considered as Input.
473
- """
474
- self._storeAttributes(self._inputs, kwargs)
475
-
476
- def _defineOutputs(self, **kwargs):
477
- """ This function should be used to specify
478
- expected outputs.
479
- """
480
- for k, v in kwargs.items():
481
- if hasattr(self, k):
482
- self._deleteChild(k, v)
483
- self._insertChild(k, v)
484
-
485
- # Store attributes in _output (this does not persist them!)
486
- self._storeAttributes(self._outputs, kwargs)
487
-
488
- # Persist outputs list
489
- self._insertChild("_outputs", self._outputs)
490
- self._useOutputList.set(True)
491
- self._insertChild("_useOutputList", self._useOutputList)
492
-
493
- def _closeOutputSet(self):
494
- """Close all output set"""
495
- for outputName, output in self.iterOutputAttributes():
496
- if isinstance(output, Set) and output.isStreamOpen():
497
- self.__tryUpdateOutputSet(outputName, output, state=Set.STREAM_CLOSED)
498
-
499
- def _updateOutputSet(self, outputName, outputSet,
500
- state=Set.STREAM_OPEN):
501
- """ Use this function when updating an Stream output set.
502
- """
503
- self.__tryUpdateOutputSet(outputName, outputSet, state)
504
-
505
- def __tryUpdateOutputSet(self, outputName, outputSet,
506
- state=Set.STREAM_OPEN, tries=1, firstException=None):
507
- try:
508
- # Update the set with the streamState value (either OPEN or CLOSED)
509
- outputSet.setStreamState(state)
510
-
511
- if self.hasAttribute(outputName):
512
- outputSet.write() # Write to commit changes
513
- outputAttr = getattr(self, outputName)
514
- # Copy the properties to the object contained in the protocol
515
- # Default Set.copy ignores some attributes like size or mapperPath.
516
- # In this case we want all to be copied
517
- outputAttr.copy(outputSet, copyId=False, ignoreAttrs=[])
518
- # Persist changes
519
- self._store(outputAttr)
520
- else:
521
- # Here the defineOutputs function will call the write() method
522
- self._defineOutputs(**{outputName: outputSet})
523
- self._store(outputSet)
524
- # Close set database to avoid locking it
525
- outputSet.close()
526
-
527
- except Exception as ex:
528
-
529
- if tries > pw.Config.getUpdateSetAttempts():
530
- raise BlockingIOError("Can't update %s (output) of %s after %s attempts. Reason: %s. "
531
- "Concurrency, a non writable file system or a quota exceeded could be among the causes." %
532
- (outputName, self,tries-1, ex)) from firstException
533
- else:
534
- logger.warning("Trying to update %s (output) of protocol %s, attempt=%d: %s " % (outputName, self, tries, ex))
535
- time.sleep(pw.Config.getUpdateSetAttemptsWait())
536
- self.__tryUpdateOutputSet(outputName, outputSet, state,
537
- tries + 1, firstException= ex if tries==1 else firstException)
538
-
539
- def hasExpert(self):
540
- """ This function checks if the protocol has
541
- any expert parameter"""
542
- if self._hasExpert is None:
543
- self._hasExpert = False
544
- for paraName, param in self._definition.iterAllParams():
545
- if param.isExpert():
546
- self._hasExpert = True
547
- break
548
-
549
- return self._hasExpert
550
-
551
- def getProject(self):
552
- return self.__project
553
-
554
- def setProject(self, project):
555
- self.__project = project
556
-
557
- @staticmethod
558
- def hasDefinition(cls):
559
- """ Check if the protocol has some definition.
560
- This can help to detect "abstract" protocol that
561
- only serve as base for other, not to be instantiated.
562
- """
563
- return hasattr(cls, '_definition')
564
-
565
- @classmethod
566
- def isNewDev(cls):
567
- if cls._devStatus == pw.NEW:
568
- return True
569
-
570
- @classmethod
571
- def isBeta(cls):
572
- return cls._devStatus == pw.BETA
573
-
574
- @classmethod
575
- def isUpdated(cls):
576
- return cls._devStatus == pw.UPDATED
577
-
578
- def getDefinition(self):
579
- """ Access the protocol definition. """
580
- return self._definition
581
-
582
- def getParam(self, paramName):
583
- """ Return a _definition param give its name. """
584
- return self._definition.getParam(paramName)
585
-
586
- def getEnumText(self, paramName):
587
- """ This function will retrieve the text value
588
- of an enum parameter in the definition, taking the actual value in
589
- the protocol.
590
-
591
- :param paramName: the name of the enum param.
592
-
593
- :returns: the string value corresponding to the enum choice.
594
-
595
- """
596
- index = getattr(self, paramName).get()
597
- return self.getParam(paramName).choices[index]
598
-
599
- def evalParamCondition(self, paramName):
600
- """ Eval if the condition of paramName in _definition
601
- is satisfied with the current values of the protocol attributes.
602
- """
603
- return self._definition.evalParamCondition(paramName)
604
-
605
- def evalExpertLevel(self, paramName):
606
- """ Return the expert level evaluation for a param with the given name.
607
- """
608
- return self.evalParamExpertLevel(self.getParam(paramName))
609
-
610
- def evalParamExpertLevel(self, param):
611
- """ Return True if the param has an expert level is less than
612
- the one for the whole protocol.
613
- """
614
- return param.expertLevel.get() <= self.expertLevel.get()
615
-
616
- def iterDefinitionAttributes(self):
617
- """ Iterate over all the attributes from definition. """
618
- for paramName, _ in self._definition.iterParams():
619
- yield paramName, getattr(self, paramName)
620
-
621
- def getDefinitionDict(self):
622
- """ Similar to getObjDict, but only for those
623
- params that are in the form.
624
- This function is used for export protocols as json text file.
625
- """
626
- d = OrderedDict()
627
- d['object.className'] = self.getClassName()
628
- d['object.id'] = self.strId()
629
- d['object.label'] = self.getObjLabel()
630
- d['object.comment'] = self.getObjComment()
631
- d['_useQueue'] = self._useQueue.getObjValue()
632
- d['_prerequisites'] = self._prerequisites.getObjValue()
633
-
634
- if self._queueParams:
635
- d['_queueParams'] = self._queueParams.get()
636
-
637
- od = self.getObjDict(includePointers=True)
638
-
639
- for attrName in od:
640
- if self.getParam(attrName) is not None:
641
- d[attrName] = od[attrName]
642
-
643
- return d
644
-
645
- def processImportDict(self, importDict, importDir):
646
- """
647
- This function is used when we import a workflow from a json to process or
648
- adjust the json data for reproducibility purposes e.g. resolve relative paths
649
- Params:
650
- importDict: Dict of the protocol that we got from the json
651
- importDir: dir of the json we're importing
652
- """
653
- return importDict
654
-
655
- def iterDefinitionSections(self):
656
- """ Iterate over all the section of the definition. """
657
- for section in self._definition.iterSections():
658
- yield section
659
-
660
- def iterInputAttributes(self):
661
- """ Iterate over the main input parameters
662
- of this protocol. Now the input are assumed to be these attribute
663
- which are pointers and have no condition.
664
- """
665
- for key, attr in self.getAttributes():
666
- if not isinstance(attr, Object):
667
- raise Exception('Attribute %s have been overwritten to type %s '
668
- % (key, type(attr)))
669
- if isinstance(attr, PointerList) and attr.hasValue():
670
- for item in attr:
671
- # the same key is returned for all items inside the
672
- # PointerList, this is used in viewprotocols.py
673
- # to group them inside the same tree element
674
- yield key, item
675
- if attr.isPointer() and attr.hasValue():
676
- yield key, attr
677
-
678
- # Consider here scalars with pointers inside
679
- elif isinstance(attr, Scalar) and attr.hasPointer():
680
- # Scheduling was stale cause this Scalar with pointers where not returned
681
- #if attr.get() is not None:
682
- yield key, attr.getPointer()
683
-
684
- def iterInputPointers(self):
685
- """ This function is similar to iterInputAttributes, but it yields
686
- all input Pointers, independently if they have value or not.
687
- """
688
- for key, attr in self.getAttributes():
689
- if not isinstance(attr, Object):
690
- raise Exception('Attribute %s have been overwritten to type %s '
691
- % (key, type(attr)))
692
- if isinstance(attr, PointerList) and attr.hasValue():
693
- for item in attr:
694
- # the same key is returned for all items inside the
695
- # PointerList, this is used in viewprotocols.py
696
- # to group them inside the same tree element
697
- yield key, item
698
- elif attr.isPointer():
699
- yield key, attr
700
-
701
- def getProtocolsToUpdate(self):
702
- """
703
- This function returns a list of protocols ids that need to update
704
- their database to launch this protocol (this method is only used
705
- when a WORKFLOW is restarted or continued).
706
- Actions done here are:
707
-
708
- #. Iterate over the main input Pointer of this protocol
709
- (here, 3 different cases are analyzed):
710
-
711
- A #. When the pointer points to a protocol
712
-
713
- B #. When the pointer points to another object (INDIRECTLY).
714
- The pointer has an _extended value (new parameters configuration
715
- in the protocol)
716
-
717
- C #. When the pointer points to another object (DIRECTLY).
718
-
719
- - The pointer has not an _extended value (old parameters
720
- configuration in the protocol)
721
-
722
- #. The PROTOCOL to which the pointer points is determined and saved in
723
- the list
724
-
725
- #. If this pointer points to a set (case B and C):
726
-
727
- - Iterate over the main attributes of the set
728
- - if attribute is a pointer then we add the pointed protocol to the ids list
729
- """
730
- protocolIds = []
731
- protocol = None
732
- for key, attrInput in self.iterInputAttributes():
733
- outputs = []
734
- output = attrInput.get()
735
- if isinstance(output, Protocol): # case A
736
- protocol = output
737
- for _, protOutput in protocol.iterOutputAttributes():
738
- outputs.append(protOutput) # for case A store all the protocols outputs
739
- else:
740
- if attrInput.hasExtended(): # case B
741
- protocol = attrInput.getObjValue()
742
- else: # case C
743
-
744
- if self.getProject() is not None:
745
- protocol = self.getProject().getRunsGraph(refresh=True).getNode(str(output.getObjParentId())).run
746
- else:
747
- # This is a problem, since protocols coming from
748
- # Pointers do not have the __project set.
749
- # We do not have a clear way to get the protocol if
750
- # we do not have the project object associated
751
- # This case implies Direct Pointers to Sets
752
- # (without extended): hopefully this will only be
753
- # created from tests
754
- logger.warning("Can't get %s info from %s."
755
- " This could render unexpected results when "
756
- "scheduling protocols. Value: %s" % (key, self, attrInput))
757
- continue
758
-
759
- if output is not None:
760
- outputs.append(output)
761
-
762
- # If there is output
763
- if outputs:
764
- # Iter over all the outputs
765
- for output in outputs:
766
- # For each output attribute: Looking for pointers like SetOfCoordinates.micrographs
767
- for k, attr in output.getAttributes():
768
- # If it's a pointer
769
- if isinstance(attr, Pointer):
770
- logger.debug("Pointer found in output: %s.%s (%s)" % (output, k, attr))
771
- prot = attr.getObjValue()
772
- if prot is not None:
773
- if isinstance(prot, Protocol):
774
- protocolIds.append(prot.getObjId())
775
- else:
776
- logger.warning(f"We have found that {output}.{key} points to {attr} "
777
- f"and is a direct pointer. Direct pointers are less reliable "
778
- f"in streaming scenarios. Developers should avoid them.")
779
-
780
- protocolIds.append(protocol.getObjId())
781
-
782
- return protocolIds
783
-
784
- def getInputStatus(self):
785
- """ Returns if any input pointer is not ready yet and if there is
786
- any pointer to an open set
787
- """
788
- emptyPointers = False
789
- openSetPointer = False
790
- emptyInput = False
791
-
792
- for paramName, attr in self.iterInputPointers():
793
-
794
- param = self.getParam(paramName)
795
- # Issue #1597: New data loaded with old code.
796
- # If the input pointer is not a param:
797
- # This could happen in backward incompatibility cases,
798
- # Protocol has an attribute (inputPointer) but class does not define
799
- # if in the define params.
800
- if param is None:
801
- print("%s attribute is not defined as parameter. "
802
- "This could happen when loading new code with older "
803
- "scipion versions." % paramName)
804
- continue
805
-
806
- condition = self.evalParamCondition(paramName)
807
-
808
- obj = attr.get()
809
- if isinstance(obj, Protocol) and obj.getStatus() == STATUS_SAVED: # the pointer points to a protocol
810
- emptyPointers = True
811
- if obj is None and attr.hasValue():
812
- emptyPointers = True
813
- if condition and obj is None and not param.allowsNull:
814
- if not attr.hasValue():
815
- emptyInput = True
816
-
817
- if not self.worksInStreaming() and isinstance(obj, Set) and obj.isStreamOpen():
818
- openSetPointer = True
819
-
820
- return emptyInput, openSetPointer, emptyPointers
821
-
822
- def iterOutputAttributes(self, outputClass=None, includePossible=False):
823
- """ Iterate over the outputs produced by this protocol. """
824
-
825
- iterator = self._iterOutputsNew if self._useOutputList else self._iterOutputsOld
826
-
827
- hasOutput=False
828
-
829
- # Iterate through actual outputs
830
- for key, attr in iterator():
831
- if outputClass is None or isinstance(attr, outputClass):
832
- hasOutput = True
833
- yield key, attr
834
-
835
- # NOTE: This will only happen in case there is no actual output.
836
- # There is no need to avoid duplication of actual output and possible output.
837
- if includePossible and not hasOutput and self.getPossibleOutputs() is not None:
838
- for possibleOutput in self.getPossibleOutputs():
839
- if isinstance(possibleOutput, str):
840
- yield possibleOutput, self._possibleOutputs[possibleOutput]
841
- else:
842
- yield possibleOutput.name, possibleOutput.value
843
-
844
- def getPossibleOutputs(self):
845
- return self._possibleOutputs
846
-
847
- def _iterOutputsNew(self):
848
- """ This methods iterates through a list where outputs have been
849
- annotated"""
850
-
851
- # Loop through the output list
852
- for attrName in self._outputs:
853
-
854
- # FIX: When deleting manually an output, specially for interactive protocols.
855
- # The _outputs is properly deleted in projects.sqlite, not it's run.db remains.
856
- # When the protocol is updated from run.db it brings the outputs that were deleted
857
- if hasattr(self, attrName):
858
- # Get it from the protocol
859
- attr = getattr(self, attrName)
860
-
861
- yield attrName, attr
862
- else:
863
- self._outputs.remove(attrName)
864
-
865
- def _iterOutputsOld(self):
866
- """ This method iterates assuming the old model: any EMObject attribute
867
- is an output."""
868
- # Iterate old Style:
869
-
870
- try:
871
- domain = self.getClassDomain()
872
- except Exception as e:
873
- print(e)
874
- print("Protocol in workingdir ", self.getWorkingDir(), " is of an unknown class")
875
- print("Maybe the class name has changed")
876
- return "none", None
877
-
878
- for key, attr in self.getAttributes():
879
- if isinstance(attr, domain._objectClass):
880
- yield key, attr
881
- return
882
-
883
- def isInStreaming(self):
884
- # For the moment let's assume a protocol is in streaming
885
- # if at least one of the output sets is in STREAM_OPEN state
886
- for paramName, attr in self.iterOutputAttributes():
887
- if isinstance(attr, Set):
888
- if attr.isStreamOpen():
889
- return True
890
- return False
891
-
892
- @classmethod
893
- def worksInStreaming(cls):
894
- # A protocol should work in streaming if it implements the stepCheck()
895
- # Get the stepCheck method from the Protocol
896
- baseStepCheck = Protocol._stepsCheck
897
- ownStepCheck = cls._stepsCheck
898
-
899
- return not pwutils.isSameFunction(baseStepCheck, ownStepCheck)
900
-
901
- def allowsGpu(self):
902
- """ Returns True if this protocol allows GPU computation. """
903
- return self.hasAttribute(GPU_LIST)
904
-
905
- def requiresGpu(self):
906
- """ Return True if this protocol can only be executed in GPU. """
907
- return self.allowsGpu() and not self.hasAttribute(USE_GPU)
908
-
909
- def usesGpu(self):
910
- return self.allowsGpu() and self.getAttributeValue(USE_GPU, True)
911
-
912
- def getGpuList(self):
913
- if not self.allowsGpu():
914
- return []
915
-
916
- return pwutils.getListFromRangeString(self.gpuList.get())
917
-
918
- def getOutputsSize(self):
919
- return sum(1 for _ in self.iterOutputAttributes())
920
-
921
- def getOutputFiles(self):
922
- """ Return the output files produced by this protocol.
923
- This can be used in web to download results back.
924
- """
925
- # By default return the output file of each output attribute
926
- s = set()
927
-
928
- for _, attr in self.iterOutputAttributes():
929
- s.update(attr.getFiles())
930
-
931
- return s
932
-
933
- def getOutputSuffix(self, outputPrefix):
934
- """ Return the suffix to be used for a new output.
935
- For example: output3DCoordinates7.
936
- It should take into account previous outputs
937
- and number with a higher value.
938
- """
939
- maxCounter = -1
940
- for attrName, _ in self.iterOutputAttributes():
941
- suffix = attrName.replace(outputPrefix, '')
942
- try:
943
- counter = int(suffix)
944
- except:
945
- counter = 1 # when there is not number assume 1
946
- maxCounter = max(counter, maxCounter)
947
-
948
- return str(maxCounter + 1) if maxCounter > 0 else '' # empty if not output
949
-
950
- def getNextOutputName(self, outputPrefix):
951
- """Return the name to be used for a new output."""
952
- return outputPrefix + self.getOutputSuffix(outputPrefix)
953
-
954
- def copyDefinitionAttributes(self, other):
955
- """ Copy definition attributes to other protocol. """
956
- for paramName, _ in self.iterDefinitionAttributes():
957
- self.copyAttributes(other, paramName)
958
-
959
- def _createVarsFromDefinition(self, **kwargs):
960
- """ This function will setup the protocol instance variables
961
- from the Protocol Class definition, taking into account
962
- the variable type and default values.
963
- """
964
- if hasattr(self, '_definition'):
965
- for paramName, param in self._definition.iterParams():
966
- # Create the var with value coming from kwargs or from
967
- # the default param definition
968
- try:
969
- value = kwargs.get(paramName, param.default.get())
970
- var = param.paramClass(value=value)
971
- setattr(self, paramName, var)
972
- except Exception as e:
973
- raise ValueError("Can't create parameter '%s' and set it to %s" %
974
- (paramName, value)) from e
975
- else:
976
- print("FIXME: Protocol '%s' has not DEFINITION"
977
- % self.getClassName())
978
-
979
- def _getFileName(self, key, **kwargs):
980
- """ This function will retrieve filenames given a key and some
981
- keywords arguments. The __filenamesDict attribute should be
982
- updated with templates that accept the given keys.
983
- """
984
- return self.__filenamesDict[key] % kwargs
985
-
986
- def _updateFilenamesDict(self, fnDict):
987
- """ Update the dictionary with templates that will be used
988
- by the _getFileName function.
989
- """
990
- self.__filenamesDict.update(fnDict)
991
-
992
- def _store(self, *objs):
993
- """ Stores objects of the protocol using the mapper.
994
- If not objects are passed, the whole protocol is stored.
995
- """
996
- if self.mapper is not None:
997
- with self._lock: # _lock is now a Rlock object (recursive locks)
998
- if len(objs) == 0:
999
- self.mapper.store(self)
1000
- else:
1001
- for obj in objs:
1002
- self.mapper.store(obj)
1003
- self.mapper.commit()
1004
-
1005
- def _insertChild(self, key, child):
1006
- """ Insert a new child not stored previously.
1007
- If stored previously, _store should be used.
1008
- The child will be set as self.key attribute
1009
- """
1010
- try:
1011
- setattr(self, key, child)
1012
- if self.hasObjId():
1013
- self.mapper.insertChild(self, key, child)
1014
- except Exception as ex:
1015
- print("Error with child '%s', value=%s, type=%s"
1016
- % (key, child, type(child)))
1017
- raise ex
1018
-
1019
- def _deleteChild(self, key, child):
1020
- """ Delete a child from the mapper. """
1021
- self.mapper.delete(child)
1022
-
1023
- def _insertAllSteps(self):
1024
- """ Define all the steps that will be executed. """
1025
- pass
1026
-
1027
- def _defineParams(self, form):
1028
- """ Define the input parameters that will be used.
1029
- Params:
1030
- form: this is the form to be populated with sections and params.
1031
- """
1032
- pass
1033
-
1034
- def __insertStep(self, step, prerequisites=None):
1035
- """ Insert a new step in the list.
1036
-
1037
- :param prerequisites: a single integer or a list with the steps index that need to be done
1038
- previous to the current one."""
1039
-
1040
- if prerequisites is None:
1041
- if len(self._steps):
1042
- # By default add the previous step as prerequisite
1043
- step.addPrerequisites(len(self._steps))
1044
- else:
1045
- # Allow passing just an id
1046
- if not isinstance(prerequisites, list):
1047
- prerequisites = [prerequisites]
1048
-
1049
- step.addPrerequisites(*prerequisites)
1050
-
1051
- self._steps.append(step)
1052
- self._newSteps = True
1053
- # Setup and return step index
1054
- step.setIndex(len(self._steps))
1055
-
1056
- return step.getIndex()
1057
-
1058
- def setRunning(self):
1059
- """ Do not reset the init time in RESUME_MODE"""
1060
- previousStart = self.initTime.get()
1061
- super().setRunning()
1062
- if self.getRunMode() == MODE_RESUME and previousStart is not None:
1063
- self.initTime.set(previousStart)
1064
- else:
1065
- self._cpuTime.set(0)
1066
-
1067
- def setAborted(self):
1068
- """ Abort the protocol, finalize the steps and close all open sets"""
1069
- try:
1070
- super().setAborted()
1071
- self._updateSteps(lambda step: step.setAborted(), where="status='%s'" % STATUS_RUNNING)
1072
- self._closeOutputSet()
1073
- except Exception as e:
1074
- print("An error occurred aborting the protocol (%s)" % e)
1075
-
1076
- def setFailed(self, msg):
1077
- """ Set the run failed and close all open sets. """
1078
- super().setFailed(msg)
1079
- self._closeOutputSet()
1080
-
1081
- def _finalizeStep(self, status, msg=None):
1082
- """ Closes the step and setting up the protocol process id """
1083
- super()._finalizeStep(status, msg)
1084
- self._pid.set(None)
1085
-
1086
- def _updateSteps(self, updater, where="1"):
1087
- """Set the status of all steps
1088
- :parameter updater callback/lambda receiving a step and editing it inside
1089
- :parameter where condition to filter the set with."""
1090
- stepsSet = StepSet(filename=self.getStepsFile())
1091
- for step in stepsSet.iterItems(where=where):
1092
- updater(step)
1093
- stepsSet.update(step)
1094
- stepsSet.write()
1095
- stepsSet.close() # Close the connection
1096
-
1097
- def getPath(self, *paths):
1098
- """ Same as _getPath but without underscore. """
1099
- return self._getPath(*paths)
1100
-
1101
- def _getPath(self, *paths):
1102
- """ Return a path inside the workingDir. """
1103
- return os.path.join(self.workingDir.get(), *paths)
1104
-
1105
- def _getExtraPath(self, *paths):
1106
- """ Return a path inside the extra folder. """
1107
- return self._getPath("extra", *paths)
1108
-
1109
- def _getTmpPath(self, *paths):
1110
- """ Return a path inside the tmp folder. """
1111
- return self._getPath("tmp", *paths)
1112
-
1113
- def _getLogsPath(self, *paths):
1114
- return self._getPath("logs", *paths)
1115
-
1116
- def _getRelPath(self, *path):
1117
- """ Return a relative path from the workingDir. """
1118
- return os.path.relpath(self._getPath(*path), self.workingDir.get())
1119
-
1120
- def _getRelPathExecutionDir(self, *path):
1121
- """ Return a relative path from the projdir. """
1122
- # TODO must be a bettis
1123
- return os.path.relpath(self._getPath(*path), os.path.dirname(os.path.dirname(self.workingDir.get())))
1124
-
1125
- def _getBasePath(self, path):
1126
- """ Take the basename of the path and get the path
1127
- relative to working dir of the protocol.
1128
- """
1129
- return self._getPath(os.path.basename(path))
1130
-
1131
- def _insertFunctionStep(self, func, *funcArgs, prerequisites=None, wait=False, interactive=False, needsGPU=True):
1132
- """
1133
- Params:
1134
- func: the function itself or, optionally, the name (string) of the function to be run in the Step.
1135
- *funcArgs: the variable list of arguments to pass to the function.
1136
- **kwargs: see __insertStep
1137
- """
1138
- if isinstance(func, str):
1139
- # Get the function give its name
1140
- func = getattr(self, func, None)
1141
-
1142
- # Ensure the protocol instance have it and is callable
1143
- if not func:
1144
- raise Exception("Protocol._insertFunctionStep: '%s' function is "
1145
- "not member of the protocol" % func)
1146
- if not callable(func):
1147
- raise Exception("Protocol._insertFunctionStep: '%s' is not callable"
1148
- % func)
1149
- step = FunctionStep(func, func.__name__, *funcArgs, wait=wait, interactive=interactive, needsGPU=needsGPU)
1150
-
1151
- return self.__insertStep(step,prerequisites)
1152
-
1153
- def _insertRunJobStep(self, progName, progArguments, resultFiles=[],
1154
- **kwargs):
1155
- """ Insert a Step that will simply call runJob function
1156
- **args: see __insertStep
1157
- """
1158
- return self._insertFunctionStep('runJob', progName, progArguments, **kwargs)
1159
-
1160
- def _insertCopyFileStep(self, sourceFile, targetFile, **kwargs):
1161
- """ Shortcut function to insert a step for copying a file to a destiny. """
1162
- step = FunctionStep(pwutils.copyFile, 'copyFile', sourceFile, targetFile, **kwargs)
1163
- return self.__insertStep(step, **kwargs)
1164
-
1165
- def _enterDir(self, path):
1166
- """ Enter into a new directory path and store the current path.
1167
- The current path will be used in _leaveDir, but nested _enterDir
1168
- are not allowed since self._currentDir is overwritten.
1169
- """
1170
- self._currentDir = os.getcwd()
1171
- os.chdir(path)
1172
- if self._log:
1173
- self._log.info("Entered into dir: cd '%s'" % path)
1174
-
1175
- def _leaveDir(self):
1176
- """ This method should be called after a call to _enterDir
1177
- to return to the previous location.
1178
- """
1179
- os.chdir(self._currentDir)
1180
- if self._log:
1181
- self._log.info("Returned to dir: cd '%s'" % self._currentDir)
1182
-
1183
- def _enterWorkingDir(self):
1184
- """ Change to the protocol working dir. """
1185
- self._enterDir(self.workingDir.get())
1186
-
1187
- def _leaveWorkingDir(self):
1188
- """ This function make sense to use in conjunction
1189
- with _enterWorkingDir to go back to execution path.
1190
- """
1191
- self._leaveDir()
1192
-
1193
- def continueFromInteractive(self):
1194
- """ TODO: REMOVE this function.
1195
- Check if there is an interactive step and set
1196
- as finished, this is used now mainly in picking,
1197
- but we should remove this since is weird for users.
1198
- """
1199
- if os.path.exists(self.getStepsFile()):
1200
- stepsSet = StepSet(filename=self.getStepsFile())
1201
- for step in stepsSet:
1202
- if step.getStatus() == STATUS_INTERACTIVE:
1203
- step.setStatus(STATUS_FINISHED)
1204
- stepsSet.update(step)
1205
- break
1206
- stepsSet.write()
1207
- stepsSet.close() # Close the connection
1208
-
1209
- def loadSteps(self):
1210
- """ Load the Steps stored in the steps.sqlite file.
1211
- """
1212
- prevSteps = []
1213
-
1214
- if os.path.exists(self.getStepsFile()):
1215
- stepsSet = StepSet(filename=self.getStepsFile())
1216
- for step in stepsSet:
1217
- prevSteps.append(step.clone())
1218
- stepsSet.close() # Close the connection
1219
- return prevSteps
1220
-
1221
- def _insertPreviousSteps(self):
1222
- """ Insert steps of previous execution.
1223
- It can be used to track previous steps done for
1224
- protocol that allow some kind of continue (such as ctf estimation).
1225
- """
1226
- for step in self.loadSteps():
1227
- self.__insertStep(step, )
1228
-
1229
- def __findStartingStep(self):
1230
- """ From a previous run, compare self._steps and self._prevSteps
1231
- to find which steps we need to start at, skipping successful done
1232
- and not changed steps. Steps that needs to be done, will be deleted
1233
- from the previous run storage.
1234
- """
1235
- if self.runMode == MODE_RESTART:
1236
- self._prevSteps = []
1237
- return 0
1238
-
1239
- self._prevSteps = self.loadSteps()
1240
-
1241
- n = min(len(self._steps), len(self._prevSteps))
1242
- self.debug("len(steps) %s len(prevSteps) %s "
1243
- % (len(self._steps), len(self._prevSteps)))
1244
-
1245
- for i in range(n):
1246
- newStep = self._steps[i]
1247
- oldStep = self._prevSteps[i]
1248
- if (not oldStep.isFinished() or newStep != oldStep
1249
- or not oldStep._postconditions()):
1250
- if pw.Config.debugOn():
1251
- self.info("Starting at step %d" % i)
1252
- self.info(" Old step: %s, args: %s"
1253
- % (oldStep.funcName, oldStep.argsStr))
1254
- self.info(" New step: %s, args: %s"
1255
- % (newStep.funcName, newStep.argsStr))
1256
- self.info(" not oldStep.isFinished(): %s"
1257
- % (not oldStep.isFinished()))
1258
- self.info(" newStep != oldStep: %s"
1259
- % (newStep != oldStep))
1260
- self.info(" not oldStep._postconditions(): %s"
1261
- % (not oldStep._postconditions()))
1262
- return i
1263
- newStep.copy(oldStep)
1264
-
1265
- return n
1266
-
1267
- def _storeSteps(self):
1268
- """ Store the new steps list that can be retrieved
1269
- in further execution of this protocol.
1270
- """
1271
- stepsFn = self.getStepsFile()
1272
-
1273
- self._stepsSet = StepSet(filename=stepsFn)
1274
- self._stepsSet.setStore(False)
1275
- self._stepsSet.clear()
1276
-
1277
- for step in self._steps:
1278
- step.cleanObjId()
1279
- self.setInteractive(self.isInteractive() or step.isInteractive())
1280
- self._stepsSet.append(step)
1281
-
1282
- self._stepsSet.write()
1283
-
1284
- def __updateStep(self, step):
1285
- """ Store a given step and write changes. """
1286
- self._stepsSet.update(step)
1287
- self._stepsSet.write()
1288
-
1289
- def _stepStarted(self, step):
1290
- """This function will be called whenever an step
1291
- has started running.
1292
- """
1293
- self.info(pwutils.magentaStr("STARTED") + ": %s, step %d, time %s" %
1294
- (step.funcName.get(), step._index, step.initTime.datetime()),
1295
- extra=getExtraLogInfo("PROTOCOL", STATUS.START,
1296
- project_name=self.getProject().getName(),
1297
- prot_id=self.getObjId(),
1298
- prot_name=self.getClassName(),
1299
- step_id=step._index))
1300
- self.__updateStep(step)
1301
-
1302
- def _stepFinished(self, step):
1303
- """This function will be called whenever an step
1304
- has finished its run.
1305
- """
1306
- doContinue = True
1307
- if step.isInteractive():
1308
- doContinue = False
1309
- elif step.isFailed():
1310
- doContinue = False
1311
- errorMsg = pwutils.redStr(
1312
- "Protocol failed: " + step.getErrorMessage())
1313
- self.setFailed(errorMsg)
1314
- self.error(errorMsg)
1315
- self.lastStatus = step.getStatus()
1316
-
1317
- self.__updateStep(step)
1318
- self._stepsDone.increment()
1319
- self._cpuTime.set(self._cpuTime.get() + step.getElapsedTime().total_seconds())
1320
- self._store(self._stepsDone, self._cpuTime)
1321
-
1322
- self.info(pwutils.magentaStr(step.getStatus().upper()) + ": %s, step %d, time %s"
1323
- % (step.funcName.get(), step._index, step.endTime.datetime()),
1324
- extra=getExtraLogInfo("PROTOCOL",STATUS.STOP,
1325
- project_name=self.getProject().getName(),
1326
- prot_id=self.getObjId(),
1327
- prot_name=self.getClassName(),
1328
- step_id=step._index))
1329
- if step.isFailed() and self.modeParallel():
1330
- # In parallel mode the executor will exit to close
1331
- # all working threads, so we need to close
1332
- self._endRun()
1333
- return doContinue
1334
-
1335
- def _stepsCheck(self):
1336
- pass
1337
-
1338
- def _runSteps(self, startIndex):
1339
- """ Run all steps defined in self._steps. """
1340
- self._stepsDone.set(startIndex)
1341
- self._numberOfSteps.set(len(self._steps))
1342
- self.setRunning()
1343
- # Keep the original value to set in sub-protocols
1344
- self._originalRunMode = self.runMode.get()
1345
- # Always set to resume, even if set to restart
1346
- self.runMode.set(MODE_RESUME)
1347
- self._store()
1348
-
1349
- if startIndex == len(self._steps):
1350
- self.lastStatus = STATUS_FINISHED
1351
- self.info("All steps seem to be FINISHED, nothing to be done.")
1352
- else:
1353
- self.lastStatus = self.status.get()
1354
- self._stepsExecutor.runSteps(self._steps,
1355
- self._stepStarted,
1356
- self._stepFinished,
1357
- self._stepsCheck,
1358
- self._stepsCheckSecs)
1359
-
1360
- print("*** Last status is %s " % self.lastStatus)
1361
- self.setStatus(self.lastStatus)
1362
- self._store(self.status)
1363
-
1364
- def __deleteOutputs(self):
1365
- """ This function should only be used from RESTART.
1366
- It will remove output attributes from mapper and object.
1367
- """
1368
- attributes = [a[0] for a in self.iterOutputAttributes()]
1369
-
1370
- for attrName in attributes:
1371
- attr = getattr(self, attrName)
1372
- self.mapper.delete(attr)
1373
- delattr(self, attrName)
1374
-
1375
- self._outputs.clear()
1376
- self.mapper.store(self._outputs)
1377
-
1378
- def findAttributeName(self, attr2Find):
1379
- for attrName, attr in self.iterOutputAttributes():
1380
- if attr.getObjId() == attr2Find.getObjId():
1381
- return attrName
1382
- return None
1383
-
1384
- def deleteOutput(self, output):
1385
- attrName = self.findAttributeName(output)
1386
- self.mapper.delete(output)
1387
- delattr(self,attrName)
1388
- if attrName in self._outputs:
1389
- self._outputs.remove(attrName)
1390
- self.mapper.store(self._outputs)
1391
- self.mapper.commit()
1392
-
1393
- def __copyRelations(self, other):
1394
- """ This will copy relations from protocol other to self """
1395
- pass
1396
-
1397
- def copy(self, other, copyId=True, excludeInputs=False):
1398
- """
1399
- Copies its attributes into the passed protocol
1400
-
1401
- :param other: protocol instance to copt the attributes to
1402
- :param copyId: True (default) copies the identifier
1403
- :param excludeInputs: False (default). If true input attributes are excluded
1404
-
1405
- """
1406
-
1407
- # Input attributes list
1408
- inputAttributes = []
1409
-
1410
- # If need to exclude input attributes
1411
- if excludeInputs:
1412
- # Get all the input attributes, to be ignored at copy():
1413
- for key, attr in self.iterInputAttributes():
1414
- inputAttributes.append(key)
1415
-
1416
- copyDict = Object.copy(self, other, copyId, inputAttributes)
1417
- self._store()
1418
- self.mapper.deleteRelations(self)
1419
-
1420
- for r in other.getRelations():
1421
- rName = r['name']
1422
- rCreator = r['parent_id']
1423
- rParent = r[OBJECT_PARENT_ID]
1424
- rChild = r['object_child_id']
1425
- rParentExt = r['object_parent_extended']
1426
- rChildExt = r['object_child_extended']
1427
-
1428
- if rParent in copyDict:
1429
- rParent = copyDict.get(rParent).getObjId()
1430
-
1431
- if rChild in copyDict:
1432
- rChild = copyDict.get(rChild).getObjId()
1433
-
1434
- self.mapper.insertRelationData(rName, rCreator, rParent, rChild,
1435
- rParentExt, rChildExt)
1436
-
1437
- def getRelations(self):
1438
- """ Return the relations created by this protocol. """
1439
- return self.mapper.getRelationsByCreator(self)
1440
-
1441
- def _defineRelation(self, relName, parentObj, childObj):
1442
- """ Insert a new relation in the mapper using self as creator. """
1443
- parentExt = None
1444
- childExt = None
1445
-
1446
- if parentObj.isPointer():
1447
- parentExt = parentObj.getExtended()
1448
- parentObj = parentObj.getObjValue()
1449
-
1450
- if childObj.isPointer():
1451
- childExt = childObj.getExtended()
1452
- childObj = childObj.getObjValue()
1453
-
1454
- self.mapper.insertRelation(relName, self, parentObj, childObj,
1455
- parentExt, childExt)
1456
-
1457
- def makePathsAndClean(self):
1458
- """ Create the necessary path or clean
1459
- if in RESTART mode.
1460
- """
1461
- # Clean working path if in RESTART mode
1462
- if self.runMode == MODE_RESTART:
1463
- self.cleanWorkingDir()
1464
- self.__deleteOutputs()
1465
- # Delete the relations created by this protocol
1466
- # (delete this in both project and protocol db)
1467
- self.mapper.deleteRelations(self)
1468
- self.makeWorkingDir()
1469
-
1470
- def cleanWorkingDir(self):
1471
- """
1472
- Delete all files and subdirectories related with the protocol
1473
- """
1474
- self.cleanTmp()
1475
- pwutils.cleanPath(self._getPath())
1476
-
1477
- def makeWorkingDir(self):
1478
- # Create workingDir, logs and extra paths
1479
- paths = [self._getPath(), self._getExtraPath(), self._getLogsPath()]
1480
- pwutils.makePath(*paths)
1481
- # Create scratch if SCIPION_SCRATCH environment variable exist.
1482
- # In other case, tmp folder is created
1483
- pwutils.makeTmpPath(self)
1484
-
1485
- def cleanTmp(self):
1486
- """ Delete all files and subdirectories under Tmp folder. """
1487
- tmpFolder = self._getTmpPath()
1488
-
1489
- if os.path.islink(tmpFolder):
1490
- pwutils.cleanPath(os.path.realpath(tmpFolder))
1491
- os.remove(tmpFolder)
1492
- else:
1493
- pwutils.cleanPath(tmpFolder)
1494
-
1495
- self._cleanExtraFiles()
1496
- def _cleanExtraFiles(self):
1497
- """ This method will be called when the protocol finishes correctly.
1498
- It is the responsibility of the protocols to implement this method to make extra cleanup
1499
- of its folders, like iterations folder and files that are not needed when finished
1500
- """
1501
-
1502
- logger.info("Nothing to clean up")
1503
- logger.debug('FOR DEVELOPERS: implement Protocol._cleanExtraFiles this protocol could'
1504
- ' free up some space upon finishing.')
1505
-
1506
- def _run(self):
1507
- # Check that a proper Steps executor have been set
1508
- if self._stepsExecutor is None:
1509
- raise Exception('Protocol.run: Steps executor should be set before '
1510
- 'running protocol')
1511
- # Check the parameters are correct
1512
- errors = self.validate()
1513
- if len(errors):
1514
- raise ValidationException(
1515
- 'Protocol has validation errors:\n' + '\n'.join(errors))
1516
-
1517
- self._insertAllSteps() # Define steps for execute later
1518
- # Find at which step we need to start
1519
- startIndex = self.__findStartingStep()
1520
- self.info(" Starting at step: %d" % (startIndex + 1))
1521
- self._storeSteps()
1522
- self.info(" Running steps ")
1523
- self._runSteps(startIndex)
1524
-
1525
- def _getEnviron(self):
1526
- """ This function should return an environ variable
1527
- that will be used when running new programs.
1528
- By default, the protocol will use the one defined
1529
- in the package that it belongs or None.
1530
- """
1531
- return self.getClassPackage().Plugin.getEnviron()
1532
-
1533
- def runJob(self, program, arguments, **kwargs):
1534
- if self.stepsExecutionMode == STEPS_SERIAL:
1535
- kwargs['numberOfMpi'] = kwargs.get('numberOfMpi',
1536
- self.numberOfMpi.get())
1537
- kwargs['numberOfThreads'] = kwargs.get('numberOfThreads',
1538
- self.numberOfThreads.get())
1539
- else:
1540
- kwargs['numberOfMpi'] = kwargs.get('numberOfMpi', 1)
1541
- kwargs['numberOfThreads'] = kwargs.get('numberOfThreads', 1)
1542
- if 'env' not in kwargs:
1543
- kwargs['env'] = self._getEnviron()
1544
-
1545
- self._stepsExecutor.runJob(self._log, program, arguments, **kwargs)
1546
-
1547
- def run(self):
1548
- """ Before calling this method, the working dir for the protocol
1549
- to run should exist.
1550
- """
1551
- try:
1552
- action = "RUNNING" if self.runMode == MODE_RESTART else "RESUMING"
1553
- self.info(pwutils.greenStr('%s PROTOCOL -----------------' % action))
1554
- self.info("Protocol starts", extra=getExtraLogInfo("PROTOCOL", STATUS.START,
1555
- project_name=self.getProject().getName(),
1556
- prot_id=self.getObjId(),
1557
- prot_name=self.getClassName()))
1558
-
1559
- self.setHostFullName(pwutils.getHostFullName())
1560
- self.info('Hostname: %s' % self.getHostFullName())
1561
-
1562
- # Store the full machine name where the protocol is running
1563
- # and also its PID
1564
- if not self.useQueueForProtocol(): # Take as reference the pID
1565
- self.setPid(os.getpid())
1566
- self.info('PID: %s' % self.getPid())
1567
- else: # Take as reference the jobID
1568
- self.info('Executing through the queue system')
1569
- self.info('JOBID: %s' % self.getJobIds())
1570
-
1571
- self.info('pyworkflow: %s' % pw.__version__)
1572
- plugin = self.getPlugin()
1573
- self.info('plugin: %s - %s' % (plugin.getName(), plugin.getUrl()))
1574
- package = self.getClassPackage()
1575
- if hasattr(package, "__version__"):
1576
- self.info('plugin v: %s%s' %(package.__version__, ' (devel)' if plugin.inDevelMode() else '(production)'))
1577
- self.info('plugin binary v: %s' % plugin.getActiveVersion())
1578
- self.info('currentDir: %s' % os.getcwd())
1579
- self.info('workingDir: %s' % self.workingDir)
1580
- self.info('runMode: %s' % MODE_CHOICES[self.runMode.get()])
1581
- try:
1582
- self.info(' MPI: %d' % self.numberOfMpi)
1583
- self.info(' threads: %d' % self.numberOfThreads)
1584
- except Exception as e:
1585
- self.info(' * Cannot get information about MPI/threads (%s)' % e)
1586
- # Something went wrong ans at this point status is launched. We mark it as failed.
1587
- except Exception as e:
1588
- print(e)
1589
- self.setFailed(str(e))
1590
- self._store(self.status, self.getError())
1591
- self._endRun()
1592
- return
1593
-
1594
- Step.run(self)
1595
- if self.isFailed():
1596
- self._store()
1597
- self._endRun()
1598
-
1599
- def _endRun(self):
1600
- """ Print some ending message and close some files. """
1601
- # self._store()
1602
- self._store(self.summaryVar)
1603
- self._store(self.methodsVar)
1604
- self._store(self.endTime)
1605
-
1606
- if pwutils.envVarOn(pw.SCIPION_DEBUG_NOCLEAN):
1607
- self.warning('Not cleaning temp folder since '
1608
- '%s is set to True.' % pw.SCIPION_DEBUG_NOCLEAN)
1609
- elif not self.isFailed():
1610
- self.info('Cleaning temp folder....')
1611
- self.cleanTmp()
1612
-
1613
- self.info(pwutils.greenStr('------------------- PROTOCOL ' +
1614
- self.getStatusMessage().upper()),
1615
- extra=getExtraLogInfo("PROTOCOL",STATUS.STOP,
1616
- project_name=self.getProject().getName(),
1617
- prot_id=self.getObjId(),
1618
- prot_name=self.getClassName()))
1619
-
1620
- def getLogPaths(self):
1621
- return [self.getStdoutLog(),self.getStderrLog() , self.getScheduleLog()]
1622
-
1623
- def getStdoutLog(self):
1624
- return self._getLogsPath("run.stdout")
1625
-
1626
- def getStderrLog(self):
1627
- return self._getLogsPath('run.stderr')
1628
-
1629
- def getScheduleLog(self):
1630
- return self._getLogsPath('schedule.log')
1631
-
1632
- def getSteps(self):
1633
- """ Return the steps.sqlite file under logs directory. """
1634
- return self._steps
1635
-
1636
- def getStepsFile(self):
1637
- """ Return the steps.sqlite file under logs directory. """
1638
- return self._getLogsPath('steps.sqlite')
1639
-
1640
- def _addChunk(self, txt, fmt=None):
1641
- """
1642
- Add text txt to self._buffer, with format fmt.
1643
- fmt can be a color (like 'red') or a link that looks like 'link:url'.
1644
- """
1645
- # Make the text html-safe first.
1646
- for x, y in [('&', 'amp'), ('<', 'lt'), ('>', 'gt')]:
1647
- txt = txt.replace(x, '&%s;' % y)
1648
-
1649
- if fmt is None:
1650
- self._buffer += txt
1651
- elif fmt.startswith('link:'):
1652
- url = fmt[len('link:'):]
1653
- # Add the url in the TWiki style
1654
- if url.startswith('http://'):
1655
- self._buffer += '[[%s][%s]]' % (url, txt)
1656
- # Web does not exist, webtools must find a solution for this case.
1657
- # else:
1658
- # from pyworkflow.web.pages import settings as django_settings
1659
- # absolute_url = django_settings.ABSOLUTE_URL
1660
- # self._buffer += '[[%s/get_log/?path=%s][%s]]' % (absolute_url,
1661
- # url, txt)
1662
- else:
1663
- self._buffer += '<font color="%s">%s</font>' % (fmt, txt)
1664
-
1665
- def getLogsAsStrings(self):
1666
-
1667
- outputs = []
1668
- for fname in self.getLogPaths():
1669
- if pwutils.exists(fname):
1670
- self._buffer = ''
1671
- pwutils.renderTextFile(fname, self._addChunk)
1672
- outputs.append(self._buffer)
1673
- else:
1674
- outputs.append('File "%s" does not exist' % fname)
1675
- return outputs
1676
-
1677
- def getLogsLastLines(self, lastLines=None, logFile=0):
1678
- """
1679
- Get the last(lastLines) lines of a log file.
1680
-
1681
- :param lastLines, if None, will try 'PROT_LOGS_LAST_LINES' env variable, otherwise 20
1682
- :param logFile: Log file to take the lines from, default = 0 (std.out). 1 for stdErr.
1683
- """
1684
- if not lastLines:
1685
- lastLines = int(os.environ.get('PROT_LOGS_LAST_LINES', 20))
1686
-
1687
- # Get stdout
1688
- stdoutFn =self.getLogPaths()[logFile]
1689
-
1690
- if not os.path.exists(stdoutFn):
1691
- return []
1692
-
1693
- with open(stdoutFn, 'r') as stdout:
1694
-
1695
- iterlen = lambda it: sum(1 for _ in it)
1696
- numLines = iterlen(stdout)
1697
-
1698
- lastLines = min(lastLines, numLines)
1699
- sk = numLines - lastLines
1700
- sk = max(sk, 0)
1701
-
1702
- stdout.seek(0, 0)
1703
- output = [l.strip('\n') for k, l in enumerate(stdout)
1704
- if k >= sk]
1705
- return output
1706
-
1707
- def warning(self, message, redirectStandard=True):
1708
- self._log.warning(message)
1709
-
1710
- def info(self, message, extra=None):
1711
- self._log.info(message, extra= extra)
1712
-
1713
- def error(self, message, redirectStandard=True):
1714
- self._log.error(message)
1715
-
1716
- def debug(self, message):
1717
- self._log.debug(message)
1718
-
1719
- def getWorkingDir(self):
1720
- return self.workingDir.get()
1721
-
1722
- def setWorkingDir(self, path):
1723
- self.workingDir.set(path)
1724
-
1725
- def setMapper(self, mapper):
1726
- """ Set a new mapper for the protocol to persist state. """
1727
- self.mapper = mapper
1728
-
1729
- def getMapper(self):
1730
- return self.mapper
1731
-
1732
- def getDbPath(self):
1733
- return self._getLogsPath('run.db')
1734
-
1735
- def setStepsExecutor(self, executor=None):
1736
- if executor is None:
1737
- executor = StepExecutor(self.getHostConfig())
1738
-
1739
- self._stepsExecutor = executor
1740
- self._stepsExecutor.setProtocol(self) # executor needs the protocol to store the jobs Ids submitted to a queue
1741
-
1742
- def getFiles(self):
1743
- resultFiles = set()
1744
- for paramName, _ in self.getDefinition().iterPointerParams():
1745
- # Get all self attribute that are pointers
1746
- attrPointer = getattr(self, paramName)
1747
- obj = attrPointer.get() # Get object pointer by the attribute
1748
- if hasattr(obj, 'getFiles'):
1749
- resultFiles.update(obj.getFiles()) # Add files if any
1750
- return resultFiles | pwutils.getFiles(self.workingDir.get())
1751
-
1752
- def getHostName(self):
1753
- """ Get the execution host name.
1754
- This value is only the key of the host in the configuration file.
1755
- """
1756
- return self.hostName.get()
1757
-
1758
- def setHostName(self, hostName):
1759
- """ Set the execution host name (the host key in the config file) """
1760
- self.hostName.set(hostName)
1761
-
1762
- def getHostFullName(self):
1763
- """ Return the full machine name where the protocol is running. """
1764
- return self.hostFullName.get()
1765
-
1766
- def setHostFullName(self, hostFullName):
1767
- self.hostFullName.set(hostFullName)
1768
-
1769
- def getHostConfig(self):
1770
- """ Return the configuration host. """
1771
- return self.hostConfig
1772
-
1773
- def setHostConfig(self, config):
1774
- self.hostConfig = config
1775
- # Never store the host config as part of the protocol, it is kept
1776
- # in the configuration information, the hostname is enough
1777
- self.hostConfig.setStore(False)
1778
-
1779
- def getJobIds(self):
1780
- """ Return an iterable list of jobs Ids associated to a running protocol. """
1781
- return self._jobId
1782
-
1783
- def setJobId(self, jobId):
1784
- " Reset this list to have the first active job "
1785
- self._jobId.clear()
1786
- self.appendJobId(jobId)
1787
-
1788
- def setJobIds(self, jobIds):
1789
- " Reset this list to have a list of active jobs "
1790
- self._jobId = jobIds
1791
-
1792
- def appendJobId(self, jobId):
1793
- " Append active jobs to the list "
1794
- self._jobId.append(jobId)
1795
- def removeJobId(self, jobId):
1796
- " Remove inactive jobs from the list "
1797
- self._jobId.remove(jobId)
1798
-
1799
- def getPid(self):
1800
- return self._pid.get()
1801
-
1802
- def setPid(self, pid):
1803
- self._pid.set(pid)
1804
-
1805
- def getRunName(self):
1806
- runName = self.getObjLabel().strip()
1807
- if not len(runName):
1808
- runName = self.getDefaultRunName()
1809
- return runName
1810
-
1811
- def getDefaultRunName(self):
1812
- return '%s.%s' % (self.getClassName(), self.strId())
1813
-
1814
- @classmethod
1815
- def getClassPackage(cls):
1816
- """ Return the package module to which this protocol belongs.
1817
- This function will only work, if for the given Domain, the
1818
- method Domain.getProtocols() has been called once. After calling
1819
- this method the protocol classes are registered with it Plugin
1820
- and Domain info.
1821
- """
1822
- return cls._package
1823
-
1824
- @classmethod
1825
- def getClassPlugin(cls):
1826
-
1827
- logger.warning("Deprecated on 04-2023. Use Protocol.getPlugin instead.")
1828
- return cls.getPlugin()
1829
-
1830
- @classmethod
1831
- def getPlugin(cls):
1832
- return cls._plugin
1833
- @classmethod
1834
- def getClassPackageName(cls):
1835
- return cls.getClassPackage().__name__ if cls.getClassPackage() else "orphan"
1836
-
1837
- @classmethod
1838
- def getClassDomain(cls):
1839
- """ Return the Domain class where this Protocol class is defined. """
1840
- return pw.Config.getDomain()
1841
-
1842
- @classmethod
1843
- def getPluginLogoPath(cls):
1844
- package = cls.getClassPackage()
1845
- logo = getattr(package, '_logo', None)
1846
- if logo:
1847
- logoPath = (pw.findResource(logo) or
1848
- os.path.join(os.path.abspath(os.path.dirname(package.__file__)), logo))
1849
- else:
1850
- logoPath = None
1851
-
1852
- return logoPath
1853
-
1854
- @classmethod
1855
- def validatePackageVersion(cls, varName, errors):
1856
- """
1857
- Function to validate the package version specified in
1858
- configuration file ~/.config/scipion/scipion.conf is among the available
1859
- options and it is properly installed.
1860
-
1861
- :param package: the package object (ej: eman2 or relion). Package should contain the
1862
- following methods: getVersion(), getSupportedVersions()
1863
- :param varName: the expected environment var containing the path (and version)
1864
- :param errors: list of strings to add errors if found
1865
-
1866
- """
1867
- package = cls.getClassPackage()
1868
- packageName = cls.getClassPackageName()
1869
- varValue = package.Plugin.getVar(varName)
1870
- versions = ','.join(package.Plugin.getSupportedVersions())
1871
-
1872
- errorMsg = None
1873
-
1874
- if not package.Plugin.getActiveVersion():
1875
- errors.append("We could not detect *%s* version. " % packageName)
1876
- errorMsg = "The path value should contains a valid version (%s)." % versions
1877
- elif not os.path.exists(varValue):
1878
- errors.append("Path of %s does not exists." % varName)
1879
- errorMsg = "Check installed packages and versions with command:\n "
1880
- errorMsg += "*scipion install --help*"
1881
-
1882
- if errorMsg:
1883
- errors.append("%s = %s" % (varName, varValue))
1884
- errors.append(
1885
- "Please, modify %s value in the configuration file:" % varName)
1886
- errors.append("*~/.config/scipion/scipion.conf*")
1887
- errors.append(errorMsg)
1888
- errors.append("After fixed, you NEED TO RESTART THE PROJECT WINDOW")
1889
-
1890
- @classmethod
1891
- def getClassLabel(cls, prependPackageName=True):
1892
- """ Return a more readable string representing the protocol class """
1893
- label = cls.__dict__.get('_label', cls.__name__)
1894
- if prependPackageName:
1895
- try:
1896
- label = "%s - %s" % (cls.getPlugin().getName(), label)
1897
- except Exception as e:
1898
- label = "%s -%s" % ("missing", label)
1899
- logger.error("Couldn't get the plugin name for %s" % label, exc_info=e)
1900
- return label
1901
-
1902
- @classmethod
1903
- def isDisabled(cls):
1904
- """ Return True if this Protocol is disabled.
1905
- Disabled protocols will not be offered in the available protocols."""
1906
- return False
1907
-
1908
- @classmethod
1909
- def isBase(cls):
1910
- """ Return True if this Protocol is a base class.
1911
- Base classes should be marked with _label = None.
1912
- """
1913
- return cls.__dict__.get('_label', None) is None
1914
-
1915
- def getSubmitDict(self):
1916
- """ Return a dictionary with the necessary keys to
1917
- launch the job to a queue system.
1918
- """
1919
- queueName, queueParams = self.getQueueParams()
1920
- hc = self.getHostConfig()
1921
-
1922
- d = {'JOB_NAME': self.strId(),
1923
- 'JOB_QUEUE': queueName,
1924
- 'JOB_NODES': self.numberOfMpi.get(),
1925
- 'JOB_THREADS': self.numberOfThreads.get(),
1926
- 'JOB_CORES': self.numberOfMpi.get() * self.numberOfThreads.get(),
1927
- 'JOB_HOURS': 72,
1928
- 'GPU_COUNT': len(self.getGpuList()),
1929
- QUEUE_FOR_JOBS: 'N',
1930
- 'SCIPION_PROJECT': "SCIPION_PROJECT", # self.getProject().getShortName(),
1931
- 'SCIPION_PROTOCOL': self.getRunName(),
1932
- PLUGIN_MODULE_VAR: self.getPlugin().getName()
1933
- }
1934
-
1935
- # Criteria in HostConfig.load to load or not QUEUE variables
1936
- if hc.getQueueSystem().hasName():
1937
- job_logs = self._getLogsPath(hc.getSubmitPrefix() + self.strId())
1938
- d['JOB_SCRIPT'] = job_logs + '.job'
1939
- d['JOB_LOGS'] = job_logs
1940
- d['JOB_NODEFILE'] = os.path.abspath(job_logs +'.nodefile')
1941
-
1942
- d.update(queueParams)
1943
- return d
1944
-
1945
- def useQueue(self):
1946
- """ Return True if the protocol should be launched through a queue. """
1947
- return self._useQueue.get()
1948
-
1949
- def useQueueForSteps(self):
1950
- """ This function will return True if the protocol has been set
1951
- to be launched through a queue by steps """
1952
- return self.useQueue() and (self.getSubmitDict()[QUEUE_FOR_JOBS] == "Y")
1953
-
1954
- def useQueueForProtocol(self):
1955
- """ This function will return True if the protocol has been set
1956
- to be launched through a queue """
1957
- return self.useQueue() and (self.getSubmitDict()[QUEUE_FOR_JOBS] != "Y")
1958
-
1959
- def getQueueParams(self):
1960
- if self._queueParams.hasValue():
1961
- return json.loads(self._queueParams.get())
1962
- else:
1963
- return '', {}
1964
-
1965
- def hasQueueParams(self):
1966
- return self._queueParams.hasValue()
1967
-
1968
- def setQueueParams(self, queueParams):
1969
- self._queueParams.set(json.dumps(queueParams))
1970
-
1971
- @property
1972
- def numberOfSteps(self):
1973
- return self._numberOfSteps.get(0)
1974
-
1975
- @property
1976
- def stepsDone(self):
1977
- """ Return the number of steps executed. """
1978
- return self._stepsDone.get(0)
1979
-
1980
- @property
1981
- def cpuTime(self):
1982
- """ Return the sum of all durations of the finished steps"""
1983
- return self._cpuTime.get()
1984
-
1985
- def updateSteps(self):
1986
- """ After the steps list is modified, this methods will update steps
1987
- information. It will save the steps list and also the number of steps.
1988
- """
1989
- self._storeSteps()
1990
- self._numberOfSteps.set(len(self._steps))
1991
- self._store(self._numberOfSteps)
1992
- self._newSteps = False
1993
-
1994
- def getStatusMessage(self):
1995
- """ Return the status string and if running the steps done.
1996
- """
1997
- msg = self.getStatus()
1998
- if self.isRunning() or self.isAborted() or self.isFailed():
1999
- msg += " (done %d/%d)" % (self.stepsDone, self.numberOfSteps)
2000
-
2001
- return msg
2002
-
2003
- def getRunMode(self):
2004
- """ Return the mode of execution, either:
2005
- MODE_RESTART or MODE_RESUME. """
2006
- return self.runMode.get()
2007
-
2008
- def hasSummaryWarnings(self):
2009
- return len(self.summaryWarnings) != 0
2010
-
2011
- def addSummaryWarning(self, warningDescription):
2012
- """Appends the warningDescription param to the list of summaryWarnings.
2013
- Will be printed in the protocol summary."""
2014
- self.summaryWarnings.append(warningDescription)
2015
- return self.summaryWarnings
2016
-
2017
- def checkSummaryWarnings(self):
2018
- """ Checks for warnings that we want to tell the user about by adding a
2019
- warning sign to the run box and a description to the run summary.
2020
- List of warnings checked:
2021
- 1. If the folder for this protocol run exists.
2022
- """
2023
- if not self.isSaved() and not os.path.exists(self.workingDir.get()):
2024
- self.addSummaryWarning("*Missing run data*: The directory for this "
2025
- "run is missing, so it won't be possible to "
2026
- "use its outputs in other protocols.")
2027
-
2028
- def isContinued(self):
2029
- """ Return if running in continue mode (MODE_RESUME). """
2030
- return self.getRunMode() == MODE_RESUME
2031
-
2032
- # Methods that should be implemented in subclasses
2033
- def _validate(self):
2034
- """ This function can be overwritten by subclasses.
2035
- Used from the public validate function.
2036
- """
2037
- return []
2038
-
2039
- @classmethod
2040
- def getUrl(cls):
2041
- return cls.getPlugin().getUrl(cls)
2042
-
2043
- @classmethod
2044
- def isInstalled(cls):
2045
- # We a consider a protocol installed if there are not errors
2046
- # from the _validateInstallation function
2047
- return not cls.validateInstallation()
2048
-
2049
- @classmethod
2050
- def validateInstallation(cls):
2051
- """ Check if the installation of this protocol is correct.
2052
- By default, we will check if the protocols' package provide a
2053
- validateInstallation function and use it.
2054
- Returning an empty list means that the installation is correct
2055
- and there are not errors. If some errors are found, a list with
2056
- the error messages will be returned.
2057
- """
2058
- try:
2059
- validateFunc = getattr(cls.getClassPackage().Plugin,
2060
- 'validateInstallation', None)
2061
-
2062
- return validateFunc() if validateFunc is not None else []
2063
- except Exception as e:
2064
- msg = str(e)
2065
- msg += (" %s installation couldn't be validated. Possible cause "
2066
- "could be a configuration issue. Try to run scipion "
2067
- "config." % cls.__name__)
2068
- print(msg)
2069
- return [msg]
2070
-
2071
- def validate(self):
2072
- """ Check that input parameters are correct.
2073
- Return a list with errors, if the list is empty, all was ok.
2074
- """
2075
- errors = []
2076
- # Validate that all input pointer parameters have a value
2077
- for paramName, param in self.getDefinition().iterParams():
2078
- # Get all self attribute that are pointers
2079
- attr = getattr(self, paramName)
2080
- paramErrors = []
2081
- condition = self.evalParamCondition(paramName)
2082
- if attr.isPointer():
2083
- obj = attr.get()
2084
- if condition and obj is None and not param.allowsNull:
2085
- paramErrors.append('cannot be EMPTY.')
2086
- elif isinstance(attr, PointerList):
2087
- # In this case allowsNull refers to not allowing empty items
2088
- if not param.allowsNull:
2089
- if len(attr) == 0:
2090
- paramErrors.append('cannot be EMPTY.')
2091
- # Consider empty pointers
2092
- else:
2093
- if any(pointer.get() is None for pointer in attr):
2094
- paramErrors.append('Can not have EMPTY items.')
2095
-
2096
- else:
2097
- if condition:
2098
- paramErrors = param.validate(attr.get())
2099
- label = param.label.get()
2100
- errors += ['*%s* %s' % (label, err) for err in paramErrors]
2101
-
2102
- try:
2103
- # Check that all ids specified in the 'Wait for' form entry
2104
- # are valid protocol ids
2105
- proj = self.getProject()
2106
- for protId in self.getPrerequisites():
2107
- try:
2108
- prot = proj.getProtocol(int(protId))
2109
- except Exception:
2110
- prot = None
2111
- if prot is None:
2112
- errors.append('*%s* is not a valid protocol id.' % protId)
2113
-
2114
- # Validate specific for the subclass
2115
- installErrors = self.validateInstallation()
2116
- if installErrors:
2117
- errors += installErrors
2118
- childErrors = self._validate()
2119
- if childErrors:
2120
- errors += childErrors
2121
- except Exception:
2122
- import urllib
2123
- exceptionStr = pwutils.formatExceptionInfo()
2124
- errors.append("Protocol validation failed. It usually happens because there are some "
2125
- "input missing. Please check if the error message gives you any "
2126
- "hint:\n{}".format(exceptionStr))
2127
- return errors
2128
-
2129
- def _warnings(self):
2130
- """ Should be implemented in subclasses. See warning. """
2131
- return []
2132
-
2133
- def warnings(self):
2134
- """ Return some message warnings that can be errors.
2135
- User should approve to execute a protocol with warnings. """
2136
- return self._warnings()
2137
-
2138
- def _summary(self):
2139
- """ Should be implemented in subclasses. See summary. """
2140
- return ["No summary information."]
2141
-
2142
- def summary(self):
2143
- """ Return a summary message to provide some information to users. """
2144
- try:
2145
- baseSummary = self._summary() or ['No summary information.']
2146
-
2147
- if isinstance(baseSummary, str):
2148
- baseSummary = [baseSummary]
2149
-
2150
- if not isinstance(baseSummary, list):
2151
- raise Exception("Developers error: _summary() is not returning "
2152
- "a list")
2153
-
2154
- comments = self.getObjComment()
2155
- if comments:
2156
- baseSummary += ['', '*COMMENTS:* ', comments]
2157
-
2158
- if self.getError().hasValue():
2159
- baseSummary += ['', '*ERROR:*', self.getError().get()]
2160
-
2161
- if self.summaryWarnings:
2162
- baseSummary += ['', '*WARNINGS:*']
2163
- baseSummary += self.summaryWarnings
2164
-
2165
- except Exception as ex:
2166
- baseSummary = [str(ex)]
2167
-
2168
- return baseSummary
2169
-
2170
- def getFileTag(self, fn):
2171
- return "[[%s]]" % fn
2172
-
2173
- def getObjectTag(self, objName):
2174
- if isinstance(objName, str):
2175
- obj = getattr(self, objName, None)
2176
- else:
2177
- obj = objName
2178
-
2179
- if obj is None:
2180
- return '*None*'
2181
-
2182
- if obj.isPointer():
2183
- obj = obj.get() # get the pointed object
2184
- if obj is None:
2185
- return '*None*'
2186
-
2187
- return "[[sci-open:%s][%s]]" % (obj.getObjId(), obj.getNameId())
2188
-
2189
- def _citations(self):
2190
- """ Should be implemented in subclasses. See citations. """
2191
- return getattr(self, "_references", [])
2192
-
2193
- def __getPluginBibTex(self):
2194
- """ Return the _bibtex from the package """
2195
- return getattr(self.getClassPackage(), "_bibtex", {})
2196
-
2197
- def _getCite(self, citeStr):
2198
- bibtex = self.__getPluginBibTex()
2199
- if citeStr in bibtex:
2200
- text = self._getCiteText(bibtex[citeStr])
2201
- else:
2202
- text = "Reference with key *%s* not found." % citeStr
2203
- return text
2204
-
2205
- def _getCiteText(self, cite, useKeyLabel=False):
2206
- try:
2207
-
2208
- journal = cite.get("journal", cite.get("booktitle", ""))
2209
- doi = cite.get("doi", "").strip()
2210
- url = cite.get("url", "").strip()
2211
- # Get the first author surname
2212
- if useKeyLabel:
2213
- label = cite['ID']
2214
- else:
2215
- label = cite['author'].split(' and ')[0].split(',')[0].strip()
2216
- label += ' et al., %s, %s' % (journal, cite['year'])
2217
- if len(doi) > 0:
2218
- text = '[[%s][%s]] ' % (doi, label)
2219
- elif len(url) > 0:
2220
- text = '[[%s][%s]] ' % (url, label)
2221
- else:
2222
- text = label.strip()
2223
- return text
2224
-
2225
- except Exception as ex:
2226
- print("Error with citation: " + label)
2227
- print(ex)
2228
- text = "Error with citation *%s*." % label
2229
- return text
2230
-
2231
- def __getCitations(self, citations):
2232
- """ From the list of citations keys, obtains the full
2233
- info from the package _bibtex dict.
2234
- """
2235
- bibtex = self.__getPluginBibTex()
2236
- newCitations = []
2237
- for c in citations:
2238
- if c in bibtex:
2239
- newCitations.append(self._getCiteText(bibtex[c]))
2240
- else:
2241
- newCitations.append(c)
2242
- return newCitations
2243
-
2244
- def __getCitationsDict(self, citationList, bibTexOutput=False):
2245
- """ Return a dictionary with Cite keys and the citation links. """
2246
- bibtex = self.__getPluginBibTex()
2247
- od = OrderedDict()
2248
- for c in citationList:
2249
- if c in bibtex:
2250
- if bibTexOutput:
2251
- od[c] = bibtex[c]
2252
- else:
2253
- od[c] = self._getCiteText(bibtex[c])
2254
- else:
2255
- od[c] = c
2256
-
2257
- return od
2258
-
2259
- def getCitations(self, bibTexOutput=False):
2260
- return self.__getCitationsDict(self._citations() or [],
2261
- bibTexOutput=bibTexOutput)
2262
-
2263
- def getPackageCitations(self, bibTexOutput=False):
2264
- refs = getattr(self.getClassPackage(), "_references", [])
2265
- return self.__getCitationsDict(refs, bibTexOutput=bibTexOutput)
2266
-
2267
- def citations(self):
2268
- """ Return a citation message to provide some information to users. """
2269
- citations = list(self.getCitations().values())
2270
- if citations:
2271
- citations.insert(0, '*Protocol references:* ')
2272
-
2273
- packageCitations = self.getPackageCitations().values()
2274
- if packageCitations:
2275
- citations.append('*Package references:*')
2276
- citations += packageCitations
2277
- if not citations:
2278
- return ['No references provided']
2279
- return citations
2280
-
2281
- @classmethod
2282
- def getHelpText(cls):
2283
- """Get help text to show in the protocol help button"""
2284
- helpText = cls.getDoc()
2285
- # NOt used since getPlugin is always None
2286
- # plugin = self.getPlugin()
2287
- # if plugin:
2288
- # pluginMetadata = plugin.metadata
2289
- # helpText += "\n\nPlugin info:\n"
2290
- # for key, value in pluginMetadata.iteritems():
2291
- # helpText += "%s: \t%s\n" % (key, value)
2292
- return helpText
2293
-
2294
- def _methods(self):
2295
- """ Should be implemented in subclasses. See methods. """
2296
- return ["No methods information."]
2297
-
2298
- def getParsedMethods(self):
2299
- """ Get the _methods results and parse possible cites. """
2300
- try:
2301
- baseMethods = self._methods() or []
2302
- bibtex = self.__getPluginBibTex()
2303
- parsedMethods = []
2304
- for m in baseMethods:
2305
- for bibId, cite in bibtex.items():
2306
- k = '[%s]' % bibId
2307
- link = self._getCiteText(cite, useKeyLabel=True)
2308
- m = m.replace(k, link)
2309
- parsedMethods.append(m)
2310
- except Exception as ex:
2311
- parsedMethods = ['ERROR generating methods info: %s' % ex]
2312
-
2313
- return parsedMethods
2314
-
2315
- def methods(self):
2316
- """ Return a description about methods about current protocol
2317
- execution. """
2318
- # TODO: Maybe store the methods and not computing all times??
2319
- return self.getParsedMethods() + [''] + self.citations()
2320
-
2321
- def runProtocol(self, protocol):
2322
- """ Setup another protocol to be run from a workflow. """
2323
- name = protocol.getClassName() + protocol.strId()
2324
- # protocol.setName(name)
2325
- protocol.setWorkingDir(self._getPath(name))
2326
- protocol.setMapper(self.mapper)
2327
- self.hostConfig.setStore(False)
2328
- protocol.setHostConfig(self.getHostConfig())
2329
- protocol.runMode.set(self._originalRunMode)
2330
- protocol.makePathsAndClean()
2331
- protocol.setStepsExecutor(self._stepsExecutor)
2332
- protocol.run()
2333
- self._store() # TODO: check if this is needed
2334
-
2335
- def isChild(self):
2336
- """ Return true if this protocol was invoked from a workflow
2337
- (another protocol)"""
2338
- return self.hasObjParentId()
2339
-
2340
- def getStepsGraph(self, refresh=True):
2341
- """ Build a graph taking into account the dependencies between
2342
- steps. In streaming we might find first the createOutputStep (e.g 24)
2343
- depending on 25"""
2344
- from pyworkflow.utils.graph import Graph
2345
- g = Graph(rootName='PROTOCOL')
2346
- root = g.getRoot()
2347
- root.label = 'Protocol'
2348
-
2349
- steps = self.loadSteps()
2350
- stepsDict = {str(i + 1): steps[i] for i in range(0, len(steps))}
2351
- stepsDone = {}
2352
-
2353
- def addStep(i, step):
2354
-
2355
- # Exit if already done
2356
- # This happens when, in streaming there is a child "before" a parent
2357
- if i in stepsDone:
2358
- return
2359
-
2360
- index = step.getIndex() or i
2361
- sid = str(index)
2362
- n = g.createNode(sid)
2363
- n.step = step
2364
- stepsDone[i] = n
2365
- if step.getPrerequisites().isEmpty():
2366
- root.addChild(n)
2367
- else:
2368
- for p in step.getPrerequisites():
2369
- # If prerequisite exists
2370
- if p not in stepsDone:
2371
- addStep(p, stepsDict[p])
2372
- stepsDone[p].addChild(n)
2373
-
2374
- for i, s in stepsDict.items():
2375
- addStep(i, s)
2376
- return g
2377
-
2378
- def closeMappers(self):
2379
- """ Close the mappers of all output Sets. """
2380
- for _, attr in self.iterOutputAttributes(Set):
2381
- attr.close()
2382
-
2383
- def loadMappers(self):
2384
- """ Open mapper connections from previous closed outputs. """
2385
- for _, attr in self.iterOutputAttributes(Set):
2386
- attr.load()
2387
-
2388
- def allowsDelete(self, obj):
2389
- return False
2390
-
2391
- def legacyCheck(self):
2392
- """ Hook defined to run some compatibility checks
2393
- before display the protocol.
2394
- """
2395
- pass
2396
-
2397
- def getSize(self):
2398
- """ Returns the size of the folder corresponding to this protocol"""
2399
- if not self._size:
2400
- self._size = getFileSize(self.getPath())
2401
-
2402
- return self._size
2403
-
2404
- def cleanExecutionAttributes(self):
2405
- """ Clean all the executions attributes """
2406
- self.setPid(0)
2407
- self._jobId.clear()
2408
- self._stepsDone.set(0)
2409
-
2410
- class LegacyProtocol(Protocol):
2411
- """ Special subclass of Protocol to be used when a protocol class
2412
- is not found. It means that have been removed or it is in another
2413
- development branch. In such, we will use the LegacyProtocol to
2414
- simply store the parameters and inputs/outputs."""
2415
-
2416
- def __str__(self):
2417
- return self.getObjLabel()
2418
-
2419
- # overload getClassDomain because legacy protocols
2420
- # do not have a package associated to it
2421
- @classmethod
2422
- def getClassDomain(cls):
2423
- return pw.Config.getDomain()
2424
-
2425
-
2426
- # ---------- Helper functions related to Protocols --------------------
2427
-
2428
- def runProtocolMain(projectPath, protDbPath, protId):
2429
- """
2430
- Main entry point when a protocol will be executed.
2431
- This function should be called when::
2432
-
2433
- scipion runprotocol ...
2434
-
2435
- :param projectPath: the absolute path to the project directory.
2436
- :param protDbPath: path to protocol db relative to projectPath
2437
- :param protId: id of the protocol object in db.
2438
-
2439
- """
2440
-
2441
- # Enter to the project directory and load protocol from db
2442
- protocol = getProtocolFromDb(projectPath, protDbPath, protId, chdir=True)
2443
-
2444
- setDefaultLoggingContext(protId, protocol.getProject().getShortName())
2445
-
2446
- hostConfig = protocol.getHostConfig()
2447
- gpuList = protocol.getGpuList()
2448
-
2449
- #If queue is to be used
2450
- if protocol.useQueue():
2451
- gpuList = anonimizeGPUs(gpuList)
2452
-
2453
- # Create the steps executor
2454
- executor = None
2455
- nThreads = max(protocol.numberOfThreads.get(), 1)
2456
-
2457
- if protocol.modeParallel() and nThreads > 1:
2458
- if protocol.useQueueForSteps():
2459
- executor = QueueStepExecutor(hostConfig,
2460
- protocol.getSubmitDict(),
2461
- nThreads - 1,
2462
- gpuList=gpuList)
2463
- else:
2464
- executor = ThreadStepExecutor(hostConfig, nThreads - 1,
2465
- gpuList=gpuList)
2466
-
2467
- if executor is None and protocol.useQueueForSteps():
2468
- executor = QueueStepExecutor(hostConfig, protocol.getSubmitDict(), 1,
2469
- gpuList=gpuList)
2470
-
2471
- if executor is None:
2472
- executor = StepExecutor(hostConfig,
2473
- gpuList=gpuList)
2474
-
2475
- logger.info("Running protocol using the %s executor." % executor)
2476
- protocol.setStepsExecutor(executor)
2477
- # Finally run the protocol
2478
- protocol.run()
2479
-
2480
-
2481
- def anonimizeGPUs(gpuList):
2482
-
2483
- renamedGPUs=dict()
2484
- anonimousGPUs = []
2485
-
2486
- for gpu in gpuList:
2487
-
2488
- if gpu not in renamedGPUs:
2489
- renamedGPUs[gpu] = len(renamedGPUs)
2490
-
2491
- anonimousGPUs.append(renamedGPUs[gpu])
2492
-
2493
- return anonimousGPUs
2494
-
2495
-
2496
-
2497
- def getProtocolFromDb(projectPath, protDbPath, protId, chdir=False):
2498
- """ Retrieve the Protocol object from a given .sqlite file
2499
- and the protocol id.
2500
- """
2501
-
2502
- if not os.path.exists(projectPath):
2503
- raise Exception("ERROR: project path '%s' does not exist. "
2504
- % projectPath)
2505
-
2506
- fullDbPath = os.path.join(projectPath, protDbPath)
2507
-
2508
- if not os.path.exists(fullDbPath):
2509
- raise Exception("ERROR: protocol database '%s' does not exist. "
2510
- % fullDbPath)
2511
-
2512
- # We need this import here because from Project is imported
2513
- # all from protocol indirectly, so if move this to the top
2514
- # we get an import error
2515
- from pyworkflow.project import Project
2516
- project = Project(pw.Config.getDomain(), projectPath)
2517
- project.load(dbPath=os.path.join(projectPath, protDbPath), chdir=chdir,
2518
- loadAllConfig=False)
2519
- protocol = project.getProtocol(protId)
2520
- return protocol
2521
-
2522
-
2523
- def getUpdatedProtocol(protocol):
2524
- """ Retrieve the updated protocol and close db connections
2525
- """
2526
- prot2 = getProtocolFromDb(protocol.getProject().path,
2527
- protocol.getDbPath(),
2528
- protocol.getObjId())
2529
- # Close DB connections
2530
- prot2.getProject().closeMapper()
2531
- prot2.closeMappers()
2532
- return prot2
2533
-
2534
-
2535
- def isProtocolUpToDate(protocol):
2536
- """ Check timestamps between protocol lastModificationDate and the
2537
- corresponding runs.db timestamp"""
2538
- if protocol is None:
2539
- return True
2540
-
2541
- if protocol.lastUpdateTimeStamp.get(None) is None:
2542
- return False
2543
-
2544
- protTS = protocol.lastUpdateTimeStamp.datetime()
2545
-
2546
- if protTS is None:
2547
- return False
2548
-
2549
- dbTS = pwutils.getFileLastModificationDate(protocol.getDbPath())
2550
-
2551
- if not (protTS and dbTS):
2552
- logger.info("Can't compare if protocol is up to date: "
2553
- "Protocol %s, protocol time stamp: %s, %s timeStamp: %s"
2554
- % (protocol, protTS, protocol, dbTS))
2555
- else:
2556
- return protTS >= dbTS
2557
-
2558
-
2559
- class ProtImportBase(Protocol):
2560
- """ Base Import protocol"""
2561
-
2562
-
2563
- class ProtStreamingBase(Protocol):
2564
- """ Base protocol to implement streaming protocols.
2565
- stepsGeneratorStep should be implemented (see its description) and output
2566
- should be created at the end of the processing Steps created by the stepsGeneratorStep.
2567
- To avoid concurrency error, when creating the output, do it in a with self._lock: block.
2568
- Minimum number of threads is 3 and should run in parallel mode.
2569
- """
2570
-
2571
- stepsExecutionMode = STEPS_PARALLEL
2572
-
2573
- def _defineStreamingParams(self, form):
2574
- """ This function can be called during the _defineParams method
2575
- of some protocols that support stream processing.
2576
- It will add a Streaming section together with the following
2577
- params:
2578
- streamingSleepOnWait: Some streaming protocols are quite fast,
2579
- so, checking input/output updates creates an IO overhead.
2580
- This params allows them to sleep (without consuming resources)
2581
- to wait for new work to be done.
2582
- """
2583
- form.addSection("Streaming")
2584
- form.addParam("streamingSleepOnWait", IntParam, default=10,
2585
- label="Sleep when waiting (secs)",
2586
- help="If you specify a value greater than zero, "
2587
- "it will be the number of seconds that the "
2588
- "protocol will sleep when waiting for new "
2589
- "input data in streaming mode. ")
2590
-
2591
- def _insertAllSteps(self):
2592
- """ Insert the step that generates the steps """
2593
- self._insertFunctionStep(self.resumableStepGeneratorStep, str(datetime.now()), needsGPU=False)
2594
-
2595
- def resumableStepGeneratorStep(self, ts):
2596
- """ This allow to resume protocols. ts is the time stamp so this stap is always different form previous execution"""
2597
- self.stepsGeneratorStep()
2598
-
2599
- def _stepsCheck(self):
2600
- """ Just store steps created in checkNewInputStep"""
2601
- if self._newSteps:
2602
- self.updateSteps()
2603
-
2604
- def stepsGeneratorStep(self):
2605
- """
2606
- This step should be implemented by any streaming protocol.
2607
- It should check its input and when ready conditions are met
2608
- call the self._insertFunctionStep method.
2609
-
2610
- :return: None
2611
- """
2612
- pass
2613
-
2614
- def _getStreamingSleepOnWait(self):
2615
- """ Retrieves the configured sleep duration for waiting during streaming.
2616
- Returns:
2617
- - int: The sleep duration in seconds during streaming wait.
2618
- """
2619
- return self.getAttributeValue('streamingSleepOnWait', 0)
2620
-
2621
- def _streamingSleepOnWait(self):
2622
- """ This method should be used by protocols that want to sleep
2623
- when there is not more work to do.
2624
- """
2625
- sleepOnWait = self._getStreamingSleepOnWait()
2626
- if sleepOnWait > 0:
2627
- self.info("Waiting %s now before checking again for new input" % sleepOnWait)
2628
- time.sleep(sleepOnWait)
2629
-
2630
- def _validateThreads(self, messages: list):
2631
-
2632
- if self.numberOfThreads.get() < 2:
2633
- messages.append("At least 2 threads are needed for running this protocol. "
2634
- "1 for the 'stepsGenerator step' and one more for the actual processing" )
2635
-
2636
- def _validate(self):
2637
- """ If you want to implement a validate method do it but call _validateThreads or validate threads value."""
2638
- errors = []
2639
- self._validateThreads(errors)
2640
-
2641
- return errors