-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathnode.py
More file actions
2018 lines (1705 loc) · 80.5 KB
/
Copy pathnode.py
File metadata and controls
2018 lines (1705 loc) · 80.5 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
# coding:utf-8
import atexit
import copy
import datetime
import json
import logging
import os
import platform
import re
import shutil
import time
import types
import uuid
from collections import defaultdict, namedtuple
from enum import Enum
import meshroom
from meshroom.common import Signal, Variant, Property, BaseObject, Slot, ListModel, DictModel
from meshroom.core import desc, stats, hashValue, nodeVersion, Version
from meshroom.core.attribute import attributeFactory, ListAttribute, GroupAttribute, Attribute
from meshroom.core.exception import NodeUpgradeError, UnknownNodeTypeError
def getWritingFilepath(filepath):
return filepath + '.writing.' + str(uuid.uuid4())
def renameWritingToFinalPath(writingFilepath, filepath):
if platform.system() == 'Windows':
# On Windows, attempting to remove a file that is in use causes an exception to be raised.
# So we may need multiple trials, if someone is reading it at the same time.
for i in range(20):
try:
os.remove(filepath)
# if remove is successful, we can stop the iterations
break
except WindowsError:
pass
os.rename(writingFilepath, filepath)
class Status(Enum):
"""
"""
NONE = 0
SUBMITTED = 1
RUNNING = 2
ERROR = 3
STOPPED = 4
KILLED = 5
SUCCESS = 6
INPUT = 7 # special status for input nodes
class ExecMode(Enum):
NONE = 0
LOCAL = 1
EXTERN = 2
class ForLoopData(BaseObject):
"""
"""
def __init__(self, parentNode=None, connectedAttribute=None, parent=None):
super(ForLoopData, self).__init__(parent)
self._countForLoop = 0
self._iterations = ListModel(parent=self) # list of nodes for each iteration
self._parentNode = parentNode # parent node
self.connectedAttribute = connectedAttribute # attribute connected to the ForLoop node from parent node
def update(self, currentNode=None):
# set the connectedAttribute
forLoopAttribute = None
if currentNode is not None:
for attr in currentNode._attributes:
if attr.isInput and attr.isLink:
forLoopAttribute = currentNode._attributes.indexOf(attr)
srcAttr = attr.getLinkParam()
# If the srcAttr is a ListAttribute, it means that the node is in a ForLoop
if isinstance(srcAttr.root, ListAttribute) and srcAttr.type == attr.type:
self.connectedAttribute = srcAttr.root
self._parentNode = srcAttr.root.node
break
# set the countForLoop
if self.connectedAttribute is not None:
self._countForLoop = self._parentNode._forLoopData._countForLoop + 1
if self.connectedAttribute.isInput:
self._countForLoop -= 1 if self._countForLoop > 1 else 1
# set the iterations by creating iteration nodes for each connected attribute value and will add them to the core graph and not the ui one
for i in range(len(self.connectedAttribute.value)):
# name of the iteration node
name = "{}_{}".format(currentNode.name, i)
# check if node already exists
if name not in [n.name for n in self._parentNode.graph.nodes]:
iterationNode = IterationNode(currentNode, i, forLoopAttribute)
self._parentNode.graph.addNode(iterationNode, iterationNode.name)
else :
# find node by name
iterationNode = self._parentNode.graph.node(name)
iterationNode._updateChunks()
self._iterations.append(iterationNode)
print("parent internal folder: ", currentNode.internalFolder)
self.parentNodeChanged.emit()
self.iterationsChanged.emit()
self.countForLoopChanged.emit()
countForLoopChanged = Signal()
countForLoop = Property(int, lambda self: self._countForLoop, notify=countForLoopChanged)
iterationsChanged = Signal()
iterations = Property(Variant, lambda self: self._iterations, notify=iterationsChanged)
parentNodeChanged = Signal()
parentNode = Property(Variant, lambda self: self._parentNode, notify=parentNodeChanged)
class StatusData(BaseObject):
"""
"""
dateTimeFormatting = '%Y-%m-%d %H:%M:%S.%f'
def __init__(self, nodeName='', nodeType='', packageName='', packageVersion='', parent=None):
super(StatusData, self).__init__(parent)
self.status = Status.NONE
self.execMode = ExecMode.NONE
self.nodeName = nodeName
self.nodeType = nodeType
self.packageName = packageName
self.packageVersion = packageVersion
self.graph = ''
self.commandLine = None
self.env = None
self.startDateTime = ""
self.endDateTime = ""
self.elapsedTime = 0
self.hostname = ""
self.sessionUid = meshroom.core.sessionUid
def merge(self, other):
self.startDateTime = min(self.startDateTime, other.startDateTime)
self.endDateTime = max(self.endDateTime, other.endDateTime)
self.elapsedTime += other.elapsedTime
def reset(self):
self.status = Status.NONE
self.execMode = ExecMode.NONE
self.graph = ''
self.commandLine = None
self.env = None
self.startDateTime = ""
self.endDateTime = ""
self.elapsedTime = 0
self.hostname = ""
self.sessionUid = meshroom.core.sessionUid
def initStartCompute(self):
import platform
self.sessionUid = meshroom.core.sessionUid
self.hostname = platform.node()
self.startDateTime = datetime.datetime.now().strftime(self.dateTimeFormatting)
# to get datetime obj: datetime.datetime.strptime(obj, self.dateTimeFormatting)
def initEndCompute(self):
self.sessionUid = meshroom.core.sessionUid
self.endDateTime = datetime.datetime.now().strftime(self.dateTimeFormatting)
@property
def elapsedTimeStr(self):
return str(datetime.timedelta(seconds=self.elapsedTime))
def toDict(self):
d = self.__dict__.copy()
d.pop('destroyed', None) # skip non data attributes from BaseObject
d["elapsedTimeStr"] = self.elapsedTimeStr
return d
def fromDict(self, d):
self.status = d.get('status', Status.NONE)
if not isinstance(self.status, Status):
self.status = Status[self.status]
self.execMode = d.get('execMode', ExecMode.NONE)
if not isinstance(self.execMode, ExecMode):
self.execMode = ExecMode[self.execMode]
self.nodeName = d.get('nodeName', '')
self.nodeType = d.get('nodeType', '')
self.packageName = d.get('packageName', '')
self.packageVersion = d.get('packageVersion', '')
self.graph = d.get('graph', '')
self.commandLine = d.get('commandLine', '')
self.env = d.get('env', '')
self.startDateTime = d.get('startDateTime', '')
self.endDateTime = d.get('endDateTime', '')
self.elapsedTime = d.get('elapsedTime', 0)
self.hostname = d.get('hostname', '')
self.sessionUid = d.get('sessionUid', '')
class LogManager:
dateTimeFormatting = '%H:%M:%S'
def __init__(self, chunk):
self.chunk = chunk
self.logger = logging.getLogger(chunk.node.getName())
class Formatter(logging.Formatter):
def format(self, record):
# Make level name lower case
record.levelname = record.levelname.lower()
return logging.Formatter.format(self, record)
def configureLogger(self):
for handler in self.logger.handlers[:]:
self.logger.removeHandler(handler)
handler = logging.FileHandler(self.chunk.logFile)
formatter = self.Formatter('[%(asctime)s.%(msecs)03d][%(levelname)s] %(message)s', self.dateTimeFormatting)
handler.setFormatter(formatter)
self.logger.addHandler(handler)
def start(self, level):
# Clear log file
open(self.chunk.logFile, 'w').close()
self.configureLogger()
self.logger.setLevel(self.textToLevel(level))
self.progressBar = False
def end(self):
for handler in self.logger.handlers[:]:
# Stops the file being locked
handler.close()
def makeProgressBar(self, end, message=''):
assert end > 0
assert not self.progressBar
self.progressEnd = end
self.currentProgressTics = 0
self.progressBar = True
with open(self.chunk.logFile, 'a') as f:
if message:
f.write(message+'\n')
f.write('0% 10 20 30 40 50 60 70 80 90 100%\n')
f.write('|----|----|----|----|----|----|----|----|----|----|\n\n')
f.close()
with open(self.chunk.logFile, 'r') as f:
content = f.read()
self.progressBarPosition = content.rfind('\n')
f.close()
def updateProgressBar(self, value):
assert self.progressBar
assert value <= self.progressEnd
tics = round((value/self.progressEnd)*51)
with open(self.chunk.logFile, 'r+') as f:
text = f.read()
for i in range(tics-self.currentProgressTics):
text = text[:self.progressBarPosition]+'*'+text[self.progressBarPosition:]
f.seek(0)
f.write(text)
f.close()
self.currentProgressTics = tics
def completeProgressBar(self):
assert self.progressBar
self.progressBar = False
def textToLevel(self, text):
if text == 'critical':
return logging.CRITICAL
elif text == 'error':
return logging.ERROR
elif text == 'warning':
return logging.WARNING
elif text == 'info':
return logging.INFO
elif text == 'debug':
return logging.DEBUG
else:
return logging.NOTSET
runningProcesses = {}
@atexit.register
def clearProcessesStatus():
global runningProcesses
for k, v in runningProcesses.items():
v.upgradeStatusTo(Status.KILLED)
class NodeChunk(BaseObject):
def __init__(self, node, range, parent=None):
super(NodeChunk, self).__init__(parent)
self.node = node
self.range = range
self.logManager = LogManager(self)
self._status = StatusData(node.name, node.nodeType, node.packageName, node.packageVersion)
self.statistics = stats.Statistics()
self.statusFileLastModTime = -1
self._subprocess = None
# notify update in filepaths when node's internal folder changes
self.node.internalFolderChanged.connect(self.nodeFolderChanged)
self.execModeNameChanged.connect(self.node.globalExecModeChanged)
@property
def index(self):
return self.range.iteration
@property
def name(self):
if self.range.blockSize:
return "{}({})".format(self.node.name, self.index)
else:
return self.node.name
@property
def statusName(self):
return self._status.status.name
@property
def logger(self):
return self.logManager.logger
@property
def execModeName(self):
return self._status.execMode.name
def updateStatusFromCache(self):
"""
Update node status based on status file content/existence.
"""
statusFile = self.statusFile
oldStatus = self._status.status
# No status file => reset status to Status.None
if not os.path.exists(statusFile):
self.statusFileLastModTime = -1
self._status.reset()
else:
try:
with open(statusFile, 'r') as jsonFile:
statusData = json.load(jsonFile)
self.status.fromDict(statusData)
self.statusFileLastModTime = os.path.getmtime(statusFile)
except Exception as e:
self.statusFileLastModTime = -1
self.status.reset()
if oldStatus != self.status.status:
self.statusChanged.emit()
@property
def statusFile(self):
if self.range.blockSize == 0:
return os.path.join(self.node.graph.cacheDir, self.node.internalFolder, 'status')
else:
return os.path.join(self.node.graph.cacheDir, self.node.internalFolder, str(self.index) + '.status')
@property
def statisticsFile(self):
if self.range.blockSize == 0:
return os.path.join(self.node.graph.cacheDir, self.node.internalFolder, 'statistics')
else:
return os.path.join(self.node.graph.cacheDir, self.node.internalFolder, str(self.index) + '.statistics')
@property
def logFile(self):
if self.range.blockSize == 0:
return os.path.join(self.node.graph.cacheDir, self.node.internalFolder, 'log')
else:
return os.path.join(self.node.graph.cacheDir, self.node.internalFolder, str(self.index) + '.log')
def saveStatusFile(self):
"""
Write node status on disk.
"""
data = self._status.toDict()
statusFilepath = self.statusFile
folder = os.path.dirname(statusFilepath)
try:
os.makedirs(folder)
except Exception as e:
pass
statusFilepathWriting = getWritingFilepath(statusFilepath)
with open(statusFilepathWriting, 'w') as jsonFile:
json.dump(data, jsonFile, indent=4)
renameWritingToFinalPath(statusFilepathWriting, statusFilepath)
def upgradeStatusTo(self, newStatus, execMode=None):
if newStatus.value <= self._status.status.value:
logging.warning('Downgrade status on node "{}" from {} to {}'.format(self.name, self._status.status,
newStatus))
if newStatus == Status.SUBMITTED:
self._status = StatusData(self.node.name, self.node.nodeType, self.node.packageName, self.node.packageVersion)
if execMode is not None:
self._status.execMode = execMode
self.execModeNameChanged.emit()
self._status.status = newStatus
self.saveStatusFile()
self.statusChanged.emit()
def updateStatisticsFromCache(self):
"""
"""
oldTimes = self.statistics.times
statisticsFile = self.statisticsFile
if not os.path.exists(statisticsFile):
return
with open(statisticsFile, 'r') as jsonFile:
statisticsData = json.load(jsonFile)
self.statistics.fromDict(statisticsData)
if oldTimes != self.statistics.times:
self.statisticsChanged.emit()
def saveStatistics(self):
data = self.statistics.toDict()
statisticsFilepath = self.statisticsFile
folder = os.path.dirname(statisticsFilepath)
if not os.path.exists(folder):
os.makedirs(folder)
statisticsFilepathWriting = getWritingFilepath(statisticsFilepath)
with open(statisticsFilepathWriting, 'w') as jsonFile:
json.dump(data, jsonFile, indent=4)
renameWritingToFinalPath(statisticsFilepathWriting, statisticsFilepath)
def isAlreadySubmitted(self):
return self._status.status in (Status.SUBMITTED, Status.RUNNING)
def isAlreadySubmittedOrFinished(self):
return self._status.status in (Status.SUBMITTED, Status.RUNNING, Status.SUCCESS)
def isFinishedOrRunning(self):
return self._status.status in (Status.SUCCESS, Status.RUNNING)
def isRunning(self):
return self._status.status == Status.RUNNING
def isStopped(self):
return self._status.status == Status.STOPPED
def isFinished(self):
return self._status.status == Status.SUCCESS
def process(self, forceCompute=False):
if not forceCompute and self._status.status == Status.SUCCESS:
logging.info("Node chunk already computed: {}".format(self.name))
return
global runningProcesses
runningProcesses[self.name] = self
self._status.initStartCompute()
exceptionStatus = None
startTime = time.time()
self.upgradeStatusTo(Status.RUNNING)
self.statThread = stats.StatisticsThread(self)
self.statThread.start()
try:
self.node.nodeDesc.processChunk(self)
except Exception as e:
if self._status.status != Status.STOPPED:
exceptionStatus = Status.ERROR
raise
except (KeyboardInterrupt, SystemError, GeneratorExit) as e:
exceptionStatus = Status.STOPPED
raise
finally:
self._status.initEndCompute()
self._status.elapsedTime = time.time() - startTime
if exceptionStatus is not None:
self.upgradeStatusTo(exceptionStatus)
logging.info(' - elapsed time: {}'.format(self._status.elapsedTimeStr))
# ask and wait for the stats thread to stop
self.statThread.stopRequest()
self.statThread.join()
self.statistics = stats.Statistics()
del runningProcesses[self.name]
self.upgradeStatusTo(Status.SUCCESS)
def stopProcess(self):
if not self.isExtern():
if self._status.status == Status.RUNNING:
self.upgradeStatusTo(Status.STOPPED)
elif self._status.status == Status.SUBMITTED:
self.upgradeStatusTo(Status.NONE)
self.node.nodeDesc.stopProcess(self)
def isExtern(self):
return self._status.execMode == ExecMode.EXTERN or (
self._status.execMode == ExecMode.LOCAL and self._status.sessionUid != meshroom.core.sessionUid)
statusChanged = Signal()
status = Property(Variant, lambda self: self._status, notify=statusChanged)
statusName = Property(str, statusName.fget, notify=statusChanged)
execModeNameChanged = Signal()
execModeName = Property(str, execModeName.fget, notify=execModeNameChanged)
statisticsChanged = Signal()
nodeFolderChanged = Signal()
statusFile = Property(str, statusFile.fget, notify=nodeFolderChanged)
logFile = Property(str, logFile.fget, notify=nodeFolderChanged)
statisticsFile = Property(str, statisticsFile.fget, notify=nodeFolderChanged)
nodeName = Property(str, lambda self: self.node.name, constant=True)
statusNodeName = Property(str, lambda self: self._status.nodeName, constant=True)
elapsedTime = Property(float, lambda self: self._status.elapsedTime, notify=statusChanged)
# simple structure for storing node position
Position = namedtuple("Position", ["x", "y"])
# initialize default coordinates values to 0
Position.__new__.__defaults__ = (0,) * len(Position._fields)
class BaseNode(BaseObject):
"""
Base Abstract class for Graph nodes.
"""
# Regexp handling complex attribute names with recursive understanding of Lists and Groups
# i.e: a.b, a[0], a[0].b.c[1]
attributeRE = re.compile(r'\.?(?P<name>\w+)(?:\[(?P<index>\d+)\])?')
def __init__(self, nodeType, position=None, parent=None, uids=None, **kwargs):
"""
Create a new Node instance based on the given node description.
Any other keyword argument will be used to initialize this node's attributes.
Args:
nodeDesc (desc.Node): the node description for this node
parent (BaseObject): this Node's parent
**kwargs: attributes values
"""
super(BaseNode, self).__init__(parent)
self._nodeType = nodeType
self.nodeDesc = None
# instantiate node description if nodeType is valid
if nodeType in meshroom.core.nodesDesc:
self.nodeDesc = meshroom.core.nodesDesc[nodeType]()
self.packageName = self.packageVersion = ""
self._internalFolder = ""
self._name = None
self.graph = None
self.dirty = True # whether this node's outputs must be re-evaluated on next Graph update
self._chunks = ListModel(parent=self)
self._uids = uids if uids else {}
self._cmdVars = {}
self._size = 0
self._position = position or Position()
self._attributes = DictModel(keyAttrName='name', parent=self)
self._internalAttributes = DictModel(keyAttrName='name', parent=self)
self.attributesPerUid = defaultdict(set)
self._alive = True # for QML side to know if the node can be used or is going to be deleted
self._locked = False
self._duplicates = ListModel(parent=self) # list of nodes with the same uid
self._hasDuplicates = False
self._forLoopData = ForLoopData()
self.globalStatusChanged.connect(self.updateDuplicatesStatusAndLocked)
def __getattr__(self, k):
try:
# Throws exception if not in prototype chain
return object.__getattribute__(self, k)
except AttributeError as e:
try:
return self.attribute(k)
except KeyError:
raise e
def getName(self):
return self._name
def getDefaultLabel(self):
return self.nameToLabel(self._name)
def getLabel(self):
"""
Returns:
str: the user-provided label if it exists, the high-level label of this node otherwise
"""
if self.hasInternalAttribute("label"):
label = self.internalAttribute("label").value.strip()
if label:
return label
return self.getDefaultLabel()
def getColor(self):
"""
Returns:
str: the user-provided custom color of the node if it exists, empty string otherwise
"""
if self.hasInternalAttribute("color"):
return self.internalAttribute("color").value.strip()
return ""
def getInvalidationMessage(self):
"""
Returns:
str: the invalidation message on the node if it exists, empty string otherwise
"""
if self.hasInternalAttribute("invalidation"):
return self.internalAttribute("invalidation").value
return ""
def getComment(self):
"""
Returns:
str: the comments on the node if they exist, empty string otherwise
"""
if self.hasInternalAttribute("comment"):
return self.internalAttribute("comment").value
return ""
@Slot(str, result=str)
def nameToLabel(self, name):
"""
Returns:
str: the high-level label from the technical node name
"""
t, idx = name.split("_")
return "{}{}".format(t, idx if int(idx) > 1 else "")
def getDocumentation(self):
if not self.nodeDesc:
return ""
return self.nodeDesc.documentation
@property
def packageFullName(self):
return '-'.join([self.packageName, self.packageVersion])
@Slot(str, result=Attribute)
def attribute(self, name):
att = None
# Complex name indicating group or list attribute
if '[' in name or '.' in name:
p = self.attributeRE.findall(name)
for n, idx in p:
# first step: get root attribute
if att is None:
att = self._attributes.get(n)
else:
# get child Attribute in Group
assert isinstance(att, GroupAttribute)
att = att.value.get(n)
if idx != '':
# get child Attribute in List
assert isinstance(att, ListAttribute)
att = att.value.at(int(idx))
else:
att = self._attributes.getr(name)
return att
@Slot(str, result=Attribute)
def internalAttribute(self, name):
# No group or list attributes for internal attributes
# The internal attribute itself can be returned directly
return self._internalAttributes.get(name)
def setInternalAttributeValues(self, values):
# initialize internal attribute values
for k, v in values.items():
attr = self.internalAttribute(k)
attr.value = v
def getAttributes(self):
return self._attributes
def getInternalAttributes(self):
return self._internalAttributes
@Slot(str, result=bool)
def hasAttribute(self, name):
# Complex name indicating group or list attribute: parse it and get the
# first output element to check for the attribute's existence
if "[" in name or "." in name:
p = self.attributeRE.findall(name)
return p[0][0] in self._attributes.keys() or p[0][1] in self._attributes.keys()
return name in self._attributes.keys()
@Slot(str, result=bool)
def hasInternalAttribute(self, name):
return name in self._internalAttributes.keys()
def _applyExpr(self):
for attr in self._attributes:
attr._applyExpr()
@property
def nodeType(self):
return self._nodeType
@property
def position(self):
""" Get node position. """
return self._position
@position.setter
def position(self, value):
""" Set node position.
Args:
value (Position): target position
"""
if self._position == value:
return
self._position = value
self.positionChanged.emit()
@property
def alive(self):
return self._alive
@alive.setter
def alive(self, value):
if self._alive == value:
return
self._alive = value
self.aliveChanged.emit()
@property
def depth(self):
return self.graph.getDepth(self)
@property
def minDepth(self):
return self.graph.getDepth(self, minimal=True)
@property
def valuesFile(self):
return os.path.join(self.graph.cacheDir, self.internalFolder, 'values')
def getInputNodes(self, recursive, dependenciesOnly):
return self.graph.getInputNodes(self, recursive=recursive, dependenciesOnly=dependenciesOnly)
def getOutputNodes(self, recursive, dependenciesOnly):
return self.graph.getOutputNodes(self, recursive=recursive, dependenciesOnly=dependenciesOnly)
def toDict(self):
pass
def _computeUids(self):
""" Compute node UIDs by combining associated attributes' UIDs. """
# Get all the attributes associated to a given UID index, specified in node descriptions with "uid=[index]"
# For now, the only index that is used is "0", so there will be a single iteration of the loop below
for uidIndex, associatedAttributes in self.attributesPerUid.items():
# UID is computed by hashing the sorted list of tuple (name, value) of all attributes impacting this UID
uidAttributes = []
for a in associatedAttributes:
if not a.enabled:
continue # disabled params do not contribute to the uid
dynamicOutputAttr = a.isLink and a.getLinkParam(recursive=True).desc.isDynamicValue
# For dynamic output attributes, the UID does not depend on the attribute value.
# In particular, when loading a project file, the UIDs are updated first,
# and the node status and the dynamic output values are not yet loaded,
# so we should not read the attribute value.
if not dynamicOutputAttr and a.value == a.uidIgnoreValue:
continue # for non-dynamic attributes, check if the value should be ignored
uidAttributes.append((a.getName(), a.uid(uidIndex)))
uidAttributes.sort()
# Adding the node type prevents ending up with two identical UIDs for different node types that have the exact same list of attributes
uidAttributes.append(self.nodeType)
self._uids[uidIndex] = hashValue(uidAttributes)
def _buildCmdVars(self):
def _buildAttributeCmdVars(cmdVars, name, attr):
if attr.enabled:
group = attr.attributeDesc.group(attr.node) if isinstance(attr.attributeDesc.group, types.FunctionType) else attr.attributeDesc.group
if group is not None:
# if there is a valid command line "group"
v = attr.getValueStr(withQuotes=True)
cmdVars[name] = '--{name} {value}'.format(name=name, value=v)
# xxValue is exposed without quotes to allow to compose expressions
cmdVars[name + 'Value'] = attr.getValueStr(withQuotes=False)
# List elements may give a fully empty string and will not be sent to the command line.
# String attributes will return only quotes if it is empty and thus will be send to the command line.
# But a List of string containing 1 element,
# and this element is an empty string will also return quotes and will be send to the command line.
if v:
cmdVars[group] = cmdVars.get(group, '') + ' ' + cmdVars[name]
elif isinstance(attr, GroupAttribute):
assert isinstance(attr.value, DictModel)
# if the GroupAttribute is not set in a single command line argument,
# the sub-attributes may need to be exposed individually
for v in attr._value:
_buildAttributeCmdVars(cmdVars, v.name, v)
""" Generate command variables using input attributes and resolved output attributes names and values. """
for uidIndex, value in self._uids.items():
self._cmdVars['uid{}'.format(uidIndex)] = value
# Evaluate input params
for name, attr in self._attributes.objects.items():
if attr.isOutput:
continue # skip outputs
_buildAttributeCmdVars(self._cmdVars, name, attr)
# For updating output attributes invalidation values
cmdVarsNoCache = self._cmdVars.copy()
cmdVarsNoCache['cache'] = ''
# Evaluate output params
for name, attr in self._attributes.objects.items():
if attr.isInput:
continue # skip inputs
# Apply expressions for File attributes
if attr.attributeDesc.isExpression:
defaultValue = ""
# Do not evaluate expression for disabled attributes (the expression may refer to other attributes that are not defined)
if attr.enabled:
try:
defaultValue = attr.defaultValue()
except AttributeError as e:
# If we load an old scene, the lambda associated to the 'value' could try to access other params that could not exist yet
logging.warning('Invalid lambda evaluation for "{nodeName}.{attrName}"'.format(nodeName=self.name, attrName=attr.name))
if defaultValue is not None:
try:
attr.value = defaultValue.format(**self._cmdVars)
attr._invalidationValue = defaultValue.format(**cmdVarsNoCache)
except KeyError as e:
logging.warning('Invalid expression with missing key on "{nodeName}.{attrName}" with value "{defaultValue}".\nError: {err}'.format(nodeName=self.name, attrName=attr.name, defaultValue=defaultValue, err=str(e)))
except ValueError as e:
logging.warning('Invalid expression value on "{nodeName}.{attrName}" with value "{defaultValue}".\nError: {err}'.format(nodeName=self.name, attrName=attr.name, defaultValue=defaultValue, err=str(e)))
v = attr.getValueStr(withQuotes=True)
self._cmdVars[name] = '--{name} {value}'.format(name=name, value=v)
# xxValue is exposed without quotes to allow to compose expressions
self._cmdVars[name + 'Value'] = attr.getValueStr(withQuotes=False)
if v:
self._cmdVars[attr.attributeDesc.group] = self._cmdVars.get(attr.attributeDesc.group, '') + \
' ' + self._cmdVars[name]
@property
def isParallelized(self):
return bool(self.nodeDesc.parallelization) if meshroom.useMultiChunks else False
@property
def nbParallelizationBlocks(self):
return len(self._chunks)
def hasStatus(self, status):
if not self._chunks:
return (status == Status.INPUT)
for chunk in self._chunks:
if chunk.status.status != status:
return False
return True
def _isComputed(self):
if not self.isComputable:
return True
return self.hasStatus(Status.SUCCESS)
def _isComputable(self):
return self.getGlobalStatus() != Status.INPUT
def clearData(self):
""" Delete this Node internal folder.
Status will be reset to Status.NONE
"""
if self.internalFolder and os.path.exists(self.internalFolder):
shutil.rmtree(self.internalFolder)
self.updateStatusFromCache()
@Slot(result=str)
def getStartDateTime(self):
""" Return the date (str) of the first running chunk """
dateTime = [chunk._status.startDateTime for chunk in self._chunks if chunk._status.status
not in (Status.NONE, Status.SUBMITTED) and chunk._status.startDateTime != ""]
return min(dateTime) if len(dateTime) != 0 else ""
def isAlreadySubmitted(self):
for chunk in self._chunks:
if chunk.isAlreadySubmitted():
return True
return False
def isAlreadySubmittedOrFinished(self):
for chunk in self._chunks:
if not chunk.isAlreadySubmittedOrFinished():
return False
return True
@Slot(result=bool)
def isSubmittedOrRunning(self):
""" Return True if all chunks are at least submitted and there is one running chunk, False otherwise. """
if not self.isAlreadySubmittedOrFinished():
return False
for chunk in self._chunks:
if chunk.isRunning():
return True
return False
@Slot(result=bool)
def isRunning(self):
""" Return True if at least one chunk of this Node is running, False otherwise. """
return any(chunk.isRunning() for chunk in self._chunks)
@Slot(result=bool)
def isFinishedOrRunning(self):
""" Return True if all chunks of this Node is either finished or running, False otherwise. """
return all(chunk.isFinishedOrRunning() for chunk in self._chunks)
@Slot(result=bool)
def isPartiallyFinished(self):
""" Return True is at least one chunk of this Node is finished, False otherwise. """
return any(chunk.isFinished() for chunk in self._chunks)
def alreadySubmittedChunks(self):
return [ch for ch in self._chunks if ch.isAlreadySubmitted()]
def isExtern(self):
""" Return True if at least one chunk of this Node has an external execution mode, False otherwise.
It is not enough to check whether the first chunk's execution mode is external, because computations
may have been started locally, interrupted, and restarted externally. In that case, if the first
chunk has completed locally before the computations were interrupted, its execution mode will always
be local, even if computations resume externally.
"""
return any(chunk.isExtern() for chunk in self._chunks)
@Slot()
def clearSubmittedChunks(self):
""" Reset all submitted chunks to Status.NONE. This method should be used to clear inconsistent status
if a computation failed without informing the graph.
Warnings:
This must be used with caution. This could lead to inconsistent node status
if the graph is still being computed.
"""
for chunk in self._chunks:
if chunk.isAlreadySubmitted():
chunk.upgradeStatusTo(Status.NONE, ExecMode.NONE)
def clearLocallySubmittedChunks(self):
""" Reset all locally submitted chunks to Status.NONE. """
for chunk in self._chunks:
if chunk.isAlreadySubmitted() and not chunk.isExtern():
chunk.upgradeStatusTo(Status.NONE, ExecMode.NONE)
def upgradeStatusTo(self, newStatus):
"""
Upgrade node to the given status and save it on disk.
"""
for chunk in self._chunks:
chunk.upgradeStatusTo(newStatus)
def updateStatisticsFromCache(self):
for chunk in self._chunks:
chunk.updateStatisticsFromCache()
def _updateChunks(self):
pass
def onAttributeChanged(self, attr):
""" When an attribute changed, a specific function can be defined in the descriptor and be called.
Args:
attr (Attribute): attribute that has changed
"""
# Call the specific function if it exists in the node implementation
paramName = attr.name[:1].upper() + attr.name[1:]
methodName = f'on{paramName}Changed'
if hasattr(self.nodeDesc, methodName):
m = getattr(self.nodeDesc, methodName)
if callable(m):
m(self)
if self.graph:
# If we are in a graph, propagate the notification to the connected output attributes
outEdges = self.graph.outEdges(attr)
for edge in outEdges:
edge.dst.onChanged()
def onAttributeClicked(self, attr):
""" When an attribute is clicked, a specific function can be defined in the descriptor and be called.