/
walker.py
1603 lines (1272 loc) · 50.8 KB
/
walker.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
"""
# Walker
You can convert a dataset to TF by writing a function that walks through it.
That function must trigger a sequence of actions when reading the data.
These actions drive Text-Fabric to build a valid Text-Fabric dataset.
Many checks will be performed.
!!! hint "to and from MQL"
If your source is MQL, you are even better off: Text-Fabric has a
module to import from MQL and to export to MQL.
See `tf.fabric.Fabric.importMQL` and `tf.fabric.Fabric.exportMQL`.
## Set up
Here is a schematic set up of such a conversion program.
```python
from tf.fabric import Fabric
from tf.convert.walker import CV
TF = Fabric(locations=OUT_DIR)
cv = CV(TF)
def director(cv):
# your code to unwrap your source data and trigger
# the generation of TF nodes, edges and features
slotType = 'word' # or whatever you choose
otext = { # dictionary of config data for sections and text formats
...
}
generic = { # dictionary of metadata meant for all features
...
}
intFeatures = { # set of integer valued feature names
...
}
featureMeta = { # per feature dicts with metadata
...
}
good = cv.walk(
director,
slotType,
otext=otext,
generic=generic,
intFeatures=intFeatures,
featureMeta=featureMeta,
warn=True,
force=False,
silent=False,
)
if good:
... load the new TF data ...
```
See `tf.convert.walker.CV.walk`.
## Walking
When you walk through the input data source, you'll encounter things
that have to become slots, non-slot nodes, edges and features in the new data set.
You issue these things by means of an *action method* from `cv`, such as
`cv.slot()` or `cv.node(nodeType)`.
When your action creates slots or non slot nodes,
Text-Fabric will return you a reference to that node,
that you can use later for more actions related to that node.
```python
curPara = cv.node('para')
```
To add features to nodes, use a `cv.feature()` action.
It will apply to a node passed as argument.
To add features to edges, issue a `cv.edge()` action.
It will require two node arguments: the *from* node and the *to* node.
There is always a set of current *embedder nodes*.
When you create a slot node
```python
curWord = cv.slot()
```
then TF will link all current embedder nodes to the resulting slot.
There are actions to add nodes to the set of embedder nodes,
to remove them from it,
and to add them again.
## Dynamic Metadata
When the director runs, you have already specified all your feature
metadata, including the value types.
But if some of that information is dependent on what you encounter in the
data, you can do two things:
(A) Run a preliminary pass over the data and gather the required information,
before running the director.
(B) Update the metadata later on
by issuing `cv.meta()` actions from within your director, see below.
## Action methods
The `cv` class contains methods that are responsible for particular *actions*
that steer the graph building:
* `tf.convert.walker.CV.slot`
* `tf.convert.walker.CV.node`
* `tf.convert.walker.CV.terminate`
* `tf.convert.walker.CV.resume`
* `tf.convert.walker.CV.link`
* `tf.convert.walker.CV.linked`
* `tf.convert.walker.CV.feature`
* `tf.convert.walker.CV.edge`
* `tf.convert.walker.CV.meta`
* `tf.convert.walker.CV.occurs`
* `tf.convert.walker.CV.active`
* `tf.convert.walker.CV.activeNodes`
* `tf.convert.walker.CV.activeTypes`
* `tf.convert.walker.CV.get` and `cv.get(feature, nf, nt)`
* `tf.convert.walker.CV.stop`
!!! hint "Example"
Follow the
[conversion tutorial](https://nbviewer.jupyter.org/github/annotation/banks/blob/master/programs/convert.ipynb)
Or study a more involved example:
[Old Babylonian](https://github.com/Nino-cunei/oldbabylonian/blob/master/programs/tfFromATF.py)
"""
import collections
import functools
import re
from ..parameters import WARP, OTYPE, OSLOTS, OTEXT
from ..core.helpers import itemize, isInt
class CV(object):
S = "slot"
N = "node"
T = "terminate"
R = "resume"
F = "feature"
E = "edge"
def __init__(self, TF, silent=False):
self.TF = TF
tmObj = TF.tmObj
isSilent = tmObj.isSilent
setSilent = tmObj.setSilent
self.wasSilent = isSilent()
setSilent(silent)
def _showWarnings(self):
tmObj = self.TF.tmObj
error = tmObj.error
info = tmObj.info
indent = tmObj.indent
warnings = self.warnings
warn = self.warn
if warn is None:
if warnings:
info("use `cv.walk(..., warn=False)` to make warnings visible")
info("use `cv.walk(..., warn=True)` to stop on warnings")
else:
method = error if warn else info
if warnings:
for (kind, msgs) in sorted(warnings.items()):
method(f"WARNING {kind} ({len(msgs)} x):")
indent(level=2)
for msg in sorted(set(msgs))[0:20]:
if msg:
method(f"{msg}", tm=False)
self.warnings = {}
if warn:
info("use `cv.walk(..., warn=False)` to continue after warnings")
info("use `cv.walk(..., warn=None)` to suppress warnings")
self.good = False
else:
info("use `cv.walk(..., warn=True)` to stop after warnings")
info("use `cv.walk(..., warn=None)` to suppress warnings")
def _showErrors(self):
tmObj = self.TF.tmObj
error = tmObj.error
info = tmObj.info
indent = tmObj.indent
forcedStop = self.forcedStop
errors = self.errors
if errors:
for (kind, msgs) in sorted(errors.items()):
error(f"ERROR {kind} ({len(msgs)} x):")
indent(level=2)
for msg in sorted(set(msgs))[0:20]:
if msg:
error(f"{msg}", tm=False)
self.errors = {}
self.good = False
if forcedStop:
error("STOPPED by the stop() instruction")
elif not errors:
if self.good:
info("OK")
else:
error("STOPPED because of warnings")
def walk(
self,
director,
slotType,
otext={},
generic={},
intFeatures=set(),
featureMeta={},
warn=True,
generateTf=True,
force=False,
):
"""Asks a director function to walk through source data and receives its actions.
The `director` function should unravel the source.
You have to program the `director`, which takes one argument: `cv`.
From the `cv` you can use a few standard actions that instruct Text-Fabric
to build a graph.
This function will check whether the metadata makes sense and is minimally
complete.
During node creation the section structure will be watched,
and you will be warned if irregularities occur.
After the creation of the feature data, some extra checks will be performed
to see whether the metadata matches the data and vice versa.
The new feature data will be written to the output directory of the
underlying TF object. In fact, the rules are exactly the same as for
`tf.fabric.Fabric.save`.
Parameters
----------
slotType: string
The node type that acts as the type of the slots in the data set.
oText: dict
The configuration information to be stored in the `otext` feature
(see `tf.core.text`):
* section types
* section features
* structure types
* structure features
* text formats
generic: dict
Metadata that will be written into the header of all generated TF features.
You can make changes to this later on, dynamically in your director.
intFeatures: iterable
The set of features that have integer values only.
You can make changes to this later on, dynamically in your director.
featureMeta: dict of dict
For each node or edge feature descriptive metadata can be supplied.
You can make changes to this later on, dynamically in your director.
warn: boolean, optional `True`
This regulates the response to warnings:
`True` (default): stop after warnings (as if they are errors);
`False` continue after warnings but do show them;
`None` suppress all warnings.
silent: boolean, optional `None`
By this you can suppress informational messages: `silent=True`.
force: boolean, optional `False`
This forces the process to continue after errors.
Your TF set might not be valid.
Yet this can be useful during testing, when you know
that not everything is OK, but you want to check some results.
Especially when dealing with large datasets, you might want to test
with little pieces. But then you get a kind of non-fatal errors that
stand in the way of testing. For those cases: `force=True`.
generateTf: boolean, optional `True`
You can pass `False` here to suppress the actual writing of TF data.
In that way you can dry-run the director to check for errors and warnings
director: function
An ordinary function that takes one argument, the `cv` object, and
should not deliver anything.
Writing this function is the main job to do when you want to convert a data source
to TF.
See `tf.convert.walker` for more details.
Returns
-------
boolean
Whether the operation was successful
"""
tmObj = self.TF.tmObj
info = tmObj.info
indent = tmObj.indent
setSilent = tmObj.setSilent
indent(level=0, reset=True)
info("Importing data from walking through the source ...")
self.force = force
self.good = True
self.forcedStop = False
self.errors = collections.defaultdict(list)
self.warnings = collections.defaultdict(list)
self.warn = warn
self.slotType = slotType
self.intFeatures = set(intFeatures)
self.featureMeta = featureMeta
self.metaData = {}
self.nodeFeatures = {}
self.edgeFeatures = {}
indent(level=1, reset=True)
self._prepareMeta(otext, generic)
indent(level=1, reset=True)
self._follow(director)
indent(level=1, reset=True)
self._removeUnlinked()
indent(level=1, reset=True)
self._checkGraph()
indent(level=1, reset=True)
self._checkFeatures()
indent(level=1, reset=True)
self._reorderNodes()
indent(level=1, reset=True)
self._reassignFeatures()
if generateTf:
indent(level=0)
if self.good or self.force:
self.good = self.TF.save(
metaData=self.metaData,
nodeFeatures=self.nodeFeatures,
edgeFeatures=self.edgeFeatures,
)
self._showWarnings()
setSilent(self.wasSilent)
return self.good
def _prepareMeta(self, otext, generic):
varRe = re.compile(r"\{([^}]+)\}")
tmObj = self.TF.tmObj
info = tmObj.info
indent = tmObj.indent
if not self.good and not self.force:
return
info("Preparing metadata... ")
intFeatures = self.intFeatures
featureMeta = self.featureMeta
errors = self.errors
self.metaData = {
"": generic,
OTYPE: {"valueType": "str"},
OSLOTS: {"valueType": "str"},
OTEXT: otext,
}
metaData = self.metaData
self.intFeatures = intFeatures
self.sectionTypes = []
self.sectionFeatures = []
self.sectionFromLevel = {}
self.levelFromSection = {}
self.structureTypes = []
self.structureFeatures = []
self.structureLevel = {}
self.textFormats = {}
self.textFeatures = set()
if not generic:
errors['Missing feature meta data in "generic"'].append(
"Consider adding provenance metadata to all features"
)
if not otext:
errors['Missing "otext" configuration'].append(
"Consider adding configuration for text representation and section levels"
)
else:
sectionInfo = {}
for f in ("sectionTypes", "sectionFeatures"):
if f not in otext:
errors['Incomplete section specs in "otext"'].append(
f'no key "{f}"'
)
sectionInfo[f] = []
else:
sFields = itemize(otext[f], sep=",")
sectionInfo[f] = sFields
if f == "sectionTypes":
for (i, s) in enumerate(sFields):
self.levelFromSection[s] = i + 1
self.sectionFromLevel[i + 1] = s
sLevels = {f: len(sectionInfo[f]) for f in sectionInfo}
if min(sLevels.values()) != max(sLevels.values()):
errors["Inconsistent section info"].append(
" but ".join(f'"{f}" has {sLevels[f]} levels' for f in sLevels)
)
self.sectionFeatures = sectionInfo["sectionFeatures"]
self.sectionTypes = sectionInfo["sectionTypes"]
self.featFromSectionType = {
typ: feat
for (typ, feat) in zip(self.sectionTypes, self.sectionFeatures)
}
self.sectionSet = set(self.sectionTypes)
structureInfo = {}
for f in ("structureTypes", "structureFeatures"):
if f not in otext:
structureInfo[f] = []
continue
sFields = itemize(otext[f], sep=",")
structureInfo[f] = sFields
if not structureInfo:
info("No structure definition found in otext")
sLevels = {f: len(structureInfo[f]) for f in structureInfo}
if min(sLevels.values()) != max(sLevels.values()):
errors["Inconsistent structure info"].append(
" but ".join(f'"{f}" has {sLevels[f]} levels' for f in sLevels)
)
structureInfo = {}
if not structureInfo or all(
len(info) == 0 for (s, info) in structureInfo.items()
):
info("No structure nodes will be set up")
self.structureFeatures = []
self.structureTypes = []
self.structureFeatures = structureInfo["structureFeatures"]
self.structureTypes = structureInfo["structureTypes"]
self.featFromStructureType = {
typ: feat
for (typ, feat) in zip(self.structureTypes, self.structureFeatures)
}
self.structureSet = set(self.structureTypes)
textFormats = {}
textFeatures = set()
for (k, v) in sorted(otext.items()):
if k.startswith("fmt:"):
featureSet = set()
features = varRe.findall(v)
for ff in features:
fr = ff.rsplit(":", maxsplit=1)[0]
for f in fr.split("/"):
featureSet.add(f)
textFormats[k[4:]] = featureSet
textFeatures |= featureSet
if not textFormats:
errors['No text formats in "otext"'].append('add "fmt:text-orig-full"')
elif "text-orig-full" not in textFormats:
errors["No default text format in otext"].append(
'add "fmt:text-orig-full"'
)
self.textFormats = textFormats
self.textFeatures = textFeatures
info(f'SECTION TYPES: {", ".join(self.sectionTypes)}', tm=False)
info(f'SECTION FEATURES: {", ".join(self.sectionFeatures)}', tm=False)
info(f'STRUCTURE TYPES: {", ".join(self.structureTypes)}', tm=False)
info(f'STRUCTURE FEATURES: {", ".join(self.structureFeatures)}', tm=False)
info("TEXT FEATURES:", tm=False)
indent(level=2)
for (fmt, feats) in sorted(textFormats.items()):
info(f'{fmt:<20} {", ".join(sorted(feats))}', tm=False)
indent(level=1)
for feat in WARP + ("",):
if feat in intFeatures:
if feat == "":
errors["intFeatures"].append(
'Do not declare the "valueType" for all features'
)
else:
errors["intFeatures"].append(
f'Do not mark the "{feat}" feature as integer valued'
)
self.good = False
for (feat, featMeta) in sorted(featureMeta.items()):
good = self._checkFeatMeta(
feat,
featMeta,
checkRegular=True,
valueTypeAllowed=False,
showErrors=False,
)
if not good:
self.good = False
metaData.setdefault(feat, {}).update(featMeta)
metaData[feat]["valueType"] = "int" if feat in intFeatures else "str"
self._showErrors()
def _checkFeatMeta(
self,
feat,
featMeta,
checkRegular=False,
valueTypeAllowed=True,
showErrors=True,
):
errors = collections.defaultdict(list)
good = True
if checkRegular:
if feat in WARP + ("",):
if feat == "":
errors["featureMeta"].append(
'Specify the generic feature meta data in "generic"'
)
good = False
elif feat == OTEXT:
errors["featureMeta"].append(
f'Specify the "{OTEXT}" feature in "otext"'
)
good = False
else:
errors["featureMeta"].append(
f'Do not pass metaData for the "{feat}" feature in "featureMeta"'
)
good = False
if "valueType" in featMeta:
if not valueTypeAllowed:
errors["featureMeta"].append(
f'Do not specify "valueType" for the "{feat}" feature in "featureMeta"'
)
good = False
elif featMeta["valueType"] not in {"int", "str"}:
errors["featureMeta"].append('valueType must be "int" or "str"')
good = False
for (e, eData) in errors.items():
self.errors[e].extend(eData)
if showErrors:
self._showErrors
return good
def stop(self, msg):
"""Stops the director. No further input will be read.
cv.stop(msg)
The director will exit with a non-good status and issue the message `msg`.
If you have called `walk()` with `force=True`, indicating that the
director must proceed after errors, then this stop command will cause termination
nevertheless.
Parameters
----------
msg: string
A message to display upon stopping.
Returns
-------
None
"""
tmObj = self.TF.tmObj
error = tmObj.error
error(f"Forced stop: {msg}")
self.good = False
self.force = False
self.forcedStop = True
def slot(self):
"""Make a slot node and return the handle to it in `n`.
n = cv.slot()
No further information is needed.
Remember that you can add features to the node by later
cv.feature(n, key=value, ...)
calls.
Parameters
----------
None
Returns
-------
node reference: tuple
The node reference consists of a node type and a sequence number,
but normally you do not have to dig these out.
Just pass the tuple as a whole to actions that require a node argument.
"""
curSeq = self.curSeq
curEmbedders = self.curEmbedders
oslots = self.oslots
levelFromSection = self.levelFromSection
warnings = self.warnings
self.stats[self.S] += 1
nType = self.slotType
curSeq[nType] += 1
seq = curSeq[nType]
inSection = False
for eNode in curEmbedders:
if eNode[0] in levelFromSection:
inSection = True
oslots[eNode].add(seq)
if levelFromSection and not inSection:
warnings["slot outside sections"].append(f"{seq}")
return (nType, seq)
def node(self, nType, slots=None):
"""Make a non-slot node and return the handle to it in `n`.
n = cv.node(nodeType)
You have to pass its *node type*, i.e. a string.
Think of `sentence`, `paragraph`, `phrase`, `word`, `sign`, whatever.
There are two modes for this function:
* Auto: (`slots=None`):
Non slot nodes will be automatically added to the set of embedders.
* Explicit: (`slots=iterable`):
The slots in iterable will be assigned to this node and nothing else.
The node will not be added to the set of embedders.
Put otherwise: the node will be terminated after construction.
However: you could resume it later to add other slots.
Remember that you can add features to the node by later
cv.feature(n, key=value, ...)
calls.
Parameters
----------
nType: string
A node type, not the slot type
slots: iterable of int, optional `None`
The slots to assign to this node.
If left out, the node is left as an embedding node and
subsequent slots will be added to it automatically.
All slots in the iterable must have been generated before
by means of the `cv.slot()` action.
Returns
-------
node reference or None
If an error occurred, `None` is returned.
The node reference consists of a node type and a sequence number,
but normally you do not have to dig these out.
Just pass the tuple as a whole to actions that require a node argument.
"""
slotType = self.slotType
errors = self.errors
if nType == slotType:
errors[f'use `cv.slot()` instead of `cv.node("{nType}")`'].append(None)
return
curSeq = self.curSeq
curEmbedders = self.curEmbedders
self.stats[self.N] += 1
curSeq[nType] += 1
seq = curSeq[nType]
node = (nType, seq)
self._checkSecLevel(node, before=True)
if slots:
maxSlot = curSeq[slotType]
for s in slots:
if not 1 <= s <= maxSlot:
errors[f"slot out of range in `cv.node(({nType}, {seq}))`"].append(
f"{s}"
)
else:
oslots = self.oslots
oslots[node].add(s)
self.stats[self.T] += 1
else:
curEmbedders.add(node)
return node
def terminate(self, node):
"""**terminate** a node.
cv.terminate(n)
The node `n` will be removed from the set of current embedders.
This `n` must be the result of a previous `cv.slot()` or `cv.node()` action.
Parameters
----------
node: tuple
A node reference, obtained by one of the actions `slot` or `node`.
Returns
-------
None
"""
self.stats[self.T] += 1
if node is not None:
self.curEmbedders.discard(node)
self._checkSecLevel(node, before=False)
def resume(self, node):
"""**resume** a node.
cv.resume(n)
If you resume a non-slot node, you add it again to the set of embedders.
No new node will be created.
If you resume a slot node, it will be added to the set of current embedders.
No new slot will be created.
Parameters
----------
node: tuple
A node reference, obtained by one of the actions `slot` or `node`.
Returns
-------
None
"""
curEmbedders = self.curEmbedders
oslots = self.oslots
self.stats[self.R] += 1
(nType, seq) = node
if nType == self.slotType:
for eNode in curEmbedders:
oslots[eNode].add(seq)
else:
self._checkSecLevel(node, before=None)
curEmbedders.add(node)
def link(self, node, slots):
"""Link the given, existing slots to a node.
cv.link(n)
Sometimes the automatic linking of slots to nodes is not sufficient.
This happens when you feel the need to construct a node retro-actively,
when the slots that need to be linked to it have already been created.
This action is precisely meant for that.
Parameters
----------
node: tuple
A node reference, obtained by one of the actions `slot` or `node`.
slots: iterable of integer
Returns
-------
boolean
"""
oslots = self.oslots
good = True
for seq in slots:
oslots[node].add(seq)
return good
def linked(self, node):
"""Returns the slots `ss` to which a node is currently linked.
ss = cv.linked(n)
If you construct non-slot nodes without linking them to slots,
they will be removed when TF validates the collective result
of the action methods.
If you want to prevent that, you can insert an extra slot, but in order
to do so, you have to detect that a node is still unlinked.
This action is precisely meant for that.
Parameters
----------
node: tuple
A node reference, obtained by one of the actions `slot` or `node`.
Returns
-------
tuple of integer
The slots are returned as a tuple of integers.
"""
oslots = self.oslots
return tuple(oslots.get(node, []))
def feature(self, node, **features):
"""Add **node features**.
cv.feature(n, name=value, ... , name=value)
Parameters
----------
node: tuple
A node reference, obtained by one of the actions `slot` or `node`.
**features: keyword arguments
The names and values of features to assign to this node.
Returns
-------
None
!!! caution "None values"
If a feature value is `None` it will not be added!
"""
nodeFeatures = self.nodeFeatures
self.stats[self.F] += 1
for (k, v) in features.items():
if v is None:
continue
# self._checkType(k, v, self.N)
nodeFeatures[k][node] = v
def edge(self, nodeFrom, nodeTo, **features):
"""Add **edge features**.
cv.edge(nf, nt, name=value, ... , name=value)
Parameters
----------
nodeFrom, nodeTo: tuple
Two node references, obtained by one of the actions `slot` or `node`.
**features: keyword arguments
The names and values of features to assign to this edge
(i.e. pair of nodes).
Returns
-------
None
!!! note "None values"
You may pass values that are `None`,
and a corresponding edge will be created.
If for all edges the value is `None`,
an edge without values will be created.
For every `nodeFrom`, such a feature
essentially specifies a set of nodes `{ nodeTo }`.
"""
edgeFeatures = self.edgeFeatures
self.stats[self.E] += 1
for (k, v) in features.items():
# self._checkType(k, v, self.E)
edgeFeatures[k][nodeFrom][nodeTo] = v
def occurs(self, feat):
"""Whether the feature `featureName` occurs in the resulting data so far.
occurs = cv.occurs(featureName)
If you have assigned None values to a feature, that will count, i.e.
that feature occurs in the data.
If you add feature values conditionally, it might happen that some
features will not be used at all.
For example, if your conversion produces errors, you might
add the error information to the result in the form of error features.
Later on, when the errors have been weeded out, these features will
not occur any more in the result, but then TF will complain that
such is feature is declared but not used.
At the end of your director you can remove unused features
conditionally, using this function.
Parameters
----------
feat: string
The name of a feature
Returns
-------
boolean
"""
nodeFeatures = self.nodeFeatures
edgeFeatures = self.edgeFeatures
if feat in nodeFeatures or feat in edgeFeatures:
return True
return False
def meta(self, feat, **metadata):
"""Add, modify, delete metadata fields of features.
cv.meta(feature, name=value, ... , name=value)
Parameters
----------
feat: string
The name of a feature
**metaData: pairs of name and value
If a `value` is `None`, that `name` will be deleted from the
metadata fields of the feature.
A bare `cv.meta(feature)` will remove the all metadata from the feature.
If you modify the field `valueType` of a feature, that feature will be
added or removed from the set of `intFeatures`.
It will be checked whether you specify either `int` or `str`.
Returns
-------
None
"""
errors = self.errors
intFeatures = self.intFeatures
metaData = self.metaData
featMeta = metaData.get(feat, {})
good = True
if not metadata:
if feat in metaData:
del metaData[feat]
intFeatures.discard(feat)
for (field, text) in metadata.items():
if text is None:
if field == "valueType":
errors['did not delete metadata field "valueType"'].append(feat)