-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPatternization_main.py
2345 lines (1836 loc) · 73.1 KB
/
Patternization_main.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 20 10:41:22 2024
@author: alexanderpfaff
"""
import json
from itertools import permutations, combinations
from collections import Counter
from random import choice
from math import factorial
from copy import deepcopy
class Patternize:
"""
Patternization: version NPEGL_0.9
WELCOME to >> P A T T E R N I Z A T I O N << and
CONGRATULATIONS on your acquisition of this cutting-edge devise!
Patternization is a method for classifying, analysing and visualising
syntactic / word-order variation on the basis of annotated text corpora.
The current version immediately builds upon the NP database NPEGL.
@see: Pfaff (2019)
@see: Pfaff (2024)
@see: Pfaff & Bouma (2024)
"""
def __init__(self, DB_from_file='oice', _secondaryInput=None):
"""
Initializes a Patternize::Database obkect comprising
-- a database (list) of NPs (type: Pattern), and
-- methods/functionalities to measure, process and classify
syntactic / word order variation found in the database.
This constructor provides two ways of initializing:
-- via primary input -- database is read in from file,
-- via secondary input; this option is only used internally in
order to activate Patternize objects acting as attributes of
the parent object.
Parameters
----------
DB_from_file :
TYPE: json file,
DESCRIPTION: the database to work on;
the options are:
- 'oice',
- 'osax',
- 'oeng'.
The default is 'oice'.
_secondaryInput : Internal use only!
TYPE: None or database.
DESCRIPTION: The default is None.
Returns
-------
None.
"""
if type(_secondaryInput) == list:
self._database = _secondaryInput[1:]
self._ID = _secondaryInput[0]
else:
with open(DB_from_file + "_db.json","r") as f:
inputDatabase = json.load(f)
self._database = [Pattern(np)
for np in inputDatabase]
self._ID = inputDatabase[0]["Language"]
self._maxPatternSize = None
self._update = []
self._rnd_update = 0
self._rnd_database = None
self._prenominalDomain = None
self._postnominalDomain = None
###############################
@property
def ID(self) -> str:
"""
Returns: str;
------- language of the current DB.
"""
return self._ID
@property
def size(self):
"""
Returns: int;
------- number of NPs in the current DB.
"""
return len(self.database)
@property
def maxPatternSize(self):
"""
Returns: int;
maximal pattern size = longest pattern in current DB;
------- measured in number of category labels.
"""
return len(max(self.patternize(), key=len))
@property
def update(self):
"""
Returns: list;
list of features according to which DB has been updated;
-------
DESCRIPTION: (X , bool): NPs containing X have been
- retained (True), else removed (if absent);
- removed (False), else retained (if absent).
"""
return tuple(self._update)
@property
def rnd_update(self):
"""
Returns: int;
number of random databases yet generated
------- (= number of calls >>> self.randomize())
"""
return self._rnd_update
@property
def database(self):
"""
THIS database containing all current NPs in >>> self.ID
Returns
-------
TYPE: list;
TYPE of elements in list: Pattern.
"""
return self._database
@property
def rnd_database(self):
"""
This recursive attribute is itself a Patternize database with all
functionalities. It contains a random selection of a given size of the
mother DB.
It is initially empty, and can be activated by the method
>>> self.randomize(size)
Returns
-------
TYPE: Patternize
"""
if self._rnd_database == None:
self._rnd_database = Patternize("empty")
return self._rnd_database
@property
def prenominalDomain(self):
"""
This recursive attribute is itself a Patternize database with all
functionalities. It contains the prenominal categories to the exclusion
of the noun itself.
It is initially empty, and can be activated by the method
>>> self.partitionize(partition="pre")
Returns
-------
TYPE: Patternize
"""
if self._prenominalDomain == None:
self._prenominalDomain = Patternize("empty")
return self._prenominalDomain
@property
def postnominalDomain(self):
"""
This recursive attribute is itself a Patternize database with all
functionalities. It contains the postnominal categories to the exclusion
of the noun itself.
It is initially empty, and can be activated by the method
>>> self.partitionize(partition="post")
Returns
-------
TYPE: Patternize
"""
if self._postnominalDomain == None:
self._postnominalDomain = Patternize("empty")
return self._postnominalDomain
###############################
def filter(self, cat, present=True):
"""
Allows to prune the NP entries in the current working database.
Parameters
----------
cat : TYPE: str (= category label),
DESCRIPTION: the target category;
present : TYPE: bool;
DESCRIPTION: True: NPs with target category will be removed,
False: NPs witout target category will be removed;
The default is True.
Returns
-------
None.
"""
eliminate = []
for np in self.database:
if np.hasCat(cat) == present:
eliminate.append(np)
_ = [self.database.remove(np)
for np in eliminate]
self._update.append((cat, present))
def ndb(self, properN=False, onlyProper=False, includeConjuncts=False):
"""
'ndb' = n_ominal d_ata b_ase.
Creates a working DB by imposing two restrictions on THIS DB:
-- every entry contains a noun ("N.C", "N.P" or "N"),
--> default noun == "N.C" (= common noun)
-- coordinated structures are excluded.
@see: self.filter({noun}, False) & self.filter("&", True)
It is possible to include the individual cojuncts before
the coordination structure is discarded.
Parameters
----------
properN :
TYPE: bool, optional.
DESCRIPTION: Include proper nouns. The default is False.
onlyProper :
TYPE: bool, optional.
DESCRIPTION: Proper nouns only. The default is False.
includeConjuncts :
TYPE: bool, optional.
DESCRIPTION. Include the individual conjuncts into the DB
BEFORE coordination is eliminated.
The default is False.
Returns
-------
None.
"""
if includeConjuncts:
self.partitionize(partition="pre", catCondition="&")
self.partitionize(partition="post", catCondition="&")
noun = self._catCondition(catCondition="N.C", properN=properN,
onlyProper=onlyProper)
if not (((noun, False) in self.update) and (("&", True) in self.update)):
self.filter(noun, False)
self.filter("&", True)
self._update.append(("includeConjuncts", includeConjuncts))
################################
def getNP(self, index):
"""
Parameters
----------
index : TYPE: integer
DESCRIPTION: index position in this database
Returns: the NP @{index}
-------
"""
return self.database[index]
def patternize(self, level=2):
"""
Pattern inventory of the current DB at level={level}.
A 'pattern' is an NP type (not token),
defined by the linear order of the categories involved.
De facto a getter method.
Parameters
----------
level : TYPE: int;
DESCRIPTION: the (sub-)categorization level: 0-3, 7.
The default is 2.
Returns
-------
TYPE: Counter;
DESCRIPTION: pattern : occurrences in current DB
(=key) (= value)
"""
out = [patt.getPatt(level)
for patt in self.database]
return Counter(out)
def categorize(self, level=2):
"""
Category inventory of the current DB at level={level}.
De facto a getter method.
Parameters
----------
level : TYPE: int;
DESCRIPTION: the (sub-)categorization level: 0-3, 7;
The default is 2.
Returns
-------
TYPE: Counter;
DESCRIPTION: category : occurrences in current DB
(=key) (= value)
"""
out = [cat
for np in self.database
for cat in np.getPatt(level)] ## instead of getCat !!!
return Counter(out) ## --> multiple occurrences
def getAllCats(self):
"""
Category inventory of the current DB at all levels.
De facto a getter method.
Returns
-------
TYPE: Counter;
DESCRIPTION: category : occurrences in current DB
(=key) (= value)
"""
out = [cat
for np in self.database
for cat in np.allCats]
return Counter(out)
def lemmatize(self):
"""
Returns
-------
TYPE: Counter;
DESCRIPTION: lemma found in current DB : occurrences in current DB
(= key) (= value)
"""
out = [lemma.lower()
for np in self.database
for lemma in np.lemmata]
return Counter(out)
def findLemma(self, cat):
"""
Finds all lemmata in THIS database instantiating {cat}.
Parameters
----------
cat : TYPE: str (category label);
Returns:
-------
TYPE: Counter;
DESCRIPTION: lemma instantiating {cat} : occurrences in current DB
(= key) (= value)
"""
out = []
for np in self.database:
if cat in np.allCats:
for position in range(np.length):
if cat in np.macroPattern[position]:
out.append(np.lemmata[position])
return Counter(out)
def cat_in_patt(self, cat, level=2):
"""
returns the patterns in which a given category {cat} occurs.
Parameters
----------
cat : TYPE: str (category label);
DESCRIPTION.
level : TYPE: int;
DESCRIPTION: level of sub-categorization.
The default is 2.
Returns
-------
TYPE: Counter;
DESCRIPTION: pattern containing {cat} : occurrences in curent DB
(= key) (= value)
"""
return Counter([np.getPatt(level)
for np in self.database
if cat in np.getPatt(level)])
@property
def tokenize(self):
"""
Returns
-------
TYPE: int;
DESCRIPTION: number of tokens in the current DB.
"""
return sum([np.length
for np in self.database])
@property
def lemmata_per_NPs(self):
"""
Nomen est omen!
Returns
-------
TYPE: float;
DESCRIPTION: ratio lemmata per NPs in the current DB.
"""
return round(100 * (len(self.lemmatize()) / self.size), 2)
@property
def lemmata_per_tokens(self):
"""
Nomen est omen!
Returns
-------
TYPE: float;
DESCRIPTION: ratio lemmata per tokens in the current DB.
"""
return round(100 * (len(self.lemmatize()) / self.tokenize), 2)
def patterns_per_NPs(self, level=2):
"""
Nomen est omen!
Parameters
----------
level : TYPE: int;
DESCRIPTION: level of sub-categorization.
The default is 2.
Returns
-------
TYPE: float;
DESCRIPTION: ratio patterns per NPs in the current DB.
@see patternDiversity!
"""
return round(100 * (len(self.patternize(level)) / self.size), 2)
def categories_per_patterns(self, level=2):
"""
Nomen est omen!
Parameters
----------
level : TYPE: int;
DESCRIPTION: level of sub-categorization.
The default is 2.
Returns
-------
TYPE: float;
DESCRIPTION: ratio categories per NPs in the current DB.
"""
return round(100 * (len(self.categorize(level)) /
len(self.patternize(level))), 2)
def randomize(self, size=1000):
"""
Creates a randomized database of a given size {size} ==
subset of the mother database.
Parameters
----------
size : TYPE: int;
DESCRIPTION: size of the random sub-database.
The default is 1000.
Returns
-------
None.
"""
out = set()
while len(out) < size:
out.add(choice(self.database))
out = list(out)
out.insert(0, self.ID + ", @rnd_database")
self._rnd_update +=1
self._rnd_database = Patternize(DB_from_file=None, _secondaryInput=out)
def patternDiversity(self, level=2, runs=500, size=1000):
"""
Pattern Diversity = ratio patterns at {level} per NPs relative to a
standardized common denominator.
The ratio is determined as the means of {runs}
iterations of patterns per NPs over randomized
sub-DBs of size {size}.
Parameters
----------
level : TYPE: int;
DESCRIPTION: level of sub-categorization.
The default is 2.
runs : TYPE: int;
DESCRIPTION: number of iterations over random sub-DBs.
The default is 500.
size : TYPE: int;
size of the random sub-DB.
DESCRIPTION. The default is 1000.
Returns
-------
TYPE: float;
DESCRIPTION: pattern diversity (ratio: patterns per {size} NPs)
"""
patterns_from_subDBs = 0
for run in range(runs):
self.randomize(size=size)
patterns_from_subDBs +=len(self.rnd_database.patternize(level=level))
avg_patts = patterns_from_subDBs / runs
return round((100 * (avg_patts / size)), 2)
def clear_subDBs(self):
"""
Sets all activated sub-databases to "empty".
Returns
-------
None.
"""
self._rnd_database = Patternize("empty")
self._prenominalDomain = Patternize("empty")
self._postnominalDomain = Patternize("empty")
###############################################
######### COMBINATORIX
def _catCondition(self, catCondition="N.C", properN=False,
onlyProper=False):
"""
auxiliary method
Parameters
----------
catCondition : TYPE: str or a neg-type (None/False);
DESCRIPTION: category label.
The default is "N.C".
properN : TYPE: bool;
DESCRIPTION: include proper names.
The default is False.
onlyProper : TYPE: bool;
DESCRIPTION: proper names only.
The default is False.
Returns
-------
catCondition : TYPE: str or a neg-type (None/False)
DESCRIPTION: category label to be used in filter methods.
"""
if catCondition:
if properN:
if onlyProper:
catCondition = "N.P"
else:
catCondition = "N"
return catCondition
def combinatorialFlexibility(self, cats, length=3, sm_pattern=None,
align=None, pattern_threshold=1,
group_threshold=2, count=bool,
addAdjectives=False, catCondition="N.C",
properN=False, onlyProper=False):
"""
This method probes into the range of combinatorial flexibility of the
current DB with respect to the pattern permutations of a given size
created on the basis of a given selection of category labels.
Procedure: with n = len(cats) and k = {length}, all n_C_k combinations
c in {cats} are produced. If not catCondition or
catCondition in c, all k! permutations p of c are generated
and collected as permutation groups. For each p in c, the
current DB is browsed and every match according to the
criterion sm_pattern is counted; if number of matches p >=
pattern_threshold, and added number of matches p in c >=
group_threshold, the permutation group c is considered
attested and stored as a CombFlex object.
Attestation values can be
- categorical (yes/no) <==> count=bool, or
- numerical (number of attestations) <==> count=int.
Parameters
----------
cats : TYPE: container (list, tuple) of category labels;
DESCRIPTION: sample space on basis of which combinations of
length {length} are created.
length : TYPE: int;
DESCRIPTION. length of combinations/permutations.
The default is 3.
sm_pattern : TYPE: container (list, tuple) of category labels;
DESCRIPTION: search/match pattern template,
possible specification: >>> self.precise,
>>> self.rigid,
>>> self.flexi.
The default is None ==> rigid.
align : TYPE: str, optional;
DESCRIPTION: allows specification for alignment;
possible values: "left", "right".
The default is None.
pattern_threshold :
TYPE: int;
DESCRIPTION: minimal number of attestations in order for a given
permutation to be counted.
The default is 1.
group_threshold :
TYPE: int;
DESCRIPTION: minimal number of attestations of permutations
within a given permutation group in order for the
combination/permutation group to be counted.
The default is 2.
count : TYPE: <int> or <bool>;
DESCRIPTION: specifies the mode of counting:
-- number of attestations (int),
-- True/False if (not) attested
in accordance with the threshold settings.
The default is bool.
addAdjectives :
TYPE: bool, optional;
DESCRIPTION. if True, adjective cat labels will be added again;
ensures combinations --> permutations involving
two adjectives are taken into account.
The default is False.
catCondition :
TYPE: str (category label);
DESCRIPTION: specifies whether a given category must be present
in all combinations (--> permutations).
The default is "N.C".
properN : TYPE: bool, optional;
DESCRIPTION: include proper names.
The default is False.
onlyProper : TYPE: bool, optional;
DESCRIPTION: proper names only.
The default is False.
Returns
-------
out : TYPE: list [ {CombFlex} ];
DESCRIPTION: permutation groups satisfying the matching and
threshold conditions are construed as CombFlex
objects and appended to {out}.
"""
catCondition = self._catCondition(catCondition=catCondition,
properN=properN,
onlyProper=onlyProper)
if sm_pattern == None:
sm_pattern = self.rigid
out = []
possiblePermutations = self._possiblePermutations(cats, length=length,
catCondition=
catCondition,
addAdjectives=
addAdjectives)
for combination in possiblePermutations:
permutationGroup = possiblePermutations[combination]
groupAttestation = dict()
groupCount = 0
for i in range(factorial(length)):
pattern = next(permutationGroup)
attested = self.collectCustomMatch(pattern,
sm_pattern=sm_pattern,
align=align)
if len(attested) < pattern_threshold:
attested = []
groupAttestation[pattern] = dict()
groupAttestation[pattern]["Count"] = count(len(attested))
groupAttestation[pattern]["Attestations"] = attested
groupCount += len(attested)
if groupCount >= group_threshold:
combFlexOut = CombFlex(combination=combination, length=length,
sm_pattern=str(sm_pattern)[:-25] + ">",
align=str(align),
pattern_threshold=pattern_threshold,
group_threshold=group_threshold,
count=count, groupCount=groupCount,
permutations=groupAttestation,
catCondition=catCondition)
out.append(combFlexOut)
return out
def customize(self, np, pattern, sm_pattern=None, align=None):
"""
Checks whether the NP matches a given pattern with additional
specifications provided by the functional parameter sm_pattern, which
can be set to self.precise, self.rigid, self.flexi (default: rigid);
@see: precise, rigid, flexi.
In addition, it allows to impose an aligment condition with the
possible values "left": first category of m_pattern and s_pattern must
be identical; "right": last category of m_pattern and s_pattern must
be identical; default: no alignment.
Parameters
----------
np : TYPE: Pattern;
DESCRIPTION: an NP.
pattern : TYPE: list or tuple
DESCRIPTION.
sm_pattern : TYPE: container (list, tuple) of category labels;
DESCRIPTION: search/match pattern template,
possible specification: >>> self.precise,
>>> self.rigid,
>>> self.flexi.
The default is None ==> rigid.
align : TYPE: str, optional;
DESCRIPTION: allows specification for alignment;
possible values: "left", "right".
The default is None.
Returns
-------
TYPE: bool;
DESCRIPTION: True if alignment and matching conditions are
satisfied.
"""
if sm_pattern == None:
sm_pattern = self.rigid
m_pattern = np.macroPattern
s_pattern = list(pattern)
# s_pattern = [cat for cat in pattern]
if align == "left":
alignmentCheck = s_pattern[0] in m_pattern[0]
elif align == "right":
alignmentCheck = s_pattern[-1] in m_pattern[-1]
else:
alignmentCheck = True
return alignmentCheck and sm_pattern(m_pattern, s_pattern)
def precise(self, m_pattern, s_pattern):
"""
A functional parameter ("pseudo-lambda") specifying a precise search
pattern (s_pattern) that has to match the given NP pattern (m_pattern).
Matching conditions:
(Cat_1, Cat_2 .. Cat_n) <==> (Cat_1, Cat_2 .. Cat_n)
i.e. an exact match.
To be passed in to >>> self.combinatorialFlexibility as a
specification of the parameter 'sm_pattern';
@see: flexi
@see: rigid
Parameters
----------
m_pattern : the matched pattern (NP)
s_pattern : the search pattern
Returns
-------
TYPE: bool;
DESCRIPTION: True if the matching condition is satisfied.
"""
if len(m_pattern) != len(s_pattern):
return False
return all([s_pattern[index] in m_pattern[index]
for index in range(len(s_pattern))])
def rigid(self, m_pattern, s_pattern):
"""
A functional parameter ("pseudo-lambda") specifying a rigid search
pattern (s_pattern) that has to match the given NP pattern (m_pattern).
Matching conditions:
(Cat_1, Cat_2 .. Cat_n) <==> (... Cat_1, Cat_2 .. Cat_n ...)
i.e. the sequence of s_pattern must be contained in m_pattern.
To be passed in to >>> self.combinatorialFlexibility as a
specification of the parameter 'sm_pattern';
@see: flexi
@see: precise
Parameters
----------
m_pattern : the matched pattern (NP)
s_pattern : the search pattern
Returns
-------
TYPE: bool;
DESCRIPTION: True if the matching condition is satisfied.
"""
if len(s_pattern) > len(m_pattern):
return False
firstCatIndex = -1
for index in range(len(m_pattern)):
if s_pattern[0] in m_pattern[index]:
firstCatIndex = index
return self.precise(m_pattern[firstCatIndex:], s_pattern)
def flexi(self, m_pattern, s_pattern):
"""
A functional parameter ("pseudo-lambda") specifying a flexible search
pattern (s_pattern) that has to match the given NP pattern (m_pattern).
Matching conditions:
(Cat_1, Cat_2 .. Cat_n) <==> (... Cat_1, ... Cat_2 ... Cat_n ...)
i.e. the relative sequence of categories in s_pattern must be found in
m_pattern (regardless of intervening material).
To be passed in to >>> self.combinatorialFlexibility as a
specification of the parameter 'sm_pattern';
@see: precise
@see: rigid
Parameters
----------
m_pattern : the matched pattern (NP)
s_pattern : the search pattern
Returns
-------
TYPE: bool;
DESCRIPTION: True if the matching condition is satisfied.
"""
if len(s_pattern) > len(m_pattern):
return False
matches = len(s_pattern)
s_pattern.append("")
match = False
currentCat = s_pattern.pop(0)
currentIndex = 0
while currentIndex < len(m_pattern) and not match:
if currentCat in m_pattern[currentIndex]:
matches -=1
if matches == 0:
match = True
currentCat = s_pattern.pop(0)
currentIndex +=1
return match
def collectCustomMatch(self, pattern, sm_pattern=None, align=None):
"""
Collects NPs that satisfy the matching and alignment conditions.
Parameters
----------
pattern : TYPE: container (tuple/list) of str;
DESCRIPTION: sequence of category labels
sm_pattern : TYPE: functional parameter specifying matching conditions
DESCRIPTION: possible values: self.precise, self.rigid,
self.flexi
The default is None ==> rigid.
align : TYPE: str, optional;
DESCRIPTION: specifies an alignment condition: "left" or "right".
The default is None (= no alignment).
Returns
-------
list of Pattern objects;
DESCRIPTION: contains the NPs satisfying the matching and
alignment conditions.
"""
return [np
for np in self.database
if self.customize(np, pattern, sm_pattern=sm_pattern, align=align)]
def combis_mirror(self, cats, sm):
""" TO DO"""
pass
def combis_flanked(self, cats, sm):
""" TO DO"""
pass
def _permutePatterns(self, pattern):
"""
aux_@_combinatorialFlexibility
creates all len(pattern)! permutations of {pattern}
Parameters
----------
pattern : TYPE: tuple/list
DESCRIPTION: sequence of category labels
Raises
------
ValueError
DESCRIPTION: if len(pattern) < 2
Returns
-------
TYPE: iterator
DESCRIPTION: contains all permutations of {pattern}.
"""
if len(pattern) < 2:
raise ValueError("Inappropriate size values!")
return permutations(pattern)
def _catCombinations(self, cats, length=3, catCondition="N.C"):
"""
aux_@_combinatorialFlexibility
creates all n_C_k combinations c over {cats}, with n = len(cats),
k = {length};
if not catCondition or catCondition in c, c is added to output list.
Parameters
----------
cats : TYPE: str;
DESCRIPTION: category label
length : TYPE: int;
DESCRIPTION: length of combination (subset) in {cats}.
The default is 3.
catCondition :
TYPE: None or str, optional;
DESCRIPTION. specifies a category that must be contained in every
combination; normally a nominal category.
The default is "N.C".
Raises
------
ValueError
DESCRIPTION: if len(cats) < 2 || length < 2 || len(cats) < length.
Returns
-------
TYPE: tuple
DESCRIPTION: of tuples = combinations of length {length},
potentially satifying {catCondition}.