-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
UniversalEnglishGrammaticalStructure.java
2029 lines (1713 loc) · 74.3 KB
/
UniversalEnglishGrammaticalStructure.java
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
package edu.stanford.nlp.trees;
import java.io.IOException;
import java.io.Serializable;
import java.util.*;
import java.util.function.Predicate;
import edu.stanford.nlp.graph.DirectedMultiGraph;
import edu.stanford.nlp.ling.CoreAnnotations;
import edu.stanford.nlp.ling.IndexedWord;
import edu.stanford.nlp.process.Morphology;
import edu.stanford.nlp.semgraph.SemanticGraph;
import edu.stanford.nlp.semgraph.SemanticGraphEdge;
import edu.stanford.nlp.semgraph.semgrex.SemgrexMatcher;
import edu.stanford.nlp.semgraph.semgrex.SemgrexPattern;
import edu.stanford.nlp.trees.ud.EnhancementOptions;
import edu.stanford.nlp.util.Filters;
import edu.stanford.nlp.util.Generics;
import edu.stanford.nlp.util.logging.Redwood;
import static edu.stanford.nlp.trees.UniversalEnglishGrammaticalRelations.*;
import static edu.stanford.nlp.trees.GrammaticalRelation.*;
/**
* A GrammaticalStructure for Universal Dependencies English.
* <br>
* For feeding Stanford parser trees into this class, the Stanford parser should be run with the
* "-retainNPTmpSubcategories" option for best results!
*
* @author Bill MacCartney
* @author Marie-Catherine de Marneffe
* @author Christopher Manning
* @author Daniel Cer (CoNLLX format and alternative user selected dependency
* printer/reader interface)
* @author John Bauer
* @author Sebastian Schuster
*/
public class UniversalEnglishGrammaticalStructure extends GrammaticalStructure {
/** A logger for this class */
private static final Redwood.RedwoodChannels log = Redwood.channels(UniversalEnglishGrammaticalStructure.class);
private static final long serialVersionUID = 1L;
private static final boolean DEBUG = System.getProperty("UniversalEnglishGrammaticalStructure", null) != null;
private static final boolean USE_NAME = System.getProperty("UDUseNameRelation") != null;
/*
* Options for "Enhanced" representation:
*
* - Process multi-word prepositions: No
* - Add prepositions to relation labels: Yes
* - Add prepositions only to nmod relations: No
* - Add coordinating conjunctions to relation labels: Yes
* - Propagate dependents: Yes
* - Add "referent" relations: Yes
* - Add copy nodes for conjoined Ps and PPs: No
* - Turn quantificational modifiers into flat MWEs: No
* - Add relations between controlling subject and controlled verbs: Yes
*
*/
public static final EnhancementOptions ENHANCED_OPTIONS = new EnhancementOptions(false, true, false, true, true, true,
false, false, true);
/*
* Options for "Enhanced++" representation:
*
* - Process multi-word prepositions: Yes
* - Add prepositions to relation labels: Yes
* - Add prepositions only to nmod relations: No
* - Add coordinating conjunctions to relation labels: Yes
* - Propagate dependents: Yes
* - Add "referent" relations: Yes
* - Add copy nodes for conjoined Ps and PPs: Yes
* - Turn quantificational modifiers into flat MWEs: Yes
* - Add relations between controlling subject and controlled verbs: Yes
*
*/
public static final EnhancementOptions ENHANCED_PLUS_PLUS_OPTIONS = new EnhancementOptions(true, true, false, true, true, true,
true, true, true);
/*
* Options for "Collapsed" representation.
* This representation is similar to the "collapsed" SD representation
* without any "Extra" relations.
*
* - Process multi-word prepositions: Yes
* - Add prepositions to relation labels: Yes
* - Add prepositions only to nmod relations: Yes
* - Add coordinating conjunctions to relation labels: Yes
* - Propagate dependents: No
* - Add "referent" relations: No
* - Add copy nodes for conjoined Ps and PPs: Yes
* - Turn quantificational modifiers into flat MWEs: No
* - Add relations between controlling subject and controlled verbs: No
*
*/
@Deprecated
public static final EnhancementOptions COLLAPSED_OPTIONS = new EnhancementOptions(true, true, true, true, false, false,
true, false, false);
/**
* Construct a new {@code EnglishGrammaticalStructure} from an existing parse
* tree. The new {@code GrammaticalStructure} has the same tree structure
* and label values as the given tree (but no shared storage). As part of
* construction, the parse tree is analyzed using definitions from
* {@link GrammaticalRelation {@code GrammaticalRelation}} to populate
* the new {@code GrammaticalStructure} with as many labeled grammatical
* relations as it can.
*
* @param t Parse tree to make grammatical structure from
*/
public UniversalEnglishGrammaticalStructure(Tree t) {
this(t, new PennTreebankLanguagePack().punctuationWordRejectFilter());
}
/**
* This gets used by GrammaticalStructureFactory (by reflection). DON'T DELETE.
*
* @param t Parse tree to make grammatical structure from
* @param tagFilter Filter to remove punctuation dependencies
*/
public UniversalEnglishGrammaticalStructure(Tree t, Predicate<String> tagFilter) {
this(t, tagFilter, new UniversalSemanticHeadFinder(true));
}
/**
* Construct a new {@code GrammaticalStructure} from an existing parse
* tree. The new {@code GrammaticalStructure} has the same tree structure
* and label values as the given tree (but no shared storage). As part of
* construction, the parse tree is analyzed using definitions from
* {@link GrammaticalRelation {@code GrammaticalRelation}} to populate
* the new {@code GrammaticalStructure} with as many labeled grammatical
* relations as it can.
*
* This gets used by GrammaticalStructureFactory (by reflection). DON'T DELETE.
*
* @param t Parse tree to make grammatical structure from
* @param tagFilter Filter for punctuation tags
* @param hf HeadFinder to use when building it
*/
public UniversalEnglishGrammaticalStructure(Tree t, Predicate<String> tagFilter, HeadFinder hf) {
// the tree is normalized (for index and functional tag stripping) inside CoordinationTransformer
super(t, UniversalEnglishGrammaticalRelations.values(), UniversalEnglishGrammaticalRelations.valuesLock(),
new CoordinationTransformer(hf, true), hf, Filters.acceptFilter(), tagFilter);
}
/** Used for postprocessing CoNLL X dependencies */
public UniversalEnglishGrammaticalStructure(List<TypedDependency> projectiveDependencies, TreeGraphNode root) {
super(projectiveDependencies, root);
}
/**
* Returns a Filter which checks dependencies for usefulness as
* extra tree-based dependencies. By default, everything is
* accepted. One example of how this can be useful is in the
* English dependencies, where the REL dependency is used as an
* intermediate and we do not want this to be added when we make a
* second pass over the trees for missing dependencies.
*/
@Override
protected Predicate<TypedDependency> extraTreeDepFilter() {
return extraTreeDepFilter;
}
private static class ExtraTreeDepFilter implements Predicate<TypedDependency>, Serializable {
@Override
public boolean test(TypedDependency d) {
return d != null && d.reln() != RELATIVE && d.reln() != PREPOSITION;
}
private static final long serialVersionUID = 1L;
}
private static final Predicate<TypedDependency> extraTreeDepFilter = new ExtraTreeDepFilter();
@Override
protected void getTreeDeps(List<TypedDependency> deps,
DirectedMultiGraph<TreeGraphNode, GrammaticalRelation> completeGraph,
Predicate<TypedDependency> puncTypedDepFilter,
Predicate<TypedDependency> extraTreeDepFilter) {
//Do nothing
}
@Override
protected void correctDependencies(List<TypedDependency> list) {
SemanticGraph sg = new SemanticGraph(list);
correctDependencies(sg);
list.clear();
list.addAll(sg.typedDependencies());
Collections.sort(list);
}
protected static void correctDependencies(SemanticGraph sg) {
if (DEBUG) {
printListSorted("At correctDependencies:", sg.typedDependencies());
}
correctSubjPass(sg);
if (DEBUG) {
printListSorted("After correctSubjPass:", sg.typedDependencies());
}
processNames(sg);
if (DEBUG) {
printListSorted("After processNames:", sg.typedDependencies());
}
removeExactDuplicates(sg);
if (DEBUG) {
printListSorted("After removeExactDuplicates:", sg.typedDependencies());
}
}
private static void printListSorted(String title, Collection<TypedDependency> list) {
List<TypedDependency> lis = new ArrayList<>(list);
Collections.sort(lis);
if (title != null) {
log.info(title);
}
log.info(lis);
}
@Override
protected void postProcessDependencies(List<TypedDependency> list) {
SemanticGraph sg = new SemanticGraph(list);
postProcessDependencies(sg);
list.clear();
list.addAll(sg.typedDependencies());
}
protected static void postProcessDependencies(SemanticGraph sg) {
if (DEBUG) {
printListSorted("At postProcessDependencies:", sg.typedDependencies());
}
correctWHAttachment(sg);
if (DEBUG) {
printListSorted("After correcting WH attachment:", sg.typedDependencies());
}
convertRel(sg);
if (DEBUG) {
printListSorted("After converting rel:", sg.typedDependencies());
}
fixCCAttachment(sg);
if (DEBUG) {
printListSorted("After fixing CC attachment:", sg.typedDependencies());
}
}
@Override
protected void getExtras(List<TypedDependency> list) {
SemanticGraph sg = new SemanticGraph(list);
addRef(sg);
if (DEBUG) {
printListSorted("After adding ref:", sg.typedDependencies());
}
addExtraNSubj(sg);
if (DEBUG) {
printListSorted("After adding extra nsubj:", sg.typedDependencies());
}
list.clear();
list.addAll(sg.typedDependencies());
}
/* Semgrex patterns for prepositional phrases. */
private static final SemgrexPattern PASSIVE_AGENT_PATTERN = SemgrexPattern.compile("{}=gov >obl=reln ({}=mod >case {word:/^(?i:by)$/}=c1) >/^aux:pass$/ {}");
private static final SemgrexPattern[] PREP_MW3_PATTERNS = {
SemgrexPattern.compile("{}=gov [>/^(nmod|obl)$/=reln ({}=mod >case ({}=c1 >fixed {}=c2 >fixed ({}=c3 !== {}=c2) ))]"),
SemgrexPattern.compile("{}=gov [>/^(advcl|acl)$/=reln ({}=mod >/^(mark|case)$/ ({}=c1 >fixed {}=c2 >fixed ({}=c3 !== {}=c2) ))]")
};
private static final SemgrexPattern[] PREP_MW2_PATTERNS = {
SemgrexPattern.compile("{}=gov >/^(nmod|obl)$/=reln ({}=mod >case ({}=c1 >fixed {}=c2))"),
SemgrexPattern.compile("{}=gov >/^(advcl|acl)$/=reln ({}=mod >/^(mark|case)$/ ({}=c1 >fixed {}=c2))")
};
private static final SemgrexPattern[] PREP_PATTERNS = {
SemgrexPattern.compile("{}=gov >/^(nmod|obl)$/=reln ({}=mod >case {}=c1)"),
SemgrexPattern.compile("{}=gov >/^(advcl|acl)$/=reln ({}=mod >/^(mark|case)$/ {}=c1)")
};
/**
* Adds the case marker(s) to all nmod, acl and advcl relations that are
* modified by one or more case markers(s).
*
* @param enhanceOnlyNmods If this is set to true, then prepositions will only be appended to nmod
* relations (and not to acl or advcl) relations.
*
* @see UniversalEnglishGrammaticalStructure#addCaseMarkersToReln
*/
private static void addCaseMarkerInformation(SemanticGraph sg, boolean enhanceOnlyNmods) {
/* Semgrexes require a graph with a root. */
if (sg.getRoots().isEmpty())
return;
/* passive agent */
SemanticGraph sgCopy = sg.makeSoftCopy();
SemgrexMatcher matcher = PASSIVE_AGENT_PATTERN.matcher(sgCopy);
while (matcher.find()) {
IndexedWord caseMarker = matcher.getNode("c1");
IndexedWord gov = matcher.getNode("gov");
IndexedWord mod = matcher.getNode("mod");
addPassiveAgentToReln(sg, gov, mod, caseMarker);
}
List<IndexedWord> oldCaseMarkers = Generics.newArrayList();
/* 3-word prepositions */
for (SemgrexPattern p: PREP_MW3_PATTERNS) {
sgCopy = sg.makeSoftCopy();
matcher = p.matcher(sgCopy);
while (matcher.find()) {
if (enhanceOnlyNmods && ! matcher.getRelnString("reln").equals("nmod")
&& ! matcher.getRelnString("reln").equals("obl")) {
continue;
}
List<IndexedWord> caseMarkers = Generics.newArrayList(3);
caseMarkers.add(matcher.getNode("c1"));
caseMarkers.add(matcher.getNode("c2"));
caseMarkers.add(matcher.getNode("c3"));
Collections.sort(caseMarkers);
/* We only want to match every case marker once. */
if (caseMarkers.equals(oldCaseMarkers))
continue;
IndexedWord gov = matcher.getNode("gov");
IndexedWord mod = matcher.getNode("mod");
addCaseMarkersToReln(sg, gov, mod, caseMarkers);
oldCaseMarkers = caseMarkers;
}
}
/* 2-word prepositions */
for (SemgrexPattern p: PREP_MW2_PATTERNS) {
sgCopy = sg.makeSoftCopy();
matcher = p.matcher(sgCopy);
while (matcher.find()) {
if (enhanceOnlyNmods && ! matcher.getRelnString("reln").equals("nmod")
&& ! matcher.getRelnString("reln").equals("obl")) {
continue;
}
List<IndexedWord> caseMarkers = Generics.newArrayList(2);
caseMarkers.add(matcher.getNode("c1"));
caseMarkers.add(matcher.getNode("c2"));
Collections.sort(caseMarkers);
/* We only want to match every case marker once. */
if (caseMarkers.equals(oldCaseMarkers))
continue;
IndexedWord gov = matcher.getNode("gov");
IndexedWord mod = matcher.getNode("mod");
addCaseMarkersToReln(sg, gov, mod, caseMarkers);
oldCaseMarkers = caseMarkers;
}
}
/* Single-word prepositions */
for (SemgrexPattern p: PREP_PATTERNS) {
sgCopy = sg.makeSoftCopy();
matcher = p.matcher(sgCopy);
while (matcher.find()) {
if (enhanceOnlyNmods && ! matcher.getRelnString("reln").equals("nmod")
&& ! matcher.getRelnString("reln").equals("obl")) {
continue;
}
List<IndexedWord> caseMarkers = Generics.newArrayList(1);
caseMarkers.add(matcher.getNode("c1"));
if (caseMarkers.equals(oldCaseMarkers))
continue;
IndexedWord gov = matcher.getNode("gov");
IndexedWord mod = matcher.getNode("mod");
addCaseMarkersToReln(sg, gov, mod, caseMarkers);
oldCaseMarkers = caseMarkers;
}
}
}
private static void addPassiveAgentToReln(SemanticGraph sg,
IndexedWord gov, IndexedWord mod, IndexedWord caseMarker) {
SemanticGraphEdge edge = sg.getEdge(gov, mod);
sg.updateEdge(edge, UniversalEnglishGrammaticalRelations.AGENT);
}
/**
* Appends case marker information to nmod/acl/advcl relations.
*
* E.g. if there is a relation {@code nmod(gov, dep)} and {@code case(dep, prep)}, then
* the {@code nmod} relation is renamed to {@code nmod:prep}.
*
*
* @param sg semantic graph
* @param gov governor of the nmod/acl/advcl relation
* @param mod modifier of the nmod/acl/advcl relation
* @param caseMarkers {@code List<IndexedWord>} of all the case markers that depend on mod
*/
private static void addCaseMarkersToReln(SemanticGraph sg, IndexedWord gov, IndexedWord mod, List<IndexedWord> caseMarkers) {
SemanticGraphEdge edge = sg.getEdge(gov, mod);
int lastCaseMarkerIndex = 0;
StringBuilder sb = new StringBuilder();
boolean firstWord = true;
for (IndexedWord cm : caseMarkers) {
/* check for adjacency */
if (lastCaseMarkerIndex == 0 || cm.index() == (lastCaseMarkerIndex + 1)) {
if ( ! firstWord) {
sb.append('_');
}
sb.append(cm.value());
firstWord = false;
} else {
/* Should never happen as there should be never two non-adjacent case markers.
* If it does happen nevertheless create an additional relation.
*/
GrammaticalRelation reln = getCaseMarkedRelation(edge.getRelation(), sb.toString().toLowerCase());
sg.addEdge(gov, mod, reln, Double.NEGATIVE_INFINITY, true);
sb = new StringBuilder(cm.value());
firstWord = true;
}
lastCaseMarkerIndex = cm.index();
}
GrammaticalRelation reln = getCaseMarkedRelation(edge.getRelation(), sb.toString().toLowerCase());
sg.updateEdge(edge, reln);
}
private static final SemgrexPattern PREP_CONJP_PATTERN = SemgrexPattern.compile("{} >/(case|mark)/ ({}=gov >conj ({} >cc {}=cc) >conj {}=conj)" +
"");
/**
* Expands prepositions with conjunctions such as in the sentence
* "Bill flies to and from Serbia." by copying the verb resulting
* in the following relations:
* <br>
* {@code conj:and(flies, flies')}<br>
* {@code case(Serbia, to)}<br>
* {@code cc(to, and)}<br>
* {@code conj(to, from)}<br>
* {@code nmod(flies, Serbia)}<br>
* {@code nmod(flies', Serbia)}<br>
* <br>
* The label of the conjunct relation includes the conjunction type
* because if the verb has multiple cc relations then it can be impossible
* to infer which coordination marker belongs to which conjuncts.
*
* @param sg A SemanticGraph for a sentence
*/
private static void expandPrepConjunctions(SemanticGraph sg) {
/* Semgrexes require a graph with a root. */
if (sg.getRoots().isEmpty())
return;
SemanticGraph sgCopy = sg.makeSoftCopy();
SemgrexMatcher matcher = PREP_CONJP_PATTERN.matcher(sgCopy);
IndexedWord oldGov = null;
IndexedWord oldCcDep = null;
List<IndexedWord> conjDeps = Generics.newLinkedList();
while (matcher.find()) {
IndexedWord ccDep = matcher.getNode("cc");
IndexedWord conjDep = matcher.getNode("conj");
IndexedWord gov = matcher.getNode("gov");
if (oldGov != null && (! gov.equals(oldGov) || ! ccDep.equals(oldCcDep))) {
expandPrepConjunction(sg, oldGov, conjDeps, oldCcDep);
conjDeps = Generics.newLinkedList();
}
oldCcDep = ccDep;
oldGov = gov;
conjDeps.add(conjDep);
}
if (oldGov != null) {
expandPrepConjunction(sg, oldGov, conjDeps, oldCcDep);
}
}
/*
* Used by expandPrepConjunctions.
*/
private static void expandPrepConjunction(SemanticGraph sg, IndexedWord gov,
List<IndexedWord> conjDeps, IndexedWord ccDep) {
IndexedWord caseGov = sg.getParent(gov);
if (caseGov == null)
return;
IndexedWord caseGovGov = sg.getParent(caseGov);
if (caseGovGov == null)
return;
IndexedWord conjGov = caseGovGov.getOriginal() != null ? caseGovGov.getOriginal() : caseGovGov;
GrammaticalRelation rel = sg.reln(caseGovGov, caseGov);
List<IndexedWord> newConjDeps = Generics.newLinkedList();
for (IndexedWord conjDep : conjDeps) {
//IndexedWord caseGovCopy = caseGov.makeSoftCopy();
IndexedWord caseGovGovCopy = caseGovGov.makeSoftCopy();
/* Change conj(prep-1, prep-2) to case(prep-1-gov-copy, prep-2) */
//SemanticGraphEdge edge = sg.getEdge(gov, conjDep);
//sg.removeEdge(edge);
//sg.addEdge(caseGovCopy, conjDep, CASE_MARKER, Double.NEGATIVE_INFINITY, false);
/* Add relation to copy node. */
//sg.addEdge(caseGovGovCopy, caseGovCopy, rel, Double.NEGATIVE_INFINITY, false);
sg.addEdge(conjGov, caseGovGovCopy, CONJUNCT, Double.NEGATIVE_INFINITY, false);
newConjDeps.add(caseGovGovCopy);
sg.addEdge(caseGovGovCopy, caseGov, rel, Double.NEGATIVE_INFINITY, true);
List<IndexedWord> caseMarkers = Generics.newArrayList();
caseMarkers.add(conjDep);
addCaseMarkersToReln(sg, caseGovGovCopy, caseGov, caseMarkers);
/* Attach all children except case markers of caseGov to caseGovCopy. */
//for (SemanticGraphEdge e : sg.outgoingEdgeList(caseGov)) {
// if (e.getRelation() != CASE_MARKER && ! e.getDependent().equals(ccDep)) {
// sg.addEdge(caseGovCopy, e.getDependent(), e.getRelation(), Double.NEGATIVE_INFINITY, false);
// }
// }
}
/* Attach CC node to caseGov */
//SemanticGraphEdge edge = sg.getEdge(gov, ccDep);
//sg.removeEdge(edge);
//sg.addEdge(conjGov, ccDep, COORDINATION, Double.NEGATIVE_INFINITY, false);
/* Add conjunction information for these relations already at this point.
* It could be that we add several coordinating conjunctions while collapsing
* and we might not know which conjunction belongs to which conjunct at a later
* point.
*/
addConjToReln(sg, conjGov, newConjDeps, ccDep);
}
private static final SemgrexPattern PP_CONJP_PATTERN = SemgrexPattern.compile("{} >/^(nmod|obl|acl|advcl)$/ (({}=gov >/(case|mark)/ {}) >conj ({} >/(case|mark)/ {} >cc {}=cc) >conj ({}=conj >/(case|mark)/ {}))");
/**
* Expands PPs with conjunctions such as in the sentence
* "Bill flies to France and from Serbia." by copying the verb
* that governs the prepositional phrase resulting in the following
* relations:
* <br>
* {@code conj:and(flies, flies')}<br>
* {@code case(France, to)}<br>
* {@code cc(flies, and)}<br>
* {@code case(Serbia, from)}<br>
* {@code nmod(flies, France)}<br>
* {@code nmod(flies', Serbia)}<br>
* <br>
* The label of the conjunct relation includes the conjunction type
* because if the verb has multiple cc relations then it can be impossible
* to infer which coordination marker belongs to which conjuncts.
*
* @param sg SemanticGraph to operate on.
*/
private static void expandPPConjunctions(SemanticGraph sg) {
/* Semgrexes require a graph with a root. */
if (sg.getRoots().isEmpty())
return;
SemanticGraph sgCopy = sg.makeSoftCopy();
SemgrexMatcher matcher = PP_CONJP_PATTERN.matcher(sgCopy);
IndexedWord oldGov = null;
IndexedWord oldCcDep = null;
List<IndexedWord> conjDeps = Generics.newLinkedList();
while (matcher.find()) {
IndexedWord conjDep = matcher.getNode("conj");
IndexedWord gov = matcher.getNode("gov");
IndexedWord ccDep = matcher.getNode("cc");
if (oldGov != null && (! gov.equals(oldGov) || ! ccDep.equals(oldCcDep))) {
expandPPConjunction(sg, oldGov, conjDeps, oldCcDep);
conjDeps = Generics.newLinkedList();
}
oldCcDep = ccDep;
oldGov = gov;
conjDeps.add(conjDep);
}
if (oldGov != null) {
expandPPConjunction(sg, oldGov, conjDeps, oldCcDep);
}
}
/*
* Used by expandPPConjunction.
*/
private static void expandPPConjunction(SemanticGraph sg, IndexedWord gov,
List<IndexedWord> conjDeps, IndexedWord ccDep) {
IndexedWord nmodGov = sg.getParent(gov);
if (nmodGov == null)
return;
IndexedWord conjGov = nmodGov.getOriginal() != null ? nmodGov.getOriginal() : nmodGov;
GrammaticalRelation rel = sg.reln(nmodGov, gov);
List<IndexedWord> newConjDeps = Generics.newLinkedList();
for (IndexedWord conjDep : conjDeps) {
IndexedWord nmodGovCopy = nmodGov.makeSoftCopy();
/* Change conj(nmod-1, nmod-2) to nmod(nmod-1-gov, nmod-2) */
SemanticGraphEdge edge = sg.getEdge(gov, conjDep);
if (edge != null) {
sg.removeEdge(edge);
sg.addEdge(nmodGovCopy, conjDep, rel, Double.NEGATIVE_INFINITY, false);
}
/* Add relation to copy node. */
sg.addEdge(conjGov, nmodGovCopy, CONJUNCT, Double.NEGATIVE_INFINITY, false);
newConjDeps.add(nmodGovCopy);
/* Attach CC node to nmodGovCopy */
SemanticGraphEdge ccEdge = sg.getEdge(conjDep, ccDep);
if (ccEdge != null) {
sg.removeEdge(ccEdge);
sg.addEdge(nmodGovCopy, ccDep, COORDINATION, Double.NEGATIVE_INFINITY, false);
}
}
/* Add conjunction information for these relations already at this point.
* It could be that we add several coordinating conjunctions while collapsing
* and we might not know which conjunction belongs to which conjunct at a later
* point.
*/
addConjToReln(sg, conjGov, newConjDeps, ccDep);
}
/**
*
* Returns a GrammaticalRelation which combines the original relation and
* the preposition.
*
*/
private static GrammaticalRelation getCaseMarkedRelation(GrammaticalRelation reln, String relationName) {
GrammaticalRelation newReln = reln;
if (reln.getSpecific() != null) {
reln = reln.getParent();
}
if (reln == NOMINAL_MODIFIER) {
newReln = UniversalEnglishGrammaticalRelations.getNmod(relationName);
} else if (reln == OBLIQUE_MODIFIER) {
newReln = UniversalEnglishGrammaticalRelations.getObl(relationName);
} else if (reln == ADV_CLAUSE_MODIFIER) {
newReln = UniversalEnglishGrammaticalRelations.getAdvcl(relationName);
} else if (reln == CLAUSAL_MODIFIER) {
newReln = UniversalEnglishGrammaticalRelations.getAcl(relationName);
}
return newReln;
}
private static final SemgrexPattern CONJUNCTION_PATTERN = SemgrexPattern.compile("{}=gov [>conj ({}=conj >cc {}=cc) | >conj ({} >cc {}=cc) >conj {}=conj ]" );
/**
* Adds the type of conjunction to all conjunct relations.
* <br>
* {@code cc(Marie, and)}, {@code conj(Marie, Chris)} and {@code conj(Marie, John)}
* become {@code cc(Marie, and)}, {@code conj:and(Marie, Chris)} and {@code conj:and(Marie, John)}.
* <br>
* In case multiple coordination marker depend on the same governor
* the one that precedes the conjunct is appended to the conjunction relation or the
* first one if no preceding marker exists.
* <br>
* Some multi-word coordination markers are collapsed to {@code conj:and} or {@code conj:negcc}.
* See {@link #conjValue(IndexedWord, SemanticGraph)}.
*
* @param sg A SemanticGraph from a sentence
*/
private static void addConjInformation(SemanticGraph sg) {
/* Semgrexes require a graph with a root. */
if (sg.getRoots().isEmpty())
return;
SemanticGraph sgCopy = sg.makeSoftCopy();
SemgrexMatcher matcher = CONJUNCTION_PATTERN.matcher(sgCopy);
IndexedWord oldGov = null;
IndexedWord oldCcDep = null;
List<IndexedWord> conjDeps = Generics.newLinkedList();
while (matcher.find()) {
IndexedWord conjDep = matcher.getNode("conj");
IndexedWord gov = matcher.getNode("gov");
IndexedWord ccDep = matcher.getNode("cc");
if (oldGov != null && (! gov.equals(oldGov) || ! ccDep.equals(oldCcDep))) {
addConjToReln(sg, oldGov, conjDeps, oldCcDep);
conjDeps = Generics.newLinkedList();
}
oldCcDep = ccDep;
conjDeps.add(conjDep);
oldGov = gov;
}
if (oldGov != null) {
addConjToReln(sg, oldGov, conjDeps, oldCcDep);
}
}
/*
* Used by addConjInformation.
*/
private static void addConjToReln(SemanticGraph sg,
IndexedWord gov, List<IndexedWord> conjDeps, IndexedWord ccDep) {
for (IndexedWord conjDep : conjDeps) {
SemanticGraphEdge edge = sg.getEdge(gov, conjDep);
if (edge.getRelation() == CONJUNCT || conjDep.index() > ccDep.index()) {
sg.updateEdge(edge, conjValue(ccDep, sg));
}
}
}
/* Used by correctWHAttachment */
private static final SemgrexPattern XCOMP_PATTERN = SemgrexPattern.compile("{}=root >xcomp {}=embedded >/^(dep|obj)$/ {}=wh ?>/(i?obj)/ {}=obj");
/**
* Tries to correct complicated cases of WH-movement in
* sentences such as "What does Mary seem to have?" in
* which "What" should attach to "have" instead of the
* control verb.
*
* @param sg The Semantic graph to operate on.
*/
private static void correctWHAttachment(SemanticGraph sg) {
/* Semgrexes require a graph with a root. */
if (sg.getRoots().isEmpty())
return;
SemanticGraph sgCopy = sg.makeSoftCopy();
SemgrexMatcher matcher = XCOMP_PATTERN.matcher(sgCopy);
while (matcher.findNextMatchingNode()) {
IndexedWord root = matcher.getNode("root");
IndexedWord embeddedVerb = matcher.getNode("embedded");
IndexedWord wh = matcher.getNode("wh");
IndexedWord dobj = matcher.getNode("obj");
/* Check if the object is a WH-word. */
if (wh.tag() != null && wh.tag().startsWith("W")) {
boolean reattach = false;
/* If the control verb already has an object, then
we have to reattach the WH-word to the verb in the embedded clause. */
if (dobj != null) {
reattach = true;
} else {
/* If the control verb can't have an object, we also have to reattach. */
if (root.value() != null && root.tag() != null) {
String lemma = Morphology.lemmaStatic(root.value(), root.tag());
if (lemma != null && lemma.matches(EnglishPatterns.NP_V_S_INF_VERBS_REGEX)) {
reattach = true;
}
}
}
if (reattach) {
SemanticGraphEdge edge = sg.getEdge(root, wh);
if (edge != null) {
sg.removeEdge(edge);
sg.addEdge(embeddedVerb, wh, DIRECT_OBJECT, Double.NEGATIVE_INFINITY, false);
}
}
}
}
}
//TODO: also reattach commas!
private static void fixCCAttachment(SemanticGraph sg) {
HashMap<SemanticGraphEdge, Integer> newHeads = new HashMap<>();
for (SemanticGraphEdge edge : sg.edgeIterable()) {
if (edge.getRelation().equals(UniversalEnglishGrammaticalRelations.COORDINATION)) {
// check if "cc" is attached to previous conjunct
if (edge.getGovernor().index() < edge.getDependent().index()) {
Set<IndexedWord> conjuncts = sg.getChildrenWithReln(edge.getGovernor(), UniversalEnglishGrammaticalRelations.CONJUNCT);
int newHead = Integer.MAX_VALUE;
for (IndexedWord conjunct : conjuncts) {
if (conjunct.index() < newHead && conjunct.index() > edge.getDependent().index()) {
newHead = conjunct.index();
}
}
if (newHead < Integer.MAX_VALUE) {
newHeads.put(edge, newHead);
}
}
}
}
for (Map.Entry<SemanticGraphEdge, Integer> entry : newHeads.entrySet()) {
SemanticGraphEdge edge = entry.getKey();
IndexedWord newGovernor = sg.getNodeByIndex(entry.getValue());
sg.removeEdge(edge);
sg.addEdge(newGovernor, edge.getDependent(), edge.getRelation(), edge.getWeight(), edge.isExtra());
}
}
/**
* What we do in this method is look for temporary dependencies of
* the type "rel" and "prep". These occur in sentences such as "I saw the man
* who you love". In that case, we should produce dobj(love, who).
* On the other hand, in the sentence "... which Mr. Bush was
* fighting for", we should have case(which, for).
*/
private static void convertRel(SemanticGraph sg) {
for (SemanticGraphEdge prep : sg.findAllRelns(PREPOSITION)) {
boolean changedPrep = false;
for (SemanticGraphEdge nmod : sg.outgoingEdgeIterable(prep.getGovernor())) {
// todo: It would also be good to add a rule here to prefer ccomp nsubj over dobj if there is a ccomp with no subj
// then we could get right: Which eco-friendly options do you think there will be on the new Lexus?
if (nmod.getRelation() != NOMINAL_MODIFIER && nmod.getRelation() != RELATIVE && nmod.getRelation() != OBLIQUE_MODIFIER) {
continue;
}
if (prep.getDependent().index() < nmod.getDependent().index()) {
continue;
}
sg.removeEdge(prep);
sg.addEdge(nmod.getDependent(), prep.getDependent(), CASE_MARKER, Double.NEGATIVE_INFINITY, false);
changedPrep = true;
if (nmod.getRelation() == RELATIVE) {
if (nmod.getGovernor().tag().startsWith("NN")
|| nmod.getGovernor().tag().startsWith("PRN")
|| nmod.getGovernor().tag().startsWith("DT")) {
sg.updateEdge(nmod, NOMINAL_MODIFIER);
} else {
sg.updateEdge(nmod, OBLIQUE_MODIFIER);
}
}
break;
}
if (!changedPrep) {
sg.updateEdge(prep, OBLIQUE_MODIFIER);
}
}
/* Rename remaining "rel" relations. */
for (SemanticGraphEdge edge : sg.findAllRelns(RELATIVE)) {
sg.updateEdge(edge, DIRECT_OBJECT);
}
}
/**
* Manipulates the given SemanticGraph to add enhancements. Note that this modifies the input graph.
*/
public static void addEnhancements(SemanticGraph sg, EnhancementOptions options) {
if (DEBUG) {
printListSorted("addEnhancements: before correctDependencies()", sg.typedDependencies());
}
correctDependencies(sg);
if (DEBUG) {
printListSorted("addEnhancements: after correctDependencies()", sg.typedDependencies());
}
/* Turn multi-word prepositions into flat mwe. */
if (options.processMultiWordPrepositions) {
processMultiwordPreps(sg);
if (DEBUG) {
printListSorted("addEnhancements: after processMultiwordPreps()", sg.typedDependencies());
}
}
/* Turn quantificational modifiers into flat mwe. */
if (options.demoteQuantMod) {
demoteQuantificationalModifiers(sg);
if (DEBUG) {
printListSorted("addEnhancements: after demoteQuantificationalModifiers()", sg.typedDependencies());
}
}
/* Add copy nodes for conjoined Ps and PPs. */
if (options.addCopyNodes) {
expandPPConjunctions(sg);
if (DEBUG) {
printListSorted("addEnhancements: after expandPPConjunctions()", sg.typedDependencies());
}
expandPrepConjunctions(sg);
if (DEBUG) {
printListSorted("addEnhancements: after expandPrepConjunctions()", sg.typedDependencies());
}
}
/* Add propositions to relation names. */
if (options.enhancePrepositionalModifiers) {
addCaseMarkerInformation(sg, options.enhanceOnlyNmods);
if (DEBUG) {
printListSorted("addEnhancements: after addCaseMarkerInformation()", sg.typedDependencies());
}
}
/* Add coordinating conjunctions to relation names. */
if (options.enhanceConjuncts) {
addConjInformation(sg);
if (DEBUG) {
printListSorted("addEnhancements: after addConjInformation()", sg.typedDependencies());
}
}
/* Add "referent" relations. */
if (options.addReferent) {
addRef(sg);
if (DEBUG) {
printListSorted("addEnhancements: after addRef()", sg.typedDependencies());
}
collapseReferent(sg);
if (DEBUG) {
printListSorted("addEnhancements: after collapseReferent()", sg.typedDependencies());
}
}
/* Propagate dependents. */
if (options.propagateDependents) {
treatCC(sg);
if (DEBUG) {
printListSorted("addEnhancements: after treatCC()", sg.typedDependencies());
}
}
/* Add relations between controlling subjects and controlled verbs. */
if (options.addXSubj) {
addExtraNSubj(sg);
if (DEBUG) {
printListSorted("addEnhancements: after addExtraNSubj()", sg.typedDependencies());
}
}
correctSubjPass(sg);
}
@Override
protected void addEnhancements(List<TypedDependency> list, EnhancementOptions options) {
SemanticGraph sg = new SemanticGraph(list);
addEnhancements(sg, options);
list.clear();
list.addAll(sg.typedDependencies());
Collections.sort(list);
}
/**
* Destructively modifies this {@code Collection<TypedDependency>}
* by collapsing several types of transitive pairs of dependencies or
* by adding additional information from the dependents to the relation
* of the governor.
* If called with a tree of dependencies and both CCprocess and