scipion-pyworkflow 3.7.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 (140) hide show
  1. pyworkflow/__init__.py +33 -0
  2. pyworkflow/apps/__init__.py +29 -0
  3. pyworkflow/apps/pw_manager.py +37 -0
  4. pyworkflow/apps/pw_plot.py +51 -0
  5. pyworkflow/apps/pw_project.py +113 -0
  6. pyworkflow/apps/pw_protocol_list.py +143 -0
  7. pyworkflow/apps/pw_protocol_run.py +51 -0
  8. pyworkflow/apps/pw_run_tests.py +267 -0
  9. pyworkflow/apps/pw_schedule_run.py +322 -0
  10. pyworkflow/apps/pw_sleep.py +37 -0
  11. pyworkflow/apps/pw_sync_data.py +439 -0
  12. pyworkflow/apps/pw_viewer.py +78 -0
  13. pyworkflow/config.py +536 -0
  14. pyworkflow/constants.py +212 -0
  15. pyworkflow/exceptions.py +18 -0
  16. pyworkflow/gui/__init__.py +36 -0
  17. pyworkflow/gui/browser.py +726 -0
  18. pyworkflow/gui/canvas.py +1190 -0
  19. pyworkflow/gui/dialog.py +976 -0
  20. pyworkflow/gui/form.py +2627 -0
  21. pyworkflow/gui/graph.py +247 -0
  22. pyworkflow/gui/graph_layout.py +271 -0
  23. pyworkflow/gui/gui.py +566 -0
  24. pyworkflow/gui/matplotlib_image.py +233 -0
  25. pyworkflow/gui/plotter.py +247 -0
  26. pyworkflow/gui/project/__init__.py +25 -0
  27. pyworkflow/gui/project/base.py +192 -0
  28. pyworkflow/gui/project/constants.py +139 -0
  29. pyworkflow/gui/project/labels.py +205 -0
  30. pyworkflow/gui/project/project.py +484 -0
  31. pyworkflow/gui/project/searchprotocol.py +154 -0
  32. pyworkflow/gui/project/searchrun.py +181 -0
  33. pyworkflow/gui/project/steps.py +166 -0
  34. pyworkflow/gui/project/utils.py +332 -0
  35. pyworkflow/gui/project/variables.py +179 -0
  36. pyworkflow/gui/project/viewdata.py +472 -0
  37. pyworkflow/gui/project/viewprojects.py +510 -0
  38. pyworkflow/gui/project/viewprotocols.py +2093 -0
  39. pyworkflow/gui/project/viewprotocols_extra.py +560 -0
  40. pyworkflow/gui/text.py +771 -0
  41. pyworkflow/gui/tooltip.py +185 -0
  42. pyworkflow/gui/tree.py +684 -0
  43. pyworkflow/gui/widgets.py +307 -0
  44. pyworkflow/mapper/__init__.py +26 -0
  45. pyworkflow/mapper/mapper.py +222 -0
  46. pyworkflow/mapper/sqlite.py +1578 -0
  47. pyworkflow/mapper/sqlite_db.py +145 -0
  48. pyworkflow/object.py +1512 -0
  49. pyworkflow/plugin.py +712 -0
  50. pyworkflow/project/__init__.py +31 -0
  51. pyworkflow/project/config.py +451 -0
  52. pyworkflow/project/manager.py +179 -0
  53. pyworkflow/project/project.py +1990 -0
  54. pyworkflow/project/scripts/clean_projects.py +77 -0
  55. pyworkflow/project/scripts/config.py +92 -0
  56. pyworkflow/project/scripts/create.py +77 -0
  57. pyworkflow/project/scripts/edit_workflow.py +90 -0
  58. pyworkflow/project/scripts/fix_links.py +39 -0
  59. pyworkflow/project/scripts/load.py +87 -0
  60. pyworkflow/project/scripts/refresh.py +83 -0
  61. pyworkflow/project/scripts/schedule.py +111 -0
  62. pyworkflow/project/scripts/stack2volume.py +41 -0
  63. pyworkflow/project/scripts/stop.py +81 -0
  64. pyworkflow/protocol/__init__.py +38 -0
  65. pyworkflow/protocol/bibtex.py +48 -0
  66. pyworkflow/protocol/constants.py +86 -0
  67. pyworkflow/protocol/executor.py +334 -0
  68. pyworkflow/protocol/hosts.py +313 -0
  69. pyworkflow/protocol/launch.py +270 -0
  70. pyworkflow/protocol/package.py +42 -0
  71. pyworkflow/protocol/params.py +744 -0
  72. pyworkflow/protocol/protocol.py +2554 -0
  73. pyworkflow/resources/Imagej.png +0 -0
  74. pyworkflow/resources/chimera.png +0 -0
  75. pyworkflow/resources/fa-exclamation-triangle_alert.png +0 -0
  76. pyworkflow/resources/fa-info-circle_alert.png +0 -0
  77. pyworkflow/resources/fa-search.png +0 -0
  78. pyworkflow/resources/fa-times-circle_alert.png +0 -0
  79. pyworkflow/resources/file_vol.png +0 -0
  80. pyworkflow/resources/loading.gif +0 -0
  81. pyworkflow/resources/no-image128.png +0 -0
  82. pyworkflow/resources/scipion_bn.png +0 -0
  83. pyworkflow/resources/scipion_icon.png +0 -0
  84. pyworkflow/resources/scipion_icon.svg +397 -0
  85. pyworkflow/resources/scipion_icon_proj.png +0 -0
  86. pyworkflow/resources/scipion_icon_projs.png +0 -0
  87. pyworkflow/resources/scipion_icon_prot.png +0 -0
  88. pyworkflow/resources/scipion_logo.png +0 -0
  89. pyworkflow/resources/scipion_logo_normal.png +0 -0
  90. pyworkflow/resources/scipion_logo_small.png +0 -0
  91. pyworkflow/resources/sprites.png +0 -0
  92. pyworkflow/resources/sprites.xcf +0 -0
  93. pyworkflow/resources/wait.gif +0 -0
  94. pyworkflow/template.py +322 -0
  95. pyworkflow/tests/__init__.py +29 -0
  96. pyworkflow/tests/test_utils.py +25 -0
  97. pyworkflow/tests/tests.py +341 -0
  98. pyworkflow/utils/__init__.py +38 -0
  99. pyworkflow/utils/dataset.py +414 -0
  100. pyworkflow/utils/echo.py +104 -0
  101. pyworkflow/utils/graph.py +196 -0
  102. pyworkflow/utils/log.py +284 -0
  103. pyworkflow/utils/path.py +527 -0
  104. pyworkflow/utils/process.py +132 -0
  105. pyworkflow/utils/profiler.py +92 -0
  106. pyworkflow/utils/progressbar.py +154 -0
  107. pyworkflow/utils/properties.py +627 -0
  108. pyworkflow/utils/reflection.py +129 -0
  109. pyworkflow/utils/utils.py +877 -0
  110. pyworkflow/utils/which.py +229 -0
  111. pyworkflow/viewer.py +328 -0
  112. pyworkflow/webservices/__init__.py +8 -0
  113. pyworkflow/webservices/config.py +11 -0
  114. pyworkflow/webservices/notifier.py +162 -0
  115. pyworkflow/webservices/repository.py +59 -0
  116. pyworkflow/webservices/workflowhub.py +74 -0
  117. pyworkflow/wizard.py +64 -0
  118. pyworkflowtests/__init__.py +51 -0
  119. pyworkflowtests/bibtex.py +51 -0
  120. pyworkflowtests/objects.py +830 -0
  121. pyworkflowtests/protocols.py +154 -0
  122. pyworkflowtests/tests/__init__.py +0 -0
  123. pyworkflowtests/tests/test_canvas.py +72 -0
  124. pyworkflowtests/tests/test_domain.py +45 -0
  125. pyworkflowtests/tests/test_logs.py +74 -0
  126. pyworkflowtests/tests/test_mappers.py +392 -0
  127. pyworkflowtests/tests/test_object.py +507 -0
  128. pyworkflowtests/tests/test_project.py +42 -0
  129. pyworkflowtests/tests/test_protocol_execution.py +72 -0
  130. pyworkflowtests/tests/test_protocol_export.py +78 -0
  131. pyworkflowtests/tests/test_protocol_output.py +158 -0
  132. pyworkflowtests/tests/test_streaming.py +47 -0
  133. pyworkflowtests/tests/test_utils.py +210 -0
  134. scipion_pyworkflow-3.7.0.dist-info/LICENSE.txt +674 -0
  135. scipion_pyworkflow-3.7.0.dist-info/METADATA +107 -0
  136. scipion_pyworkflow-3.7.0.dist-info/RECORD +140 -0
  137. scipion_pyworkflow-3.7.0.dist-info/WHEEL +5 -0
  138. scipion_pyworkflow-3.7.0.dist-info/dependency_links.txt +1 -0
  139. scipion_pyworkflow-3.7.0.dist-info/entry_points.txt +5 -0
  140. scipion_pyworkflow-3.7.0.dist-info/top_level.txt +2 -0
@@ -0,0 +1,81 @@
1
+ #!/usr/bin/env python
2
+ # **************************************************************************
3
+ # *
4
+ # * Authors: Yaiza Rancel (yrancel@cnb.csic.es)
5
+ # *
6
+ # * Unidad de Bioinformatica of Centro Nacional de Biotecnologia, CSIC
7
+ # *
8
+ # * This program is free software; you can redistribute it and/or modify
9
+ # * it under the terms of the GNU General Public License as published by
10
+ # * the Free Software Foundation; either version 3 of the License, or
11
+ # * (at your option) any later version.
12
+ # *
13
+ # * This program is distributed in the hope that it will be useful,
14
+ # * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ # * GNU General Public License for more details.
17
+ # *
18
+ # * You should have received a copy of the GNU General Public License
19
+ # * along with this program; if not, write to the Free Software
20
+ # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21
+ # * 02111-1307 USA
22
+ # *
23
+ # * All comments concerning this program package may be sent to the
24
+ # * e-mail address 'scipion@cnb.csic.es'
25
+ # *
26
+ # **************************************************************************
27
+
28
+
29
+ import sys
30
+ import os
31
+
32
+ import pyworkflow as pw
33
+ import pyworkflow.utils as pwutils
34
+ from pyworkflow.project import Manager, Project
35
+
36
+
37
+ def usage(error):
38
+ print("""
39
+ ERROR: %s
40
+
41
+ Usage: scipion python -m pyworkflow.project.scripts.stop project_name
42
+ This script will stop all running protocols of the specified project.
43
+ """ % error)
44
+ sys.exit(1)
45
+
46
+
47
+ n = len(sys.argv)
48
+
49
+ if n > 2:
50
+ usage("This script accepts 1 mandatory parameter: the project name")
51
+
52
+ projName = sys.argv[1]
53
+
54
+ path = pw.join('gui', 'no-tkinter')
55
+ sys.path.insert(1, path)
56
+
57
+ manager = Manager()
58
+
59
+ if not manager.hasProject(projName):
60
+ usage("There is no project with this name: %s"
61
+ % pwutils.red(projName))
62
+
63
+ # the project may be a soft link which may be unavailable to the cluster so get the real path
64
+ try:
65
+ projectPath = os.readlink(manager.getProjectPath(projName))
66
+ except:
67
+ projectPath = manager.getProjectPath(projName)
68
+
69
+ project = Project(pw.Config.getDomain(), projectPath)
70
+ project.load()
71
+
72
+ runs = project.getRuns()
73
+
74
+ # Now assuming that there is no dependencies between runs
75
+ # and the graph is linear
76
+ for prot in runs:
77
+ if prot.isActive():
78
+ try:
79
+ project.stopProtocol(prot)
80
+ except:
81
+ print("Couldn't stop protocol %s" % prot)
@@ -0,0 +1,38 @@
1
+ # **************************************************************************
2
+ # *
3
+ # * Authors: J.M. De la Rosa Trevin (jmdelarosa@cnb.csic.es)
4
+ # *
5
+ # * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC
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, write to the Free Software
19
+ # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20
+ # * 02111-1307 USA
21
+ # *
22
+ # * All comments concerning this program package may be sent to the
23
+ # * e-mail address 'scipion@cnb.csic.es'
24
+ # *
25
+ # **************************************************************************
26
+ """
27
+ This modules contains classes required for the workflow
28
+ execution and tracking like: Step and Protocol
29
+ """
30
+
31
+ from .protocol import *
32
+ from .executor import *
33
+ from .constants import *
34
+ from .params import *
35
+
36
+ from .launch import *
37
+
38
+ from .hosts import HostConfig
@@ -0,0 +1,48 @@
1
+ # -*- coding: utf-8 -*-
2
+ # **************************************************************************
3
+ # *
4
+ # * Authors: Yaiza Rancel (cyrancel@cnb.csic.es)
5
+ # *
6
+ # * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC
7
+ # *
8
+ # * This program is free software; you can redistribute it and/or modify
9
+ # * it under the terms of the GNU General Public License as published by
10
+ # * the Free Software Foundation; either version 3 of the License, or
11
+ # * (at your option) any later version.
12
+ # *
13
+ # * This program is distributed in the hope that it will be useful,
14
+ # * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ # * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
+ # * GNU General Public License for more details.
17
+ # *
18
+ # * You should have received a copy of the GNU General Public License
19
+ # * along with this program; if not, write to the Free Software
20
+ # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21
+ # * 02111-1307 USA
22
+ # *
23
+ # * All comments concerning this program package may be sent to the
24
+ # * e-mail address 'scipion@cnb.csic.es'
25
+ # *
26
+ # **************************************************************************
27
+ """
28
+ @article{delaRosaTrevin201693,
29
+ title = "Scipion: A software framework toward integration, reproducibility and validation in 3D electron microscopy ",
30
+ journal = "Journal of Structural Biology",
31
+ volume = "195",
32
+ number = "1",
33
+ pages = "93 - 99",
34
+ year = "2016",
35
+ note = "",
36
+ issn = "1047-8477",
37
+ doi = "http://doi.org/10.1016/j.jsb.2016.04.010",
38
+ url = "http://www.sciencedirect.com/science/article/pii/S104784771630079X",
39
+ author = "J.M. de la Rosa-Trevín and A. Quintana and L. del Cano and A. Zaldívar and I. Foche and J. Gutiérrez and J. Gómez-Blanco and J. Burguet-Castell and J. Cuenca-Alba and V. Abrishami and J. Vargas and J. Otón and G. Sharov and J.L. Vilas and J. Navas and P. Conesa and M. Kazemi and R. Marabini and C.O.S. Sorzano and J.M. Carazo",
40
+ keywords = "Electron microscopy",
41
+ keywords = "Single particle analysis",
42
+ keywords = "Image processing",
43
+ keywords = "Software package",
44
+ keywords = "Workflows",
45
+ keywords = "Reproducibility "
46
+ }
47
+ """
48
+
@@ -0,0 +1,86 @@
1
+ # **************************************************************************
2
+ # *
3
+ # * Authors: J.M. De la Rosa Trevin (jmdelarosa@cnb.csic.es)
4
+ # *
5
+ # * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC
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, write to the Free Software
19
+ # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20
+ # * 02111-1307 USA
21
+ # *
22
+ # * All comments concerning this program package may be sent to the
23
+ # * e-mail address 'scipion@cnb.csic.es'
24
+ # *
25
+ # **************************************************************************
26
+ """
27
+ This modules contains classes required for the workflow
28
+ execution and tracking like: Step and Protocol
29
+ """
30
+
31
+ # ------------------ Constants values -----------------------------------------
32
+
33
+ # Possible status of a protocol run, used mainly to monitor progress
34
+
35
+ STATUS_SAVED = "saved" # Parameters saved for later use
36
+ STATUS_LAUNCHED = "launched" # launched to queue system, only useful for protocols
37
+ STATUS_NEW = "new"
38
+ STATUS_RUNNING = "running" # currently executing
39
+ STATUS_FAILED = "failed" # it run and failed
40
+ STATUS_FINISHED = "finished" # successfully finished
41
+ STATUS_ABORTED = "aborted"
42
+ STATUS_INTERACTIVE = "interactive" # waiting for user interaction
43
+ STATUS_WAITING = "waiting" # following status is used for streaming only
44
+ # Allow to schedule jobs not ready for running yet
45
+ STATUS_SCHEDULED = "scheduled"
46
+
47
+ ACTIVE_STATUS = [STATUS_LAUNCHED, STATUS_RUNNING, STATUS_INTERACTIVE,
48
+ STATUS_SCHEDULED]
49
+
50
+ # Execution modes
51
+ MODE_RESUME = 0 # Try to starting at the first changed step, skipping unchanged ones
52
+ MODE_RESTART = 1 # Restart the protocol from the beginning, deleting all previous results
53
+ MODE_CONTINUE = 2 # Continue from specific step, not widely used //DEPRECATED.
54
+ # JMRT: We now use 'Continue' label instead of 'Resume' which is more intuitive for users.
55
+ MODE_CHOICES = ('Continue', 'Restart') # , 'Continue')
56
+
57
+ # Initial sleeping time (in seconds) in order to launch a scheduled protocol.
58
+ # This value is multiply to the protocol level into the workflow.
59
+ INITIAL_SLEEP_TIME = 30
60
+
61
+ # Maximum time (in seconds) waiting for a scheduled protocol to check if it
62
+ # can be launched.
63
+ MAX_SLEEP_TIME = 120
64
+
65
+
66
+ # Steps execution mode
67
+ STEPS_SERIAL = 0 # Execute steps serially, some of the steps can be mpi programs
68
+ STEPS_PARALLEL = 1 # Execute steps in parallel through threads
69
+
70
+ # Level of expertise for the input parameters, mainly used in the protocol form
71
+ LEVEL_NORMAL = 0
72
+ LEVEL_ADVANCED = 1
73
+ LEVEL_CHOICES = ('Normal', 'Advanced')
74
+
75
+ # Param names for GPU processing
76
+ USE_GPU = 'useGpu'
77
+ GPU_LIST = 'gpuList'
78
+
79
+ # Job management
80
+ UNKNOWN_JOBID = -1
81
+
82
+ # File sizes
83
+ SIZE_1KB = 1024
84
+ SIZE_1MB = SIZE_1KB * SIZE_1KB
85
+ SIZE_1GB = SIZE_1MB * SIZE_1KB
86
+ SIZE_1TB = SIZE_1GB * SIZE_1KB
@@ -0,0 +1,334 @@
1
+ # **************************************************************************
2
+ # *
3
+ # * Authors: J.M. De la Rosa Trevin (jmdelarosa@cnb.csic.es)
4
+ # *
5
+ # * Unidad de Bioinformatica of Centro Nacional de Biotecnologia, CSIC
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, write to the Free Software
19
+ # * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20
+ # * 02111-1307 USA
21
+ # *
22
+ # * All comments concerning this program package may be sent to the
23
+ # * e-mail address 'scipion@cnb.csic.es'
24
+ # *
25
+ # **************************************************************************
26
+ """
27
+ This module have the classes for execution of protocol steps.
28
+ The basic one will run steps, one by one, after completion.
29
+ There is one based on threads to execute steps in parallel
30
+ using different threads and the last one with MPI processes.
31
+ """
32
+
33
+ import logging
34
+ logger = logging.getLogger(__name__)
35
+ import time
36
+ import datetime
37
+ import threading
38
+ import os
39
+
40
+ import pyworkflow.utils.process as process
41
+ from pyworkflow.utils.path import getParentFolder, removeExt
42
+ from . import constants as cts
43
+
44
+ from .launch import _submit, UNKNOWN_JOBID, _checkJobStatus
45
+
46
+
47
+ class StepExecutor:
48
+ """ Run a list of Protocol steps. """
49
+ def __init__(self, hostConfig, **kwargs):
50
+ self.hostConfig = hostConfig
51
+ self.gpuList = kwargs.get(cts.GPU_LIST, None)
52
+ self.protocol = None
53
+
54
+ def getGpuList(self):
55
+ """ Return the GPU list assigned to current thread. """
56
+ return self.gpuList
57
+
58
+ def setProtocol(self, protocol):
59
+ """ Set protocol to append active jobs to its jobIds. """
60
+ self.protocol = protocol
61
+
62
+ def runJob(self, log, programName, params,
63
+ numberOfMpi=1, numberOfThreads=1,
64
+ env=None, cwd=None, executable=None):
65
+ """ This function is a wrapper around runJob,
66
+ providing the host configuration.
67
+ """
68
+ process.runJob(log, programName, params,
69
+ numberOfMpi, numberOfThreads,
70
+ self.hostConfig,
71
+ env=env, cwd=cwd, gpuList=self.getGpuList(), executable=executable)
72
+
73
+ def _getRunnable(self, steps, n=1):
74
+ """ Return the n steps that are 'new' and all its
75
+ dependencies have been finished, or None if none ready.
76
+ """
77
+ rs = [] # return a list of runnable steps
78
+
79
+ for s in steps:
80
+ if (s.getStatus() == cts.STATUS_NEW and
81
+ all(steps[i-1].isFinished() for i in s._prerequisites)):
82
+ rs.append(s)
83
+ if len(rs) == n:
84
+ break
85
+ return rs
86
+
87
+ def _arePending(self, steps):
88
+ """ Return True if there are pending steps (either running or waiting)
89
+ that can be done and thus enable other steps to be executed.
90
+ """
91
+ return any(s.isRunning() or s.isWaiting() for s in steps)
92
+
93
+ def runSteps(self, steps,
94
+ stepStartedCallback,
95
+ stepFinishedCallback,
96
+ stepsCheckCallback,
97
+ stepsCheckSecs=3):
98
+ # Even if this will run the steps in a single thread
99
+ # let's follow a similar approach than the parallel one
100
+ # In this way we can take into account the steps graph
101
+ # dependency and also the case when using streaming
102
+
103
+ delta = datetime.timedelta(seconds=stepsCheckSecs)
104
+ lastCheck = datetime.datetime.now()
105
+
106
+ while True:
107
+ # Get a step to run, if there is any
108
+ runnableSteps = self._getRunnable(steps)
109
+
110
+ if runnableSteps:
111
+ step = runnableSteps[0]
112
+ # We found a step to work in, so let's start a new
113
+ # thread to do the job and book it.
114
+ step.setRunning()
115
+ stepStartedCallback(step)
116
+ step.run()
117
+ doContinue = stepFinishedCallback(step)
118
+
119
+ if not doContinue:
120
+ break
121
+
122
+ elif self._arePending(steps):
123
+ # We have not found any runnable step, but still there
124
+ # there are some running or waiting for dependencies
125
+ # So, let's wait a bit to check if something changes
126
+ time.sleep(0.5)
127
+ else:
128
+ # No steps to run, neither running or waiting
129
+ # So, we are done, either failed or finished :)
130
+ break
131
+
132
+ now = datetime.datetime.now()
133
+ if now - lastCheck > delta:
134
+ stepsCheckCallback()
135
+ lastCheck = now
136
+
137
+ stepsCheckCallback() # one last check to finalize stuff
138
+
139
+
140
+ class StepThread(threading.Thread):
141
+ """ Thread to run Steps in parallel. """
142
+ def __init__(self, thId, step, lock):
143
+ threading.Thread.__init__(self)
144
+ self.thId = thId
145
+ self.step = step
146
+ self.lock = lock
147
+
148
+ def run(self):
149
+ error = None
150
+ try:
151
+ self.step._run() # not self.step.run() , to avoid race conditions
152
+ except Exception as e:
153
+ error = str(e)
154
+ logger.error("Couldn't run the code in a thread." , exc_info=e)
155
+ finally:
156
+ with self.lock:
157
+ if error is None:
158
+ self.step.setFinished()
159
+ else:
160
+ self.step.setFailed(error)
161
+
162
+
163
+ class ThreadStepExecutor(StepExecutor):
164
+ """ Run steps in parallel using threads. """
165
+ def __init__(self, hostConfig, nThreads, **kwargs):
166
+ StepExecutor.__init__(self, hostConfig, **kwargs)
167
+ self.numberOfProcs = nThreads
168
+ # If the gpuList was specified, we need to distribute GPUs among
169
+ # all the threads
170
+ self.gpuDict = {}
171
+
172
+ if self.gpuList:
173
+ nodes = range(nThreads)
174
+ nGpu = len(self.gpuList)
175
+
176
+ if nGpu > nThreads:
177
+ chunk = int(nGpu / nThreads)
178
+ for i, node in enumerate(nodes):
179
+ self.gpuDict[node] = list(self.gpuList[i*chunk:(i+1)*chunk])
180
+ else:
181
+ # Expand gpuList repeating until reach nThreads items
182
+ if nThreads > nGpu:
183
+ newList = self.gpuList * (int(nThreads/nGpu)+1)
184
+ self.gpuList = newList[:nThreads]
185
+
186
+ for node, gpu in zip(nodes, self.gpuList):
187
+ self.gpuDict[node] = [gpu]
188
+
189
+ def getGpuList(self):
190
+ """ Return the GPU list assigned to current thread
191
+ or empty list if not using GPUs. """
192
+ return self.gpuDict.get(threading.current_thread().thId, [])
193
+
194
+ def runSteps(self, steps,
195
+ stepStartedCallback,
196
+ stepFinishedCallback,
197
+ stepsCheckCallback,
198
+ stepsCheckSecs=5):
199
+ """
200
+ Creates threads and synchronize the steps execution.
201
+
202
+ :param steps: list of steps to run
203
+ :param stepStartedCallback: callback to be called before starting any step
204
+ :param stepFinishedCallback: callback to be run after all steps are done
205
+ :param stepsCheckCallback: callback to check if there are new steps to add (streaming)
206
+ :param stepsCheckSecs: seconds between stepsCheckCallback calls
207
+
208
+ """
209
+
210
+ delta = datetime.timedelta(seconds=stepsCheckSecs)
211
+ lastCheck = datetime.datetime.now()
212
+
213
+ sharedLock = threading.Lock()
214
+
215
+ runningSteps = {} # currently running step in each node ({node: step})
216
+ freeNodes = list(range(self.numberOfProcs)) # available nodes to send jobs
217
+
218
+ while True:
219
+ # See which of the runningSteps are not really running anymore.
220
+ # Update them and freeNodes, and call final callback for step.
221
+ with sharedLock:
222
+ nodesFinished = [node for node, step in runningSteps.items()
223
+ if not step.isRunning()]
224
+ doContinue = True
225
+ for node in nodesFinished:
226
+ step = runningSteps.pop(node) # remove entry from runningSteps
227
+ freeNodes.append(node) # the node is available now
228
+ # Notify steps termination and check if we should continue
229
+ doContinue = stepFinishedCallback(step)
230
+ if not doContinue:
231
+ break
232
+
233
+ if not doContinue:
234
+ break
235
+
236
+ anyLaunched = False
237
+ # If there are available nodes, send next runnable step.
238
+ with sharedLock:
239
+ if freeNodes:
240
+ runnableSteps = self._getRunnable(steps, len(freeNodes))
241
+
242
+ for step in runnableSteps:
243
+ # We found a step to work in, so let's start a new
244
+ # thread to do the job and book it.
245
+ anyLaunched = True
246
+ step.setRunning()
247
+ stepStartedCallback(step)
248
+ node = freeNodes.pop() # take an available node
249
+ runningSteps[node] = step
250
+ t = StepThread(node, step, sharedLock)
251
+ # won't keep process up if main thread ends
252
+ t.daemon = True
253
+ t.start()
254
+ anyPending = self._arePending(steps)
255
+
256
+ if not anyLaunched:
257
+ if anyPending: # nothing running
258
+ time.sleep(0.5)
259
+ else:
260
+ break # yeah, we are done, either failed or finished :)
261
+
262
+ now = datetime.datetime.now()
263
+ if now - lastCheck > delta:
264
+ stepsCheckCallback()
265
+ lastCheck = now
266
+
267
+ stepsCheckCallback()
268
+
269
+ # Wait for all threads now.
270
+ for t in threading.enumerate():
271
+ if t is not threading.current_thread():
272
+ t.join()
273
+
274
+
275
+ class QueueStepExecutor(ThreadStepExecutor):
276
+ def __init__(self, hostConfig, submitDict, nThreads, **kwargs):
277
+ ThreadStepExecutor.__init__(self, hostConfig, nThreads, **kwargs)
278
+ self.submitDict = submitDict
279
+ # Command counter per thread
280
+ self.threadCommands = {}
281
+ for threadId in range(nThreads):
282
+ self.threadCommands[threadId] = 0
283
+
284
+ if nThreads > 1:
285
+ self.runJobs = ThreadStepExecutor.runSteps
286
+ else:
287
+ self.runJobs = StepExecutor.runSteps
288
+
289
+ self.renameGpuIds()
290
+
291
+ def renameGpuIds(self):
292
+ """ Reorganize the gpus ids starting from 0 since the queue engine is the one assigning them.
293
+ https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#env-vars """
294
+ for threadId, gpuList in self.gpuDict.items():
295
+ for i in range(len(gpuList)):
296
+ self.gpuDict[threadId][i] = i
297
+
298
+ logger.debug("Updated gpus ids rebase starting from 0: %s per thread" %self.gpuDict)
299
+
300
+ def runJob(self, log, programName, params, numberOfMpi=1, numberOfThreads=1, env=None, cwd=None, executable=None):
301
+ threadId = threading.current_thread().thId
302
+ submitDict = dict(self.hostConfig.getQueuesDefault())
303
+ submitDict.update(self.submitDict)
304
+ submitDict['JOB_COMMAND'] = process.buildRunCommand(programName, params, numberOfMpi,
305
+ self.hostConfig, env,
306
+ gpuList=self.getGpuList())
307
+ self.threadCommands[threadId] += 1
308
+ subthreadId = '-%s-%s' % (threadId, self.threadCommands[threadId])
309
+ submitDict['JOB_NAME'] = submitDict['JOB_NAME'] + subthreadId
310
+ submitDict['JOB_SCRIPT'] = os.path.abspath(removeExt(submitDict['JOB_SCRIPT']) + subthreadId + ".job")
311
+ submitDict['JOB_LOGS'] = os.path.join(getParentFolder(submitDict['JOB_SCRIPT']), submitDict['JOB_NAME'])
312
+
313
+ jobid = _submit(self.hostConfig, submitDict, cwd, env)
314
+ self.protocol.appendJobId(jobid) # append active jobs
315
+ self.protocol._store(self.protocol._jobId)
316
+
317
+ if (jobid is None) or (jobid == UNKNOWN_JOBID):
318
+ logger.info("jobId is none therefore we set it to fail")
319
+ raise Exception("Failed to submit to queue.")
320
+
321
+ status = cts.STATUS_RUNNING
322
+ wait = 3
323
+
324
+ # Check status while job running
325
+ # REVIEW this to minimize the overhead in time put by this delay check
326
+ while _checkJobStatus(self.hostConfig, jobid) == cts.STATUS_RUNNING:
327
+ time.sleep(wait)
328
+ if wait < 300:
329
+ wait += 3
330
+
331
+ self.protocol.removeJobId(jobid) # After completion, remove inactive jobs.
332
+ self.protocol._store(self.protocol._jobId)
333
+
334
+ return status