-
Notifications
You must be signed in to change notification settings - Fork 0
/
codeplans.py
1363 lines (1124 loc) · 46.5 KB
/
codeplans.py
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
from enum import IntEnum
from win32com import client
from openpyxl import load_workbook
from collections import defaultdict, namedtuple
from shutil import copyfile
from adodbapi import connect
from xml.etree import ElementTree
############################################################################
#
# CONSTANTS / ENUMERATIONS
#
############################################################################
CODE_PREFIX = 'CB_'
HELPER_FIELD = '.Coding'
class CodeplanNodeTypes(IntEnum):
Root = 0
Basic = 1
Parent = 2
class CFileSources(IntEnum):
Verbaco = 1
Ascribe = 2
class AxisSeparators(IntEnum):
Comma = 1
NetStart = 2
NetEnd = 3
class XLCodeplanRowTypes(IntEnum):
Invalid = 0
Regular = 1
Combine = 2
NetStart = 3
NetEnd = 4
class ObjectTypesConstants(IntEnum):
mtVariable = 0
mtArray = 1
mtGrid = 2
mtClass = 3
mtElement = 4
mtElements = 5
mtLabel = 6
mtField = 7
mtHelperFields = 8
mtFields = 9
mtTypes = 10
mtProperties = 11
mtRouting = 12
mtContexts = 13
mtLanguages = 14
mtLevelObject = 15
mtVariableInstance = 16
mtRoutingItem = 17
mtCompound = 18
mtElementInstance = 19
mtElementInstances = 20
mtLanguage = 21
mtRoutingItems = 22
mtRanges = 23
mtCategories = 24
mtCategoryMap = 25
mtDataSources = 26
mtDocument = 27
mtVersion = 29
mtVersions = 30
mtVariables = 31
mtDataSource = 32
mtAliasMap = 33
mtIndexElement = 34
mtIndicesElements = 35
mtPages = 36
mtParameters = 37
mtPage = 38
mtItems = 39
mtContext = 40
mtContextAlternatives = 41
mtElementList = 42
mtGoto = 43
mtTemplate = 44
mtTemplates = 45
mtStyle = 46
mtNote = 47
mtNotes = 48
mtIfBlock = 49
mtConditionalRouting = 50
mtDBElements = 51
mtDBQuestionDataProvider = 52
mtUnknown = 65535
class DataTypeConstants(IntEnum):
mtNone = 0
mtLong = 1
mtText = 2
mtCategorical = 3
mtObject = 4
mtDate = 5
mtDouble = 6
mtBoolean = 7
class ElementTypeConstants(IntEnum):
mtCategory = 0
mtAnalysisSubheading = 1
mtAnalysisBase = 2
mtAnalysisSubtotal = 3
mtAnalysisSummaryData = 4
mtAnalysisTotal = 6
mtAnalysisMean = 7
mtAnalysisStdDev = 8
mtAnalysisStdErr = 9
mtAnalysisSampleVariance = 10
mtAnalysisMinimum = 11
mtAnalysisMaximum = 12
mtAnalysisCategory = 14
class openConstants(IntEnum):
oREAD = 1
oREADWRITE = 2
oNOSAVE = 3
############################################################################
#
# CODEPLAN
#
############################################################################
class CodeplanNode:
def __init__(self, name='', label='', function='', properties='', parent=None, level=0):
self._name = name
self._label = label
self._function = function
self._properties = properties
self._parent = parent
self._level = level
self._axis = None
self._children = []
self._flat_children = None
@classmethod
def from_axis(cls, axis, parent=None, level=0):
node = CodeplanNode()
node._axis = axis
node._parent = parent
node._level = level
# sets label mask
in_label = False
quote_pending = False
label_mask = []
for c in axis:
if c == "'": # label starts or continues
in_label = True
quote_pending = not quote_pending
elif in_label and not quote_pending: #label ends
in_label = False
quote_pending = False
label_mask.append(in_label)
# sets level mask
level_mask = []
level = 1
for c, in_label in zip(axis, label_mask):
if c == ')' and not in_label:
level -= 1
level_mask.append(level)
if c == '(' and not in_label:
level += 1
# sets children mask
children_mask = []
nested_brackets = 0
for c in axis:
if c == '{':
nested_brackets += 1
children_mask.append(bool(nested_brackets))
if c == '}':
nested_brackets -= 1
# sets characters
AxisChar = namedtuple('AxisChar', 'idx char in_label in_children level')
characters = [
AxisChar(x[0], *x[1])
for x in enumerate(zip(axis, label_mask, children_mask, level_mask))
]
# sets children if they were found in children mask
node._children = []
if any(children_mask):
first = min(c.idx for c in characters if c.in_children) + 1
last = max(c.idx for c in characters if c.in_children)
current_idx = first
current_level = characters[first].level
for c in characters[first:last]:
if not c.in_label and c.level == current_level and c.char == ',' :
node._children.append(CodeplanNode.from_axis(
axis[current_idx:c.idx].strip(),
parent = node,
level = node.level + 1
))
current_idx = c.idx + 1
node._children.append(CodeplanNode.from_axis(
axis[current_idx:last].strip(),
parent = node,
level = node.level + 1
))
# sets body, name, label, function and properties
body = ''.join(c.char for c in characters if not c.in_children).strip()
node._label = ''.join(c.char for c in characters if not c.in_children and c.in_label)[1:-1].replace("''", "'").strip()
body_without_label = ''.join(c.char for c in characters if not c.in_children and not c.in_label).strip()
start_properties = body_without_label.find('[')
if start_properties >= 0:
node._properties = body_without_label[start_properties:]
body_without_label = body_without_label[:start_properties].strip()
else:
node._properties = ''
split_body = body_without_label.split(maxsplit=1)
if not body: # if there is no body
node._name = ''
node._function = ''
elif len(split_body) == 1 and '(' not in body_without_label: # single code
node._name = body_without_label
node._function = ''
elif len(split_body) == 1 and '(' in body_without_label: # single function
node._name = ''
node._function = body_without_label
elif len(split_body) == 2: # function
node._name = split_body[0].strip()
node._function = split_body[1].strip()
return node
@classmethod
def from_excel(cls, xl_rows):
root = CodeplanNode()
current_parent = root
for row in xl_rows:
if row.row_type == XLCodeplanRowTypes.NetStart:
node = CodeplanNode(
name=f'net{row.index}',
label=row.label,
function='net()',
parent=current_parent,
level=current_parent.level + 1)
current_parent.children.append(node)
current_parent = node
elif row.row_type == XLCodeplanRowTypes.NetEnd:
level_difference = current_parent.level - len(row.code) + 1
while level_difference:
current_parent = current_parent.parent
level_difference -= 1
elif row.row_type == XLCodeplanRowTypes.Regular:
node = CodeplanNode(
name=f'{CODE_PREFIX}{row.code}',
label=row.label,
parent=current_parent,
level=current_parent.level + 1)
current_parent.children.append(node)
elif row.row_type == XLCodeplanRowTypes.Combine:
combine_node = CodeplanNode(
name=f'comb{row.index}',
label=row.label,
function='combine()',
parent=current_parent,
level=current_parent.level + 1)
for c in row.combine_codes:
child = CodeplanNode(
name=f'{CODE_PREFIX}{c}',
parent=combine_node,
level=combine_node.level + 1)
combine_node.children.append(child)
current_parent.children.append(combine_node)
return root
@property
def axis(self):
if self._axis == None:
# building axis: name and label
escaped_label = self._label.replace("'", "''")
self._axis = f"{self._name} '{escaped_label}'" if self._label else self._name
# building axis: function and children
children = f'{{{",".join(c.axis for c in self._children)}}}' if self._children else ''
if self._function and self._children:
self._axis += f" {self._function[:-1]}{children}{self._function[-1]}"
elif self._function and not self._children:
self._axis += f" {self._function}"
elif not self._function and self._children:
self._axis += f" {children}"
# building axis: properties
self._axis += self.properties
return self._axis
@property
def xl_axis(self):
result = ''
if self.function == 'net()':
result = (f'{"*"*self.level}\t{self.label}\n'
+ ''.join(c.xl_axis for c in self.children)
+ ('#' * self.level)) + '\n'
elif self.function == 'combine()':
result = (','.join(c.name[len(CODE_PREFIX):] for c in self.children)
+ '\t' + self.label) + '\n'
elif self.function == '':
result = f'{self.name[len(CODE_PREFIX):]}\t{self.label}\n'
return result
def get_tom_axis(self, total_label='Sum'):
tom_node = CodeplanNode.from_axis(self.axis)
if tom_node.children[0].function != 'base()':
tom_node.children.insert(0, CodeplanNode.from_axis('base()'))
if tom_node.children[-1].function != 'total()':
tom_node.children.append(CodeplanNode.from_axis(f"sum '{total_label}' total()"))
tom_node._axis = None
return tom_node.axis
@property
def parent(self):
return self._parent
@property
def children(self):
return self._children
@property
def flat_children(self):
if self._flat_children == None:
# deep first traversal
self._flat_children = []
stack = [*self.children]
while stack:
current = stack[0]
stack = stack[1:]
self._flat_children.append(current)
for child in reversed(current.children):
stack.insert(0, child)
return self._flat_children
@property
def indented_children(self):
return [f'{" "*(node.level - 1)}{node.name} - {node.label}' for node in self.flat_children]
@property
def xl_children(self):
result = []
if not self.children:
return result
children_axis = ''.join(c.xl_axis for c in self.children).strip().split('\n')
last_line = ' '
for line in children_axis[::-1]:
if line[0] == last_line[0] == '#':
pass
else:
result.append(line)
last_line = line
return result[::-1]
@property
def level(self):
return self._level
@property
def name(self):
return self._name
@property
def label(self):
return self._label
@property
def function(self):
return self._function
@property
def properties(self):
return self._properties
def __repr__(self):
return f'CodeplanNode({self.name} - {self.label})'
class CodeplanElement:
def __init__(self, code, label, double=False):
self.code = code
self.label = label
self.double = double
def __gt__(self, other):
return sort_element(self.code) > sort_element(other.code)
def __repr__(self):
return f"CodeplanElement(code='{self.code}', label='{self.label}', double={self.double})"
############################################################################
#
# MDD CODEPLAN
#
############################################################################
class MDDFile:
def __init__(self, mdd_path, *, parser='xml'):
self.path = mdd_path
self.parser = parser
# reads meta data from mdd
if parser == 'xml':
self.types, self.variables = self._read_mdd_from_xml()
elif parser == 'com':
self.types, self.variables = self._read_mdd_from_com()
def _read_mdd_from_com(self):
# parser, which uses MDM.Document COM Object
# to access types and variables
# opens mdd
mdd = client.Dispatch('MDM.Document')
mdd.Open(self.path, mode=openConstants.oREAD)
# fills types
types = [
MDDCodeplan(
name=t.Name,
elements=[
CodeplanElement(code=e.Name, label=e.label)
for e in t.Elements
],
axis={f.AxisExpression
for f in mdd.Fields
if f.ObjectTypeValue == ObjectTypesConstants.mtVariable
and f.Elements.Reference.Name == t.Name
}.pop(),
mdd_file=self
) for t in mdd.Types]
# fills variables
variables = [
MDDVariable(
name=f.Name,
label=f.Label,
type_name=f.Elements.Reference.Name,
axis=f.AxisExpression
)
for f in mdd.Fields
if f.ObjectTypeValue == ObjectTypesConstants.mtVariable
]
# closes mdd
mdd.Close()
return types, variables
def _read_mdd_from_xml(self):
# parser, which uses XML from MDD file
# to access types and variables
types = []
variables = []
# root node for variables and types is xml\mdm:metadata\definition
tree = ElementTree.parse(self.path)
root = tree.getroot()[0].find('definition')
# root node contains elements of 2 types:
# 'variable' for variables
# 'categories' for types
for node in root:
# parsing logic for variables
if node.tag == 'variable':
name = node.get('name')
var_type = int(node.get('type'))
# labels element may contain multiple labels
# for different label types, contexts and languages (LCL)
# parser just uses 1st label it encounters
label = node.find('labels')[0].text
ref_name = node.find('categories').get('ref_name')
axis = node.find('axis').get('expression')
if var_type == DataTypeConstants.mtCategorical and ref_name:
variables.append(MDDVariable(name, label, ref_name, axis))
# parsing logic for types
elif node.tag == 'categories':
name = node.get('name')
elements = [
CodeplanElement(
code=element.get('name'),
label=element.find('labels')[0].text
)
for element in node
if element.tag == 'category'
]
# sets axis expression for type based on the 1st variable
# which belongs to this type
# assumes variables collection is completely populated
axis = {v.axis for v in variables if v.type_name == name}.pop()
types.append(MDDCodeplan(name, elements, axis, self))
return types, variables
@property
def variable_map(self):
# populates field list from variable list in 3 stages:
# - saves list of variables per field
# - saves list of types per field
# - merges both results in fields list
variables_per_field = defaultdict(list)
for v in self.variables:
variables_per_field[v.field_name].append(v)
types_per_field = defaultdict(set)
for v in self.variables:
types_per_field[v.field_name].add(v.type_name)
Field = namedtuple('Field', 'name variables types')
fields = [
Field(
name=k,
variables=v,
types=types_per_field[k]
)
for k, v in variables_per_field.items()
]
# checks if there are variables, which belong to the same field
# but use different types.
# creates variable map, for renaming such variables in cfile
return {
f'{v.label}{HELPER_FIELD}': v.compliant_name
for f in fields
for v in f.variables
if len(f.types) > 1
}
def save_variable_map(self, path):
with open(path, mode='w', encoding='utf-8') as f:
for vm in self.variable_map.items():
f.write(','.join(vm) + '\n')
def save_as(self, path):
self.path = path
# saves types and elements lists in mdd file
mdd = client.Dispatch('MDM.Document')
mdd.IncludeSystemVariables = False
for t in self.types:
new_list = mdd.CreateElements(t.name)
for element in t:
new_element = mdd.CreateElement(element.code, element.label)
new_element.Type = ElementTypeConstants.mtCategory
new_list.Add(new_element)
mdd.Types.Add(new_list)
for v in self.variables:
new_variable = mdd.CreateVariable(v.name, v.label)
new_variable.DataType = DataTypeConstants.mtCategorical
new_variable.Elements.ReferenceName = v.type_name
new_variable.AxisExpression = self[v.type_name].axis
mdd.Fields.Add(new_variable)
mdd.CategoryMap.AutoAssignValues()
mdd.Save(path)
mdd.Close()
def __getitem__(self, value):
if isinstance(value, str):
return [t for t in self.types if t.name == value][0]
else:
return self.types[value]
def __contains__(self, value):
return bool([t for t in self.types if t.name == value])
def __repr__(self):
return f"MDDFile(path='{self.path}')"
class MDDCodeplan:
def __init__(self, name, elements, axis, mdd_file):
self.name = name
self.mdd_file = mdd_file
self.elements = elements
self.axis = axis
self._errors = None
self._tree = None
self._is_valid = None
@property
def errors(self):
if self._errors is None:
self._errors = []
return self._errors
@property
def tree(self):
if self._tree is None:
self._tree = CodeplanNode.from_axis(self.axis)
return self._tree
@tree.setter
def tree(self, value):
self._tree = value
@property
def is_valid(self):
if self._is_valid is None:
self._is_valid = False if self.errors else True
return self._is_valid
@property
def net_elements(self):
return [n for n in self.tree.flat_children if n.function == 'net()']
@property
def variables(self):
return [v for v in self.mdd_file.variables if v.type_name == self.name]
def print_tree(self):
for node in self.tree.flat_children:
print(f'{" " * (node.level - 1)}{node.code} - {node.label}')
def print_summary(self):
error_string = '\n'.join(self.errors) if self.errors else '(not found)'
print(f'''Name: {self.name}\n# Codes: {len(self.elements)}\n# Nets: {len(self.net_elements)}\nErrors: {error_string}''')
def __len__(self):
return len(self.elements)
def __getitem__(self, i):
if isinstance(i, str):
return [e for e in self.elements if e.code == i][0]
else:
return self.elements[i]
def __repr__(self):
return f"MDDCodeplan(name='{self.name}'), len={len(self)}"
class MDDVariable:
def __init__(self, name, label, type_name, axis):
self.name = name
self.label = label
self.type_name = type_name
self.axis = axis
self._field_name = None
self._iterations = None
self._compliant_name = None
@property
def field_name(self):
'''f4l[{axa}].f4 -> f4l.f4'''
if self._field_name is None:
self._field_name = '.'.join(part.split(
'[')[0] for part in self.label.split('.'))
return self._field_name
@property
def iterations(self):
'''q7loop[{_12}].q7[_5].slice -> [_12, _5]'''
if self._iterations is None:
self._iterations = [part.split(
'[')[1][1:-2] for part in self.label.split('.') if len(part.split('[')) > 1]
return self._iterations
@property
def compliant_name(self):
'''f4l[{axa}].f4 -> f4l_f4_axa_o_c'''
if self._compliant_name is None:
prefix = '_'.join(self.field_name.split('.'))
suffix = '_'.join(self.iterations) + '_o_c'
self._compliant_name = f'{prefix}_{suffix}'
return self._compliant_name
def __repr__(self):
return f"MDDVariable(name='{self.name}'), label='{self.label}', type_name='{self.type_name}'"
############################################################################
#
# EXCEL CODEPLAN
#
############################################################################
class XLFile:
def __init__(self, path, *, code_column=1):
self.path = path
self.code_column = code_column
workbook = load_workbook(self.path, read_only=True, data_only=True)
self.codeplans = [
XLCodeplan(
name=sheet.title,
rows = [
XLCodeplanRow(
code=row[self.code_column - 1].value,
label=row[self.code_column].value,
index=index
)
for index, row in enumerate(sheet, start=1)],
xl_file = self)
for sheet in workbook
]
self.category_map = []
workbook.close()
def __getitem__(self, value):
if isinstance(value, str):
return [t for t in self.codeplans if t.name == value][0]
else:
return self.codeplans[value]
def __contains__(self, value):
return bool([t for t in self.codeplans if t.name == value])
def __repr__(self):
return f'XLFile(path="{self.path}")'
class XLCodeplan:
def __init__(self, name, rows, xl_file, *, other_element=''):
self.name =name
self.rows = self._trim_rows(rows)
self.other_element = other_element
self.xl_file = xl_file
self._elements = None
self._tree = None
self._errors = None
self._is_valid = None
def _trim_rows(self, rows):
first_valid_row = last_valid_row = 0
for row in rows:
if row.is_valid:
first_valid_row = row.index
break
if not first_valid_row:
return []
for row in reversed(rows):
if row.is_valid:
last_valid_row = row.index
break
return rows[first_valid_row - 1:last_valid_row]
@property
def elements(self):
if self._elements is None:
elements_with_label_list = defaultdict(list)
for row in self.rows:
if row.row_type == XLCodeplanRowTypes.Regular:
elements_with_label_list[row.code].append(row.label)
elif row.row_type == XLCodeplanRowTypes.Combine:
for c in row.combine_codes:
elements_with_label_list[c].append('')
self._elements = []
for code, labels in elements_with_label_list.items():
self._elements.append(
CodeplanElement(
code=f'{CODE_PREFIX}{code}',
label=max(labels),
double=True if len(labels) > 1 else False
)
)
self._elements.sort()
return self._elements
@property
def tree(self):
if self._tree is None:
self._tree = CodeplanNode.from_excel(self.rows)
return self._tree
@property
def axis(self):
return self.tree.axis
@property
def errors(self):
if self._errors is None:
self._errors = []
# Checks if codeplan is empty
if len(self.rows) == 0:
self._errors.append('Empty codeplan')
# Check if codes are valid
self._errors.extend([f'Invalid code "{row.code}" in row {row.index}'
for row in self.rows if not row.is_valid])
# Structural validation
current_level = 0
current_elements = []
last_row_type = XLCodeplanRowTypes.Invalid
for row in self.rows:
if row.row_type == XLCodeplanRowTypes.NetStart:
current_elements = []
if len(row.code) != current_level + 1:
self._errors.append(
f'Invalid * in row {row.index}({"*"*(current_level + 1)} expected)')
current_level = len(row.code)
elif row.row_type == XLCodeplanRowTypes.NetEnd:
if len(row.code) > current_level:
self._errors.append(
f'Invalid # in row {row.index}. (Less than {"#"*current_level} expected)')
if last_row_type == XLCodeplanRowTypes.NetStart:
self._errors.append(f'Empty net in row {row.index}')
current_level = len(row.code) - 1
elif row.row_type == XLCodeplanRowTypes.Combine:
if len(row.combine_codes) != len(set(row.combine_codes)):
self._errors.append(
f'Duplicate codes found in row {row.index}')
elif row.row_type == XLCodeplanRowTypes.Regular:
if row.code in current_elements:
self._errors.append(
f'Duplicate codes found in row {row.index}')
else:
current_elements.append(row.code)
last_row_type = row.row_type
return self._errors
@property
def is_valid(self):
if self._is_valid is None:
self._is_valid = False if self.errors else True
return self._is_valid
@property
def double_elements(self):
seen = set()
duplicates = set()
for node in self.tree.flat_children:
if node.code not in seen:
seen.add(node.code)
else:
duplicates.add(node.code)
return sorted(duplicates, key=lambda x: int(x[len(CODE_PREFIX):]))
@property
def net_elements(self):
return [n for n in self.tree.flat_children if n.node_type == CodeplanNodeTypes.Net]
@property
def combine_elements(self):
return [n for n in self.tree.flat_children if n.node_type == CodeplanNodeTypes.Combine]
def print_summary(self):
error_string = '\n'.join(self.errors) if self.errors else '(not found)'
double_elements = self.double_elements
double_elements_string = ','.join(double_elements) if double_elements else '(not found)'
print(f'''Name: {self.name}\n# Codes: {len(self.elements)}\n# Nets: {len(self.net_elements)}\n# Combines: {len(self.combine_elements)}\nDouble codes: {double_elements_string}\nErrors: {error_string}''')
def __len__(self):
return len(self.elements)
def __getitem__(self, i):
if isinstance(i, str):
return [e for e in self.elements if e.code == i][0]
else:
return self.elements[i]
def __repr__(self):
return f"XLCodeplan(name='{self.name}'), len={len(self)}"
class XLCodeplanRow:
def __init__(self, code, label, index):
self.code = str(code).strip() if code is not None else ''
self.label = str(label).strip() if label is not None else ''
self.index = index
self._row_type = None
self._combine_codes = None
self._is_valid = None
@property
def row_type(self):
if self._row_type is None:
# regular/numeric rows
if self.code.isdigit():
self._row_type = XLCodeplanRowTypes.Regular
# start (*) and end tags (#) for net()
elif self.code and self.code in '*******':
self._row_type = XLCodeplanRowTypes.NetStart
elif self.code and self.code in '#######':
self._row_type = XLCodeplanRowTypes.NetEnd
# floats (23.35) for combine()
elif '.' in self.code and self.code.replace('.', '', 1).isdigit():
self._row_type = XLCodeplanRowTypes.Combine
# "142, 43, 5" pattern for combine()
elif ',' in self.code and len(self.code.split(',')) == len(
[c.strip() for c in self.code.split(',') if c.strip().isdigit()]):
self._row_type = XLCodeplanRowTypes.Combine
else:
self._row_type = XLCodeplanRowTypes.Invalid
return self._row_type
@property
def combine_codes(self):
if self._combine_codes is None:
if self.row_type != XLCodeplanRowTypes.Combine:
self._combine_codes = []
elif '.' in self.code and self.code.replace('.', '', 1).isdigit():
self._combine_codes = self.code.split('.')
elif ',' in self.code:
self._combine_codes = [
c.strip() for c in self.code.split(',') if c.strip().isdigit()]
return self._combine_codes
@property
def is_valid(self):
if self._is_valid is None:
self._is_valid = bool(self.row_type)
return self._is_valid
def __repr__(self):
return f"XLCodeplanRow(code='{self.code}', label='{self.label}', index={self.index})"
############################################################################
#
# MERGERS
#
############################################################################
class MDDXLFileMerger:
def __init__(self, mdd_file, xl_file, mdd_xl_map, *, verbose = False):
# mdd_xl_map is named_tuple with 3 fields:
# mdd_name xl_name other_element
self.mdd_file = mdd_file
self.xl_file = xl_file
self.mdd_xl_map = mdd_xl_map
self.codeplan_mergers = []
if verbose:
print('Initializing MDDXLFileMerger...')
mdd_codeplans_missing_in_map = {t.name for t in self.mdd_file.types if t.name not in {m.mdd_name for m in self.mdd_xl_map}}
print('MDD types missing in the map:')
print(','.join(mdd_codeplans_missing_in_map))
xl_codeplans_missing_in_map = {cp.name for cp in self.xl_file.codeplans if cp.name not in {m.xl_name for m in self.mdd_xl_map}}
print('XL types missing in the map:')
print(','.join(xl_codeplans_missing_in_map))
for m in mdd_xl_map:
if m.mdd_name and m.xl_name and m.mdd_name in mdd_file and m.xl_name in xl_file:
mdd_codeplan = mdd_file[m.mdd_name]
xl_codeplan = xl_file[m.xl_name]
xl_codeplan.other_element = m.other_element
self.codeplan_mergers.append(
CodeplanMerger(mdd_codeplan, xl_codeplan, self)
)
self.category_map = []
def merge_all(self):
adjusted_types = []
for m in self.codeplan_mergers:
adjusted_types.append(m.merge())
self.category_map.extend(m.category_map)