-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathgraph.py
More file actions
1553 lines (1343 loc) · 63.7 KB
/
graph.py
File metadata and controls
1553 lines (1343 loc) · 63.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
from collections.abc import Iterable
import logging
import os
import re
import json
from enum import Enum
from threading import Thread, Event, Lock
from multiprocessing.pool import ThreadPool
from typing import Optional, Union
from collections.abc import Iterator
from collections import OrderedDict
from PySide6.QtCore import (
Slot,
QJsonValue,
QObject,
QUrl,
Property,
Signal,
QPoint,
QItemSelectionModel,
QItemSelection,
)
from meshroom.core import sessionUid
from meshroom.common.qt import QObjectListModel
from meshroom.core.attribute import Attribute, ListAttribute, ShapeAttribute
from meshroom.core.graph import Graph, Edge, generateTempProjectFilepath
from meshroom.core.graphIO import GraphIO
from meshroom.core.taskManager import TaskManager
from meshroom.core.submitter import jobManager
from meshroom.core.node import NodeChunk, Node, Status, ExecMode, CompatibilityNode, Position
from meshroom.core import submitters, MrNodeType
from meshroom.ui import commands
from meshroom.ui.utils import makeProperty
class PollerRefreshStatus(Enum):
AUTO_ENABLED = 0 # The file watcher polls every single status file periodically
DISABLED = 1 # The file watcher is disabled and never polls any file
MINIMAL_ENABLED = 2 # The file watcher only polls status files for chunks that are either submitted or running externally
class FilesModTimePollerThread(QObject):
"""
Thread responsible for non-blocking polling of last modification times of a list of files.
Uses a Python ThreadPool internally to split tasks on multiple threads.
"""
timesAvailable = Signal(list)
def __init__(self, parent=None):
super().__init__(parent)
self._thread = None
self._mutex = Lock()
self._threadPool = ThreadPool(4)
self._stopFlag = Event()
self._refreshInterval = 5 # refresh interval in seconds
self._files = []
if submitters:
self._filePollerRefresh = PollerRefreshStatus.MINIMAL_ENABLED
else:
self._filePollerRefresh = PollerRefreshStatus.DISABLED
def __del__(self):
self._threadPool.terminate()
self._threadPool.join()
def start(self, files=None):
""" Start polling thread.
Args:
files: the list of files to monitor
"""
if self._filePollerRefresh is PollerRefreshStatus.DISABLED:
return
if self._thread:
# thread already running, return
return
self._stopFlag.clear()
self._files = files or []
self._thread = Thread(target=self.run)
self._thread.start()
def setFiles(self, files):
""" Set the list of files to monitor
Args:
files: the list of files to monitor
"""
logging.debug(f"FilesModTimePollerThread: Watch files {files}")
with self._mutex:
self._files = files
def stop(self):
""" Request polling thread to stop. """
if not self._thread:
return
self._stopFlag.set()
self._thread.join()
self._thread = None
@staticmethod
def getFileLastModTime(f):
""" Return 'mtime' of the file if it exists, -1 otherwise. """
try:
return os.path.getmtime(f)
except OSError:
return -1
def run(self):
""" Poll watched files for last modification time. """
while not self._stopFlag.wait(self._refreshInterval):
with self._mutex:
files = list(self._files)
times = self._threadPool.map(FilesModTimePollerThread.getFileLastModTime, files)
with self._mutex:
if files == self._files:
self.timesAvailable.emit(times)
def onFilePollerRefreshChanged(self, value):
""" Stop or start the file poller depending on the new refresh status. """
self._filePollerRefresh = PollerRefreshStatus(value)
if self._filePollerRefresh is PollerRefreshStatus.DISABLED:
self.stop()
else:
self.start()
self.filePollerRefreshReady.emit()
filePollerRefresh = Property(int, lambda self: self._filePollerRefresh.value, constant=True)
filePollerRefreshReady = Signal() # The refresh status has been updated and is ready to be used
class NodeStatusMonitor(QObject):
"""
NodeStatusMonitor regularly check status files for modification and trigger their update on change.
When working locally, status changes are reflected through the emission of 'statusChanged' signals.
But when a graph is being computed externally - either via a Submitter or on another machine,
Status files are modified by another instance, potentially outside this machine file system scope.
Same goes when status files are deleted/modified manually.
Thus, for genericity, monitoring is based on regular polling and not file system watching.
"""
def __init__(self, parent=None):
super().__init__(parent)
self.monitorableNodes = []
self.monitoredFiles = {} # Dict {filepath: node}
self._filesTimePoller = FilesModTimePollerThread(parent=self)
self._filesTimePoller.timesAvailable.connect(self.compareFilesTimes)
self._filesTimePoller.start()
self.setMonitored([])
self.filePollerRefreshChanged.connect(self._filesTimePoller.onFilePollerRefreshChanged)
self._filesTimePoller.filePollerRefreshReady.connect(self.onFilePollerRefreshUpdated)
def setWatchedFiles(self):
self.monitoredItems = self.getMonitoredFiles()
monitoredFiles = list([f for f in self.monitoredItems.keys()])
self._filesTimePoller.setFiles(monitoredFiles)
def setMonitored(self, nodes):
self.monitorableNodes = nodes
self.setWatchedFiles()
def stop(self):
""" Stop the status files monitoring. """
self._filesTimePoller.stop()
def getMonitoredFiles(self):
monitoredItems = OrderedDict()
for node in self.monitorableNodes:
if node._chunksCreated:
fileItems = {c.getStatusFile(): ("chunk", c) for c in node._chunks}
else:
fileItems = {node.nodeStatusFile: ("node", node)}
if self.filePollerRefresh is PollerRefreshStatus.AUTO_ENABLED.value:
# Add everything
monitoredItems.update(fileItems)
elif self.filePollerRefresh is PollerRefreshStatus.MINIMAL_ENABLED.value:
# Only chunks that are run externally or local_isolated should be monitored,
# when run locally, status changes are already notified.
# Chunks with an ERROR status may be re-submitted externally and should thus still be monitored
for file, (_type, _item) in fileItems.items():
if not _item.shouldMonitorChanges():
continue
monitoredItems[file] = (_type, _item)
return monitoredItems
def compareFilesTimes(self, times):
"""
Compare previous file modification times with results from last poll.
Trigger chunk status update if file was modified since.
Args:
times: the last modification times for currently monitored files.
"""
newRecords = dict(zip(self.monitoredItems.items(), times))
nodesToUpdate = set()
for monitoredItem, fileModTime in newRecords.items():
_, (_type, _item) = monitoredItem
if _type == "chunk":
chunk = _item
# update chunk status if last modification time has changed since previous record
if fileModTime != chunk.statusFileLastModTime:
chunk.updateStatusFromCache()
if chunk._status.status == Status.SUCCESS:
nodesToUpdate.add(chunk.node)
elif _type == "node":
node = _item
if fileModTime != node.nodeStatusFileLastModTime:
node.updateStatusFromCache()
# Check for success
if node.getGlobalStatus() == Status.SUCCESS:
nodesToUpdate.add(node)
elif node._chunksCreated:
# Chunks have been created -> set the watched files again
self.setWatchedFiles()
for node in nodesToUpdate:
node.loadOutputAttr()
def onFilePollerRefreshUpdated(self):
"""
Upon an update of the file poller status, retrigger the generation of the list of status files for
the chunks that are to be watched.
In auto-refresh mode, this includes all the chunks' status files.
In minimal auto-refresh mode, this includes only the chunks that are submitted or running.
"""
if self.filePollerRefresh is not PollerRefreshStatus.DISABLED.value:
self.setWatchedFiles()
def onComputeStatusChanged(self):
"""
When a chunk's status is updated, update the list of watched files with submitted and running chunks if the
file poller status is minimal auto-refresh.
"""
if self.filePollerRefresh is PollerRefreshStatus.MINIMAL_ENABLED.value:
self.setWatchedFiles()
filePollerRefreshChanged = Signal(int)
filePollerRefresh = Property(int, lambda self: self._filesTimePoller.filePollerRefresh, notify=filePollerRefreshChanged)
class GraphLayout(QObject):
"""
GraphLayout provides auto-layout features to a UIGraph.
"""
class DepthMode(Enum):
""" Defines available node depth mode to layout the graph automatically. """
MinDepth = 0 # use node minimal depth
MaxDepth = 1 # use node maximal depth
# map between DepthMode and corresponding node depth attribute name
_depthAttribute = {
DepthMode.MinDepth: 'minDepth',
DepthMode.MaxDepth: 'depth'
}
def __init__(self, graph):
super().__init__(graph)
self.graph = graph
self._depthMode = GraphLayout.DepthMode.MaxDepth
self._nodeWidth = 160 # implicit node width
self._nodeHeight = 120 # implicit node height
self._gridSpacing = 40 # column/line spacing between nodes
@Slot(Node, Node, int, int)
def autoLayout(self, fromNode=None, toNode=None, startX=0, startY=0):
"""
Perform auto-layout from 'fromNode' to 'toNode', starting from (startX, startY) position.
Args:
fromNode (BaseNode): where to start the auto layout from
toNode (BaseNode): up to where to perform the layout
startX (int): start position x coordinate
startY (int): start position y coordinate
"""
if not self.graph.nodes:
return
fromIndex = self.graph.nodes.indexOf(fromNode) if fromNode else 0
toIndex = self.graph.nodes.indexOf(toNode) if toNode else self.graph.nodes.count - 1
def getDepth(n):
return getattr(n, self._depthAttribute[self._depthMode])
maxDepth = max([getDepth(n) for n in self.graph.nodes.values()])
grid = [[] for _ in range(maxDepth + 1)]
# retrieve reference depth from start node
zeroDepth = getDepth(self.graph.nodes.at(fromIndex)) if fromIndex > 0 else 0
for i in range(fromIndex, toIndex + 1):
n = self.graph.nodes.at(i)
grid[getDepth(n) - zeroDepth].append(n)
with self.graph.groupedGraphModification("Graph Auto-Layout"):
for x, line in enumerate(grid):
for y, node in enumerate(line):
px = startX + x * (self._nodeWidth + self._gridSpacing)
py = startY + y * (self._nodeHeight + self._gridSpacing)
self.graph.moveNode(node, Position(px, py))
@Slot()
def reset(self):
""" Perform auto-layout on the whole graph. """
self.autoLayout()
def positionBoundingBox(self, nodes=None):
"""
Return bounding box for a set of nodes as (x, y, width, height).
Args:
nodes (list of Node): the list of nodes or the whole graph if None
Returns:
list of int: the resulting bounding box (x, y, width, height)
"""
if nodes is None:
nodes = self.graph.nodes.values()
if not nodes:
return [0, 0, 0, 0]
first = nodes[0]
bbox = [first.x, first.y, first.x, first.y]
for n in nodes:
bbox[0] = min(bbox[0], n.x)
bbox[1] = min(bbox[1], n.y)
bbox[2] = max(bbox[2], n.x)
bbox[3] = max(bbox[3], n.y)
bbox[2] -= bbox[0]
bbox[3] -= bbox[1]
return bbox
def boundingBox(self, nodes=None):
"""
Return bounding box for a set of nodes as (x, y, width, height).
Args:
nodes (list of Node): the list of nodes or the whole graph if None
Returns:
list of int: the resulting bounding box (x, y, width, height)
"""
bbox = self.positionBoundingBox(nodes)
bbox[2] += self._nodeWidth
bbox[3] += self._nodeHeight
return bbox
def setDepthMode(self, mode):
""" Set node depth mode to use. """
if isinstance(mode, int):
mode = GraphLayout.DepthMode(mode)
if self._depthMode.value == mode.value:
return
self._depthMode = mode
depthModeChanged = Signal()
depthMode = Property(int, lambda self: self._depthMode.value, setDepthMode, notify=depthModeChanged)
nodeHeightChanged = Signal()
nodeHeight = makeProperty(int, "_nodeHeight", notify=nodeHeightChanged)
nodeWidthChanged = Signal()
nodeWidth = makeProperty(int, "_nodeWidth", notify=nodeWidthChanged)
gridSpacingChanged = Signal()
gridSpacing = makeProperty(int, "_gridSpacing", notify=gridSpacingChanged)
class UIGraph(QObject):
""" High level wrapper over core.Graph, with additional features dedicated to UI integration.
UIGraph exposes undoable methods on its graph and computation in a separate thread.
It also provides a monitoring of all its computation units (NodeChunks).
"""
def __init__(self, undoStack: commands.UndoStack, taskManager: TaskManager, parent: QObject = None):
super().__init__(parent)
self._undoStack = undoStack
self._taskManager = taskManager
self._graph: Graph = Graph('', self)
self._modificationCount = 0
self._chunksMonitor: NodeStatusMonitor = NodeStatusMonitor(parent=self)
self._computeThread: Thread = Thread()
self._computingLocally = self._submitted = False
self._sortedDFSChunks: QObjectListModel = QObjectListModel(parent=self)
self._layout: GraphLayout = GraphLayout(self)
self._selectedNode = None
self._selectedChunk = None
self._nodeSelection: QItemSelectionModel = QItemSelectionModel(self._graph.nodes, parent=self)
self._hoveredNode = None
self.submitLabel = "{projectName}"
self.computeStatusChanged.connect(self.updateLockedUndoStack)
self.filePollerRefreshChanged.connect(self._chunksMonitor.filePollerRefreshChanged)
def setGraph(self, g):
""" Set the internal graph. """
if self._graph:
self.stopExecution()
# Clear all the locally submitted nodes at once before the graph gets changed, as it won't receive further updates
if self._computingLocally:
self._graph.clearLocallySubmittedNodes()
self.clear()
oldGraph = self._graph
self._graph = g
if oldGraph:
oldGraph.deleteLater()
self._graph.updated.connect(self.onGraphUpdated)
self._graph.statusUpdated.connect(self.updateChunkMonitor)
self._taskManager.update(self._graph)
# update and connect chunks when the graph is set for the first time
self.updateChunks()
# perform auto-layout if graph does not provide nodes positions
if GraphIO.Features.NodesPositions not in self._graph.fileFeatures:
self._layout.reset()
# clear undo-stack after layout
self._undoStack.clear()
else:
bbox = self._layout.positionBoundingBox()
if bbox[2] == 0 and bbox[3] == 0:
self._layout.reset()
# clear undo-stack after layout
self._undoStack.clear()
self._nodeSelection.setModel(self._graph.nodes)
self.graphChanged.emit()
def onGraphUpdated(self):
""" Callback to any kind of attribute modification. """
# TODO: handle this with a better granularity
self.updateChunks()
def updateChunks(self):
dfsNodes = self._graph.dfsOnFinish(None)[0]
chunks = []
for node in dfsNodes:
if node._chunksCreated:
nodechunks = node.getChunks()
chunks.extend(nodechunks)
else:
chunks.extend(node.chunkPlaceholder)
if self._sortedDFSChunks.objectList() == chunks:
# Nothing has changed, return
return
for chunk in self._sortedDFSChunks:
if chunk not in chunks:
# Chunk have been already deleted
continue
chunk.statusChanged.disconnect(self.updateGraphComputingStatus)
chunk.statusChanged.disconnect(self._chunksMonitor.onComputeStatusChanged)
self._sortedDFSChunks.setObjectList(chunks)
for chunk in self._sortedDFSChunks:
chunk.statusChanged.connect(self.updateGraphComputingStatus)
chunk.statusChanged.connect(self._chunksMonitor.onComputeStatusChanged)
# provide ChunkMonitor with the update list of chunks
self.updateChunkMonitor()
# update graph computing status based on the new list of NodeChunks
self.updateGraphComputingStatus()
def updateChunkMonitor(self):
""" Update the list of chunks for status files monitoring. """
nodes = set()
for node in self._graph.dfsOnFinish(None)[0]:
if not node._chunksCreated:
nodes.add(node)
for chunk in self._sortedDFSChunks:
nodes.add(chunk.node)
self._chunksMonitor.setMonitored(list(nodes))
def clear(self):
if self._graph:
self.clearNodeHover()
self.clearNodeSelection()
self._taskManager.clear()
self._graph.clear()
self._sortedDFSChunks.clear()
self._undoStack.clear()
def stopChildThreads(self):
""" Stop all child threads. """
self.stopExecution()
self._chunksMonitor.stop()
@Slot(str)
def loadGraph(self, filepath):
g = Graph("")
if filepath:
g.load(filepath)
if not os.path.exists(g.cacheDir):
os.mkdir(g.cacheDir)
self.setGraph(g)
@Slot(str)
@Slot(str, bool)
def initFromTemplate(self, filepath, copyOutputs=False):
graph = Graph("")
if filepath:
graph.initFromTemplate(filepath, copyOutputs=copyOutputs)
self.setGraph(graph)
@Slot(QUrl, result="QVariantList")
@Slot(QUrl, QPoint, result="QVariantList")
def importProject(self, filepath, position=None):
if isinstance(filepath, (QUrl)):
# depending how the QUrl has been initialized,
# toLocalFile() may return the local path or an empty string
localFile = filepath.toLocalFile()
if not localFile:
localFile = filepath.toString()
else:
localFile = filepath
if isinstance(position, QPoint):
position = Position(position.x(), position.y())
yOffset = self.layout.gridSpacing + self.layout.nodeHeight
return self.push(commands.ImportProjectCommand(self._graph, localFile, position=position, yOffset=yOffset))
@Slot(QUrl)
def saveAs(self, url):
self._saveAs(url)
@Slot(QUrl)
def saveAsTemplate(self, url):
self._saveAs(url, setupProjectFile=False, template=True)
def _saveAs(self, url, setupProjectFile=True, template=False):
""" Helper function for 'save as' features. """
if isinstance(url, (str)):
localFile = url
else:
localFile = url.toLocalFile()
# ensure file is saved with ".mg" extension
if os.path.splitext(localFile)[-1] != ".mg":
localFile += ".mg"
self.parent().showMessage(f"Saving file to {localFile}", "ok")
self._graph.save(localFile, setupProjectFile=setupProjectFile, template=template)
self._undoStack.setClean()
# saving file on disk impacts cache folder location
# => force re-evaluation of monitored status files paths
self.updateChunkMonitor()
@Slot()
def saveAsTemp(self):
projectPath = generateTempProjectFilepath()
self._saveAs(projectPath)
@Slot()
def save(self):
self._graph.save()
self._undoStack.setClean()
@Slot()
def saveAsNewVersion(self):
self._graph.saveAsNewVersion()
self._undoStack.setClean()
@Slot()
def updateLockedUndoStack(self):
if self.isComputingLocally():
self._undoStack.lockAtThisIndex()
else:
self._undoStack.unlock()
@Slot()
@Slot(Node)
@Slot(list)
def execute(self, nodes: Optional[Union[list[Node], Node]] = None):
nodes = [nodes] if not isinstance(nodes, Iterable) and nodes else nodes
self.save() # always save the graph before computing
self._taskManager.compute(self._graph, nodes)
self.updateLockedUndoStack() # explicitly call the update while it is already computing
@Slot()
def stopExecution(self):
self.updateChunks()
if not self.isComputingLocally():
return
self._taskManager.requestBlockRestart()
self._graph.stopExecution()
self._taskManager.join()
@Slot(Node)
def stopNodeComputation(self, node):
""" Stop the computation of the node and update all the nodes depending on it. """
self.updateChunks()
if not self.isComputingLocally():
return
# Stop the node and wait Task Manager
node.stopComputation()
self._taskManager.join()
@Slot(Node)
def cancelNodeComputation(self, node):
""" Cancel the computation of the node and all the nodes depending on it. """
self.updateChunks()
if node.getGlobalStatus() == Status.SUBMITTED:
# Status from SUBMITTED to NONE
# Make sure to remove the nodes from the Task Manager list
node.clearSubmittedChunks()
self._taskManager.removeNode(node, displayList=True, processList=True)
for n in node.getOutputNodes(recursive=True, dependenciesOnly=True):
n.clearSubmittedChunks()
self._taskManager.removeNode(n, displayList=True, processList=True)
def isChunkComputingLocally(self, chunk):
# update graph computing status
computingLocally = chunk._status.execMode == ExecMode.LOCAL and \
(sessionUid in (chunk.node._nodeStatus.submitterSessionUid, chunk._status.computeSessionUid)) and \
(chunk._status.status in (Status.RUNNING, Status.SUBMITTED))
return computingLocally
def isChunkComputingExternally(self, chunk):
# Note: We do not check computeSessionUid for the submitted status,
# as the source instance of the submit has no importance.
return (chunk._status.execMode == ExecMode.EXTERN) and \
chunk._status.status in (Status.RUNNING, Status.SUBMITTED)
@Slot(NodeChunk)
def stopTask(self, chunk: NodeChunk):
""" Stop the selected task """
chunk.updateStatusFromCache()
if not chunk.isAlreadySubmitted():
return
node = chunk.node
job = jobManager.getNodeJob(node)
if job:
chunkIteration = chunk.range.iteration
try:
job.stopChunkTask(node, chunkIteration)
except Exception as e:
self.parent().showMessage(f"Failed to stop chunk {chunkIteration} of {node.label}", "error")
logging.warning(f"Error on stopTask:\n{e}")
else:
chunk.updateStatusFromCache()
chunk.upgradeStatusTo(Status.STOPPED)
# TODO : Stop depending nodes ?
self.parent().showMessage(f"Stopped chunk {chunkIteration} of {node.label}")
else:
chunk.stopProcess()
self._taskManager._cancelledChunks.append(chunk)
for chunk in node._chunks:
if chunk._status.status == Status.SUBMITTED:
chunk.stopProcess()
self._taskManager._cancelledChunks.append(chunk)
for n in node.getOutputNodes(recursive=True, dependenciesOnly=True):
n.clearSubmittedChunks()
self._taskManager.removeNode(n, displayList=True, processList=True)
@Slot(Node)
def stopNode(self, node: Node):
""" Stop the selected task """
job = jobManager.getNodeJob(node)
if job:
try:
job.stopChunkTask(node, -1)
except Exception as e:
self.parent().showMessage(f"Failed to stop node {node.label}", "error")
logging.warning(f"Error on stopTask:\n{e}")
else:
node.updateNodeStatusFromCache()
node.upgradeStatusTo(Status.STOPPED)
# TODO : Stop depending nodes ?
self.parent().showMessage(f"Stopped node {node.label}")
else:
self.cancelNodeComputation(node)
node.stopComputation()
@Slot(NodeChunk)
def restartTask(self, chunk: NodeChunk):
""" Relaunch a stopped task """
node = chunk.node
job = jobManager.getNodeJob(node)
if job:
chunkIteration = chunk.range.iteration
try:
chunk.updateStatusFromCache()
chunk.upgradeStatusTo(Status.SUBMITTED)
job.restartChunkTask(node, chunkIteration)
except Exception as e:
chunk.updateStatusFromCache()
chunk.upgradeStatusTo(Status.ERROR)
self.parent().showMessage(f"Failed to relaunch chunk {chunkIteration} of {node.label}", "error")
logging.warning(f"Error on restartTask:\n{e}")
else:
self.parent().showMessage(f"Relaunched chunk {chunkIteration} of {node.label}")
else:
# For this we would need to use a pool (with either chunks or nodes)
# instead of the list of nodes that are processed serially
self.parent().showMessage(f"Chunks cannot be launched individually locally", "warning")
if self.canComputeNode(node):
self.execute([node])
@Slot(NodeChunk)
def skipTask(self, chunk: NodeChunk):
""" Skip the task : the job will continue as if the task succeeded
In local mode, the chunk status will be set to success
"""
chunk.updateStatusFromCache()
node = chunk.node
chunkIteration = chunk.range.iteration
job = jobManager.getNodeJob(node)
if job:
try:
job.skipChunkTask(node, chunkIteration)
except Exception as e:
self.parent().showMessage(f"Failed to skip chunk {chunkIteration} of {node.label}", "error")
logging.warning(f"Error on skipTask:\n{e}")
else:
chunk.upgradeStatusTo(Status.SUCCESS)
self.parent().showMessage(f"Skipped chunk {chunkIteration} of {node.label}")
else:
chunk.stopProcess()
chunk.upgradeStatusTo(Status.SUCCESS)
self._taskManager._cancelledChunks.append(chunk)
self.parent().showMessage(f"Skipped chunk {chunkIteration} of {node.label}")
@Slot(Node)
def pauseJob(self, node: Node):
""" Pause the running job : cancel all scheduled tasks.
Current task don't stop but future tasks won't be launched
"""
job = jobManager.getNodeJob(node)
if job:
try:
job.pauseJob()
except Exception as e:
logging.warning(f"Error on pauseJob:\n{e}")
self.parent().showMessage(f"Failed to pause the job for node {node}", "error")
else:
self.parent().showMessage(f"Paused node {node.label} on farm")
elif not node.isExtern():
self.parent().showMessage(f"PauseJob is only available in external computation mode!", "warning")
else:
self.parent().showMessage(f"Cannot retrieve the job", "error")
@Slot(Node)
def resumeJob(self, node: Node):
""" Resume the paused job
"""
job = jobManager.getNodeJob(node)
if job:
# Node is submitted to farm
try:
job.resumeJob()
except Exception as e:
self.parent().showMessage(f"Failed to resume node {node.label} on farm")
logging.warning(f"Error on resumeJob:\n{e}")
else:
self.parent().showMessage(f"Resumed the job for node {node}")
else:
# In this case user can just relaunch the node computation
# Could be implemented if we had a paused state on the task manager
# Where unprocessed nodes are retained
pass
@Slot(Node)
def interruptJob(self, node: Node):
""" Interrupt the job that processes the node
"""
job = jobManager.getNodeJob(node)
if job:
try:
job.interruptJob()
except Exception as e:
self.parent().showMessage(f"Failed to interrupt node {node.label} on farm", "error")
logging.warning(f"Error on interruptJob:\n{e}")
else:
for chunk in self._sortedDFSChunks:
if jobManager.getNodeJob(chunk.node) == job:
if chunk._status.status in (Status.SUBMITTED, Status.RUNNING):
chunk.updateStatusFromCache()
chunk.upgradeStatusTo(Status.STOPPED)
for _node in self._graph.dfsOnFinish(None)[0]:
if jobManager.getNodeJob(_node) == job and not _node._chunksCreated and \
_node._nodeStatus.status in (Status.SUBMITTED, Status.RUNNING):
_node.upgradeStatusTo(Status.STOPPED)
self.parent().showMessage(f"Interrupted the job for node {node}")
elif not node.isExtern():
for chunk in self._sortedDFSChunks:
if not chunk.isExtern() and chunk._status.status in (Status.SUBMITTED, Status.RUNNING):
chunk.updateStatusFromCache()
chunk.upgradeStatusTo(Status.STOPPED)
for node in self._graph.dfsOnFinish(None)[0]:
if not node.isExtern() and not node._chunksCreated and \
node._nodeStatus.status in (Status.SUBMITTED, Status.RUNNING):
node.upgradeStatusTo(Status.STOPPED)
self.stopExecution()
self.parent().showMessage(f"Stopped the local job process")
else:
self.parent().showMessage(f"Could not retrieve job for node {node}", "error")
@Slot(Node)
def restartJobErrorTasks(self, node: Node):
""" Restart all tasks in the job that have failed
"""
job = jobManager.getNodeJob(node)
if job:
try:
# Fist update status of each chunk to submitted
for chunk in self._sortedDFSChunks:
if chunk._status.status not in (Status.ERROR, Status.STOPPED, Status.KILLED):
continue
if jobManager.getNodeJob(chunk.node) == job:
chunk.upgradeStatusTo(Status.SUBMITTED)
for node in self._graph.dfsOnFinish(None)[0]:
if not node._chunksCreated and node._nodeStatus.status in (Status.ERROR, Status.STOPPED, Status.KILLED):
node.upgradeStatusTo(Status.SUBMITTED)
job.restartErrorTasks()
job.resumeJob()
except Exception as e:
self.parent().showMessage(f"Failed to restart error tasks for node {node.label} on farm", "error")
logging.warning(f"Error on restartJobErrorTasks:\n{e}")
else:
self.parent().showMessage(f"Restarted error tasks for the node {node}")
else:
# In this case user can just relaunch the node computation
# Could be implemented if we had a paused state on the task manager
# Where error/failed nodes are retained
pass
@Slot()
@Slot(Node)
@Slot(list)
def submit(self, nodes: Optional[Union[list[Node], Node]] = None):
""" Submit the graph to the default Submitter.
If a node is specified, submit this node and its uncomputed predecessors.
Otherwise, submit the whole
Notes:
Default submitter is specified using the MESHROOM_DEFAULT_SUBMITTER environment variable.
"""
self.save() # graph must be saved before being submitted
self._undoStack.clear() # the undo stack must be cleared
nodes = [nodes] if not isinstance(nodes, Iterable) and nodes else nodes
mrDefaultSubmitter = os.environ.get('MESHROOM_DEFAULT_SUBMITTER', '')
chosenSubmitter = self.parent()._defaultSubmitterName or mrDefaultSubmitter
self.parent().showMessage(f"Submit job on farm through {chosenSubmitter}")
self.parent().showMessage(f"Nodes to submit : {nodes}")
self._taskManager.submit(self._graph, chosenSubmitter, nodes, submitLabel=self.submitLabel)
def updateGraphComputingStatus(self):
dfsNodes = self._graph.dfsOnFinish(None)[0]
# TODO : these functions should go on the node part
# We should do any([node.isRunning for node in dfsNodes])
# update graph computing status
computingLocally = any([
ch._status.execMode == ExecMode.LOCAL and \
(sessionUid in (ch.node._nodeStatus.submitterSessionUid, ch._status.computeSessionUid)) and \
(ch._status.status in (Status.RUNNING, Status.SUBMITTED))
for ch in self._sortedDFSChunks
])
# Note: We do not check computeSessionUid for the submitted status,
# as the source instance of the submit has no importance.
submitted = any([ch._status.execMode == ExecMode.EXTERN and ch._status.status in (Status.RUNNING, Status.SUBMITTED) for ch in self._sortedDFSChunks])
# Handle nodes with uninitialized chunks
for node in dfsNodes:
if node._chunksCreated:
continue
if node._nodeStatus.status in (Status.RUNNING, Status.SUBMITTED):
# TODO : save session ID in node
if node._nodeStatus.execMode == ExecMode.LOCAL:
computingLocally = True
elif node._nodeStatus.execMode == ExecMode.EXTERN:
submitted = True
if self._computingLocally != computingLocally or self._submitted != submitted:
self._computingLocally = computingLocally
self._submitted = submitted
self.computeStatusChanged.emit()
def isComputing(self):
""" Whether is graph is being computed, either locally or externally. """
return self.isComputingLocally() or self.isComputingExternally()
def isComputingExternally(self):
""" Whether this graph is being computed externally. """
return self._submitted
def isComputingLocally(self):
""" Whether this graph is being computed locally (i.e computation can be stopped). """
## One solution could be to check if the thread is still running,
# but the latency in creating/stopping the thread can be off regarding the update signals.
# isRunningThread = self._taskManager._thread.isRunning()
## Another solution is to retrieve the current status directly from all chunks status
# isRunning = self._taskManager.hasRunningChunks()
## For performance reason, we use a precomputed value updated in updateGraphComputingStatus:
return self._computingLocally
def push(self, command):
""" Try and push the given command to the undo stack.
Args:
command (commands.UndoCommand): the command to push
"""
return self._undoStack.tryAndPush(command)
def groupedGraphModification(self, title, disableUpdates=True):
""" Get a GroupedGraphModification for this Graph.
Args:
title (str): the title of the macro command
disableUpdates (bool): whether to disable graph updates
Returns:
GroupedGraphModification: the instantiated context manager
"""
return commands.GroupedGraphModification(self._graph, self._undoStack, title, disableUpdates)
@Slot(str)
def beginModification(self, name):
""" Begin a Graph modification. Calls to beginModification and endModification may be nested, but
every call to beginModification must have a matching call to endModification. """
self._modificationCount += 1
self._undoStack.beginMacro(name)
@Slot()
def endModification(self):
""" Ends a Graph modification. Must match a call to beginModification. """
assert self._modificationCount > 0
self._modificationCount -= 1
self._undoStack.endMacro()
@Slot(str, QPoint, result=QObject)
def addNewNode(self, nodeType, position=None, **kwargs):
""" [Undoable]
Create a new Node of type 'nodeType' and returns it.
Args:
nodeType (str): the type of the Node to create.
position (QPoint): (optional) the initial position of the node
**kwargs: optional node attributes values
Returns:
Node: the created node
"""
if isinstance(position, QPoint):
position = Position(position.x(), position.y())
return self.push(commands.AddNodeCommand(self._graph, nodeType, position=position, **kwargs))
@Slot(Node, str, result=str)
def renameNode(self, node: Node, newName: str):
""" Triggers the node renaming.
In this function the last `_N` index is removed, then all special characters
(everything except letters and numbers) are removed.
The name uniqueness will be ensured later by adding a suffix (e.g. `_1`, `_2`, ...)
Labels can be used to have special characters in the displayed name.
Args:
node (Node): Node to rename.
newName (str): New name to set.
Returns:
str: The final name of the node.
"""
newName = "_".join(newName.split("_")[:-1]) if "_" in newName else newName
# Eliminate all characters except digits and letters
newName = re.sub(r"[^0-9a-zA-Z]", "", newName)
# Create unique name
uniqueName = self._graph._createUniqueNodeName(newName, {n._name for n in self._graph._nodes if n != node})
if not newName or uniqueName == node._name:
return ""
return self.push(commands.RenameNodeCommand(self._graph, node, uniqueName))
def moveNode(self, node: Node, position: Position):
"""
Move `node` to the given `position`.
Args:
node: The node to move.
position: The target position.
"""
self.push(commands.MoveNodeCommand(self._graph, node, position))
@Slot(QPoint)
def moveSelectedNodesBy(self, offset: QPoint):
"""Move all the selected nodes by the given `offset`."""
with self.groupedGraphModification("Move Selected Nodes"):
for node in self.iterSelectedNodes():
position = Position(node.x + offset.x(), node.y + offset.y())
self.moveNode(node, position)
def getMeanPosition(self):
""" Get the average Position of selected nodes """
# Not great, would be better if Position was a non-tuple class
selectedNodes = self.getSelectedNodes()
sum_pose = [0, 0]
nb_tot = 0
for selectedNode in selectedNodes:
sum_pose[0] += selectedNode.x
sum_pose[1] += selectedNode.y
nb_tot += 1
return Position(int(sum_pose[0] / nb_tot), int(sum_pose[1] / nb_tot))