-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.py
More file actions
1649 lines (1372 loc) · 55.9 KB
/
Copy pathparser.py
File metadata and controls
1649 lines (1372 loc) · 55.9 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
from copy import deepcopy
import re
import os
from enum import Enum
from io import StringIO
import numpy as np
import pandas as pd
import sys
from collections import OrderedDict
import itertools, operator
MISSING_READER_ALERT = [None]
LOG_LEVEL = 1
REGEX_ENABLER_PREFIX = "ø"
# TODO:
# x allow semantic tree to be converted to simple block e.g. ([Controls, Material > User Material] etc.
# - Support comments
# - extend parameteriation
# - behaviour for joining line ending in comma with nextline
# - Root header
# Done:
# - remove children and keep linenumbering intact
def isnotebook():
try:
shell = get_ipython().__class__.__name__
if shell == 'ZMQInteractiveShell':
return True # Jupyter notebook or qtconsole
elif shell == 'TerminalInteractiveShell' or shell == 'SpyderShell':
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False # Probably standard Python interpreter
codedir = None
if (isnotebook()):
codedir = os.path.dirname(os.path.abspath(''))
else:
codedir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(codedir)
import annotations
class ReaderExitCode(Enum):
CONTINUE = 0
DONE = 1
REJECT = 2
ERROR = 3
ERROR_NO_EOL_COMMA_ALLOWED = 4 # TODO
def infernumber(s, explicit=False):
"""
Try to cast a string to a number (float/int)
Parameters
----------
s : string
string to be be cast to number
explicit : boolean, optional
DESCRIPTION. The default is False.
Returns
-------
float, int, or string
Number best representing the string,
or string if it cannot be cast.
"""
try:
a = float(s)
if (explicit and "." in s):
# keep float if declared as float
return a
# downcast to int if no information is lost
return int(a) if (a == int(a)) else a
except ValueError:
return s
def findblockbyname(stck, name, regex = False):
"""
Find INode by its name
Parameters
----------
stck : list of INodes (or parent INode)
...
name : string
name of desired INode. The default is None.
regex : boolean, optional
Use regex. The default is False.
Yields
------
i : INode
INode with matching name.
"""
if isinstance(stck, INode):
stck = stck.getchildren()
for i in stck:
if isinstance(i, INode) and (i.name == name if not regex else re.match(i.name, name)):
yield i
def parseheader(line):
"""
Parse name and proprties from header line
e.g.
*Soils, consolidation, end=PERIOD, utol=5.
becomes:
name = Soils,
properties = {
"consolidation": None,
"end": "PERIOD",
"utol": 5
}
Parameters
----------
line : string
line to be parsed.
Returns
-------
name : string
name of header.
properties : OrderedDict
properties listed in header.
"""
segments = line.split(",")
name = segments[0]
name = name.lstrip("* ")
properties = OrderedDict()
for i in segments[1:]:
if ("=" in i):
k, v = i.split("=")
v = v.strip()
properties[k.strip()] = infernumber(v)
else:
properties[i.strip()] = None
return name, properties
def matchdict2str(dic, attrs, regex = True):
"""
Match a dictionary to a template string
e.g.
"consolidation,end=PERIOD"
"consolidation,end=P.*" (with regex)
"consolidation,1=PERIOD"
all match:
{
"consolidation": None,
"end": "PERIOD",
"utol": 5
}
Parameters
----------
dic : dict
..
attr : string
template string used as matcher, with comma seperated attributes.
regex : boolean, optional
Use regex. The default is True.
Returns
-------
bool
True if matches.
"""
for kv in attrs.split(","):
if "=" in kv:
k, v = kv.split("=")
chead_val = None
if k in dic.keys():
chead_val = dic[k]
elif (isinstance(dic, OrderedDict) and k.isnumeric()):
chead_val = list(dic.values())[int(k)]
else:
return False
if (chead_val is not None):
if (not isinstance(chead_val, str)):
if (chead_val != infernumber(v)):
return False
else:
regexlocal = regex
if (v.startswith(REGEX_ENABLER_PREFIX)):
v = v.lstrip(REGEX_ENABLER_PREFIX)
regexlocal = True
if (regexlocal):
if (re.search(v, chead_val) == None):
return False
elif (v != chead_val):
return False
elif (kv not in dic.keys()):
return False
return True
def matchcontent(content, match, regex = True):
if (isinstance(content, BlockReaderBase)):
content = content.getcontent()
if regex:
for i in content:
if (isinstance(i, str)):
if (re.search(match, i) != None):
return True
else:
for i in content:
if (isinstance(i, str)):
if (i == match):
return True
return False
class ParameterizedLine(object):
def __init__(self, line, name):
"""
Line with comma seperated properties, stored as a name and OrderedDict
Parameters
----------
line : string
Original line.
name : string
Name of the line.
"""
self.name = name
self.line = line
self.properties = OrderedDict()
@classmethod
def fromheader(cls, line):
"""
Create instance from a header line (.inp file)
e.g.
*Step, name = Step-1, nlgeom=YES, amplitude=RAMP, inc=1000
Parameters
----------
cls : TYPE
DESCRIPTION.
line : string
The line.
Returns
-------
paraml : ParameterizedLine
Instance.
"""
prs = parseheader(line)
paraml = cls(line, prs[0])
paraml.properties = prs[1]
return paraml
def getline(self):
return self.line
def getproperty(self, key):
return self.properties[key]
def __str__(self):
return "{:s} {:s}".format(
self.name,
"{"+", ".join([str(k)+": "+str(v) for k,v in self.properties.items()]) + "}"
)
def __repr__(self):
return self.getline()
class INode(object):
"""
INode object, has a header and can store content in order.
Content can include other INode objects, therefore it offers
an interface to create and utilize an object Tree.
"""
def __init__(self, name, parent = None):
"""
Parameters
----------
name : string
name of the node.
parent : INode, optional
Parent node. The default is None.
"""
self.name = name
self.content = []
self._parent = parent
self.header = None
def findchildrenbyname(self, name, regex=False):
# TODO: debug should be yield?
yield from findblockbyname(self.getcontent(), name, regex)
def getheader(self):
return self.header
def getcontent(self):
return self.content
def getchildren(self):
for line in self.getcontent():
if isinstance(line, INode):
yield line
def getparent(self):
return self._parent
def hasparent(self):
return self.getparent() != None
def getroot(self):
if (self.hasparent()):
return list(self.upstreamhierarchy())[-1]
else:
return self
def upstreamhierarchy(self):
"""
Stream parents untill root is reached
Yields
------
_p : INode
parent.
"""
_p = self.getparent()
while _p != None:
yield _p
_p = _p.getparent()
def _setparent(self, parent):
self._parent = parent
return self
def getname(self,):
"""
Return name
Returns
------
string
name
"""
return self.name
def getid(self,):
"""
Return a more unique short name
Returns
------
string
id
"""
return self.name
def flattencontent(self):
"""
Yield all content and children (and their children recursively)
Yields
------
INode, string or any other dtype
Child (content).
"""
if (isinstance(self.getheader(), str)):
yield self.getheader()
else:
yield repr(self.getheader())
for i in self.getcontent():
if isinstance(i, INode):
yield from i.flattencontent()
else:
yield i
def flatten(self,):
"""
Flatten all children (and their children recursively)
Yields
------
INode, string or any other dtype
Child (content).
"""
for i in self.getchildren():
yield i
yield from i.flatten()
def query(self, query, regex = False):
"""
Query the INode tree
Attributes (in the header):
parent[key=value] # test for value (allows regexs)
# regex can be enabled per value if first character of value is REGEX_ENABLER_PREFIX
parent[key] # test for presence
Content:
parent(content) # match parent if content matches
# regex can be enabled if first character is REGEX_ENABLER_PREFIX
Keyords:
> : child selector
| : match multiple nodes
* : match all children
** : match all children and their children and so on
.. : move to parent
root : move to root
Example, query solid section:
Root
*Part {name: PART-1}
*| └-Section: Section-11-F1 {}
*| | └-Solid Section {elset: F1, material: FACETS}
*| └-Section: Section-12-F2 {}
*| | └-Solid Section {elset: F2, material: FACETS}
*| └-Section: Section-13-F3 {}
*| ...
Query:
Part > Section > Solid Section[elset=F\d]
Or:
Part > Section > Solid Section[0=F\d]
Yields
------
INode
Queried child
"""
if ">" in query:
parentname, childname = query.split(">", 1)
for parent in self.query(parentname.strip(), regex = regex):
yield from parent.query(childname.strip(), regex = regex)
elif "|" in query:
# match multiple children
for term in query.split("|"):
yield from self.query(term.strip(), regex = regex)
elif "[" in query:
# filter for attributes
name = query[:query.find("[")] + query[query.find("]")+1:]
attr = query[query.find("[")+1:query.find("]")]
yield from filter(lambda x: matchdict2str(x.getheader().properties, attr, regex = regex), self.query(name, regex = regex))
elif "(" in query:
# match content
name = query[:query.find("(")] + query[query.find(")")+1:]
match = query[query.find("(")+1:query.find(")")]
regexlocal = regex
if (match.startswith(REGEX_ENABLER_PREFIX)):
match = match.lstrip(REGEX_ENABLER_PREFIX)
regexlocal = True
yield from filter(lambda x: matchcontent(x, match, regex = regexlocal), self.query(name, regex = regex))
elif (query.strip() == "*"):
# match all children
yield from self.getchildren()
elif (query.strip() == "**"):
# match all children and their children (flatten)
yield from self.flatten()
elif (query.strip() == ".."):
# move to parent
yield self.getparent()
elif (query.strip() == "root"):
# move to root
yield self.getroot()
else:
# return child
yield from self.findchildrenbyname(query, regex = regex)
def printchildren(self, out = print, level = 0):
"""
Print this node and its childrend as a Tree
Parameters
----------
level : int, optional
level to start. The default is 0.
Returns
-------
None.
"""
prefix = ""
if level == 0:
pass
elif level == 1:
prefix = "*"
else:
prefix = "*" + "| "*(level-1)+"└-"
trimspacer = True
formatplain = not trimspacer
selfstr = str(self)
if (trimspacer and len(selfstr) > 10):
reps = [selfstr[i] == selfstr[i+1] for i in range(len(selfstr)-1)]
# find longest space (repeating characters)
if (True in reps):
seq = max((list(y) for (x,y) in itertools.groupby((enumerate(reps)),operator.itemgetter(1)) if x == True), key=len)
size = seq[-1][0] - seq[0][0]
rem = min(len(prefix), size-1)
out(prefix + selfstr[:seq[0][0]] + selfstr[seq[0][0]+rem:])
else:
formatplain = True
else:
formatplain = True
if (formatplain):
out(prefix + selfstr)
for i in self.getchildren():
i.printchildren(out=out, level=level+1)
def printparents(self, out = print):
parents = [self] + list(self.upstreamhierarchy())
for i, par in enumerate(parents[::-1]):
if (par != None):
if (i == 0):
out(str(par))
elif (i == 1):
out("*" + str(par))
else:
out("*" + "| "*(i-1)+"└-" + str(par))
def __len__(self):
size = 0 if self.getheader() == None else 1
for _x in self.getcontent():
if isinstance(_x, str):
size += 1
else:
size += len(_x)
return size
def __str__(self):
if (self.getheader() is not None):
return "{:<120s} lines {:s}".format(str(self.getheader()).rstrip("\n"),
str(self.getlinenumberrange()))
else:
return "{:<120s} ({:s})".format(self.getname(), "MOCK")
def __repr__(self):
strarr = []
content = [self.getheader()] + self.getcontent() if self.getheader() != None else self.getcontent()
for _x in content:
if isinstance(_x, str):
strarr += [_x.rstrip("\n")]
else:
strarr += [repr(_x)]
return "\n".join(strarr)
""""
class IBlockReader(object):
def __init__(self):
self._isreading = False
self.startlinenumber = None
def matchheader(line):
return False
def startreading(self, startlinenumber = 0):
self._isreading = True
self.startlinenumber = startlinenumber
def read(self, line, nextreader = None):
return ReaderExitCode.ERROR
def stopreading(self):
self._isreading = False
def isreading(self):
return self._isreading
def getheader(self):
return self.header
def getstartlinenumber(self):
return self.getstartlinenumber
"""
class BlockReaderBase(INode):
"""
An implementation of INode offering the reading of lines of text and
store them as other BlockReaderBase instances (functional block) or as
a string.
Specifically designed for Abaqus .inp files
"""
def __init__(self, name, parent = None,
acceptchildren = True, acceptunimplementedchildren = True,
childreaderresolver = None):
"""
"""
super().__init__(name, parent)
self.childreaderresolver = childreaderresolver
self.startlinenumber = None # starting line of this block corresponding to line in file
self._nlines = 0 # counter for the amount of lines read
self._isreading = False # current state
self._activechildreader = None # active child reader to which lines are delegated
# Behaviour
self.acceptchildren = acceptchildren # accept childreader
self.acceptunimplementedchildren = acceptunimplementedchildren # accept functional block, without corresponding childreader (as text)
self.preferchildoversibling = True # if true and both a next horizontalreader and a next child reader present
# choose the childreader
self.takesiblingpreference = True # useful when same reader can both occur as a child or sibling
#self.allowcommaEOL = True # TODO
self.stripEOL = True
def matchheader(self, line):
"""
Looks at the header of the next coming functiona block and
returns true if this class can handle that block
Parameters
----------
line : string
A line of text (which is a potential header of an upcoming functional block)
Returns
-------
boolean
True if this class can handle the upcoming functional block
"""
return False
def startreading(self, startlinenumber = -1):
"""
Prepare the reader for reading
Parameters
----------
startlinenumber : int
Where in the file this line can be found
Returns
-------
None
"""
if (len(self.getcontent()) > 0):
raise ValueError("[{:^20s}] Cannot start reading when block has pre-existing content".format(self.getid()))
self._isreading = True
self.startlinenumber = startlinenumber
self.content = []
def read(self, line, nextsiblingeader = None):
"""
Read the line (or header) which is part of this functional block
Parameters
----------
line : string
A line of text
nextchildreader : BlockReaderBase
Another reader (sibling relationship) which also matches the line of text as a header
and can thus potentially take-over parsing
Returns
-------
enum ReaderExitCode
CONTINUE - ready for parsing next line of text
DONE - finished parsing this functional block
REJECT - finished parsing this functional block and the current line
is not a part of it
"""
if not self.isreading():
raise ValueError("[{:^20s}] Start reader first".format(self.getid()))
if self.stripEOL:
line = line.rstrip("\n")
if LOG_LEVEL >= 2:
print("[{:^20s}] received line ({:d}): \"{:s}\" and nextsiblingeader: {:s}".format(self.getid(), self.getendlinenumber(), line, str(nextsiblingeader)))
if self.getheader() is None:
self.header = self.parameterizeheader(line)
if LOG_LEVEL >= 2:
print("[{:^20s}] set header".format(self.getid()))
else:
if self.doterminate(line, nextsiblingeader):
if LOG_LEVEL >= 2:
print("[{:^20s}] terminated".format(self.getid()))
self.stopreading()
return ReaderExitCode.REJECT
nextchildreader = None
# Child reader
if (self.isfunctionalblock(line)):
nextchildreader = self._resolvechildreader(line)
# No active child reader yet
if (not self._hasactivechildreader()):
if (nextchildreader is not None):
self._activatechildreader(nextchildreader)
if (not self._hasactivechildreader()):
# Read normal line (or property)
self.getcontent().append(self.parameterize(line))
if LOG_LEVEL >= 2:
print("[{:^20s}] appended content".format(self.getid()))
else:
# Delegate to child reader
rsp = self._activechildreader.read(line, nextchildreader)
if (rsp in [ReaderExitCode.DONE, ReaderExitCode.REJECT]):
self._stopactivechildreader()
if (rsp == ReaderExitCode.REJECT):
if (nextchildreader is not None):
# This block can be ommited
self._activatechildreader(nextchildreader)
if LOG_LEVEL >= 2:
print("[{:^20s}] redo".format(self.getid()))
return self.read(line, nextsiblingeader)
self._nlines += 1
return ReaderExitCode.CONTINUE
def _resolvechildreader(self, line):
if (self.acceptchildren and self.getchildreaderresolver() is not None):
return deepcopy(self.getchildreaderresolver()(line))
else:
return None
def _stopactivechildreader(self):
self._activechildreader.stopreading()
self.getcontent().append(self._activechildreader)
self._activechildreader = None
def _activatechildreader(self, nextchildreader):
self._activechildreader = nextchildreader
self._activechildreader.startreading(self.getendlinenumber())
self._activechildreader._setparent(self)
def _hasactivechildreader(self):
"""
Returns
-------
boolean
True if a childreader is active
"""
return self._activechildreader is not None
def iscomment(self, line):
return line.lstrip().startswith("**")
def isfunctionalblock(self, line):
"""
Looks at the header of the next coming functiona block and
returns true if this class can handle that block
Parameters
----------
line : string
A line of text (which is a potential header of an upcoming functional block)
Returns
-------
boolean
True if this class can handle the upcoming functional block
"""
# TODO: should exclude comments (**) as soon as they are supported
return line.lstrip().startswith("*")
def stopreading(self):
"""
Stop the reader
Parameters
----------
line : string
A line of text (which is a potential header of an upcoming functional block)
Returns
-------
boolean
True if this class can handle the upcoming functional block
"""
if (self._activechildreader != None):
self._stopactivechildreader()
self._isreading = False
def doterminate(self, line, nextsiblingeader):
"""
Determine if this reader can handle the line,
or whether a potential next reader should take-over
Parameters
----------
line : string
A line of text (which is a potential header of an upcoming functional block)
nextreader: BlockReaderBase
Another reader on the same level (sibling), which wants to take-over parsing
Returns
-------
boolean
True if this reader should stop
"""
hasnextchildreader = self._resolvechildreader(line) is not None
if (nextsiblingeader is not None):
if (self.isfunctionalblock(line)):
# Dismiss next reader if a child can handle it
if (hasnextchildreader):
# refuse next sibling reader if:
# 1. current reader insists on preference for childreader over siblingreader
# 2. next siblingreader does not want preference
if (self.preferchildoversibling \
or not nextsiblingeader.takesiblingpreference):
return False
# next block
return True
elif (hasnextchildreader):
return False
else:
if (self.iscomment(line)):
return False
elif (self.isfunctionalblock(line)):
# child block without corresponding reader class
# Notify missing behaviour
self.__notifymissingreader(line)
return not self.acceptunimplementedchildren
return False
def isreading(self):
"""
Returns
-------
boolean
True if this reader is currently reading
"""
return self._isreading
def setchildreaderresolver(self, prop):
self.childreaderresolver = prop
return self
def getchildreaderresolver(self):
"""
Get the childreader resolver.
Returns
-------
lambda
A function taking a string as argument (line)
and returning an BlockReaderBase or None
"""
return self.childreaderresolver
def getstartlinenumber(self):
"""
Returns
-------
int
corresponding to linenumber where this functional block starts in the file
"""
if (self.startlinenumber == None):
raise ValueError("Start line number was never defined")
return self.startlinenumber
def getlinenumberrange(self):
"""
Returns
-------
tuple : (int, int)
(startlinenumber, endlinenumber)
"""
return (self.getstartlinenumber(), self.getendlinenumber() - 1)
def getendlinenumber(self):
"""
Returns
-------
int
endlinenumber
"""
return self.getstartlinenumber() + len(self)
def parameterizeheader(self, line):
"""
Option to perameterize a header into an object
e.g.
*Element type=S4R
becomes:
{
"type": "S4R",
}
"""
return ParameterizedLine.fromheader(line)
def parameterize(self, line):
"""
Option to perameterize a property of a block into an object
e.g.
0.1, 60, 0.0001, 60
becomes:
{
"initial": 0.1,
"period": 60,
"min": 0.0001,
"max": 60
}
"""
return line
def numberedflattencontent(self):
"""
TODO:
- test synergy with *INCLUDE (maybe get startlinenumber of block itself?)
Yields
-------
tuple : (int, string)
(linenumber, content)
"""
i = 0
for l in self.flattencontent():
yield (self.getstartlinenumber()+ i, l)
i += 1
def updatestartlinenumber(self, number):
"""
When content is removed, update the linenumbers (of this block and its children)
to be continuous again
Parameters
----------
number : int
New Start line number
nextreader: BlockReaderBase
Another reader on the same level (sibling), which wants to take-over parsing
Returns
-------
boolean
True if this reader should stop
"""
self.startlinenumber = number
children = {i.getheader().line: i for i in self.getchildren()}
for n, l in self.numberedflattencontent():
if (l in children.keys()):
children[l].updatestartlinenumber(n)
def __notifymissingreader(self, line):
if (line.lstrip().startswith("**")):
pass
elif(self.isfunctionalblock(line)):
readername = line.lstrip(" * ")
if ("," in readername):
readername = readername.split(",", 1)[0]
global MISSING_READER_ALERT
parentstr = [i.getname() for i in self.upstreamhierarchy()][::-1]
parentstr = " > ".join(parentstr + [self.getname(), readername])
if (parentstr.lower() not in MISSING_READER_ALERT):
MISSING_READER_ALERT += [parentstr.lower()]
print("NOTE: No explicit reader class defined for {:<40s} at line {:d}".format(parentstr, self.getendlinenumber()))
def __len__(self):
if (self.isreading() and self._activechildreader != None):
return super().__len__() + len(self._activechildreader)
else:
return super().__len__()