-
Notifications
You must be signed in to change notification settings - Fork 0
/
top.js
2190 lines (1974 loc) · 74.8 KB
/
top.js
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
if(typeof window === "undefined"){
window = {};
}
(function() {
window.GEN_impl = function(sTree, leaves, options) {
var recursiveOptions = {};
for (var k in options) {
if (options.hasOwnProperty(k) && k !== 'requireRecWrapper')
recursiveOptions[k] = options[k];
}
/* if rootCategory and recursiveCategory are the same, we don't want to call
* addRecCatWrapped because half of the candidates will have a root node with
* only one child, which will be of the same category, ie. {i {i (...) (...)}}
*/
var rootlessCand = gen(leaves, recursiveOptions)
if(options.rootCategory !== options.recursiveCategory){
rootlessCand = addRecCatWrapped(gen(leaves, recursiveOptions), options);
}
var candidates = [];
for(var i=0; i<rootlessCand.length; i++){
var pRoot = wrapInRootCat(rootlessCand[i], options);
if (!pRoot)
continue;
if (options.obeysHeadedness && !obeysHeadedness(pRoot))
continue;
candidates.push([sTree, pRoot]);
}
return candidates;
}
/* Function to check if a tree obeys headedness. Each node must either be be
* terminal or have at least one child of the category immidately below its own
* on the prosodic hierarch. Otherwise, return false. Written as a recursive
* function, basically a constraint.
*/
function obeysHeadedness(tree){
//inner function
function nodeIsHeaded(node) {
/* Function to check if a node is headed. Relies on the prosodic hierarchy being
* properly defined. Returns true iff
* a. one of the node's children is of the category directly below its own category * on the prosodic hierarchy,
* b. one of the node's descendants is of the same category as the node
* c. the node is terminal.
*/
var children = node.children;
//vacuously true if node is terminal
if (!children)
return true;
for (var i = 0; i < children.length; i++)
if (children[i].cat === pCat.nextLower(node.cat)
|| children[i].cat === node.cat){
return true;
}
return false;
}
//outer function
//first, check the parent node
if (!nodeIsHeaded(tree))
return false;
//return false if one of the children does not obey headedness
if (tree.children){
for (var x = 0; x<tree.children.length; x++){
if (!obeysHeadedness(tree.children[x])) //recursive function call
return false;
}
}
//if we get this far, the tree obeys headedness
return true;
}
function obeysExhaustivity(cat, children) {
for (var i = 0; i < children.length; i++)
if (cat !== children[i].cat && pCat.nextLower(cat) !== children[i].cat){
return false;
}
return true;
}
function wrapInRootCat(candidate, options){
if (options && options.obeysExhaustivity){ // check that options.obeysExhaustivity is defined
if(typeof options.obeysExhaustivity ==="boolean" && options.obeysExhaustivity && !obeysExhaustivity(options.rootCategory, candidate)){
return null;
}
else if (options.obeysExhaustivity instanceof Array && options.obeysExhaustivity.indexOf(options.rootCategory)>=0 && !obeysExhaustivity(options.rootCategory, candidate)){
return null;
}
}
if(candidate.length < 2 && options.rootCategory === candidate[0].cat){
return null;
}
//if we get here, there aren't any relevant exhaustivity violations
return {id: 'root', cat: options.rootCategory, children: candidate};
}
/*Conceptually, returns all possible parenthesizations of leaves that don't
* have a set of parentheses enclosing all of the leaves
* Format: returns an array of parenthesizations, where each parenthesization
* is an array of children, where each child is
* either a node of category recursiveCategory (with descendant nodes attached)
* or a leaf (of category terminalCategory)
* Options:
*/
function gen(leaves, options){
var candidates = []; //each candidate will be an array of siblings
var cand;
if(!(leaves instanceof Array))
throw new Error(leaves+" is not a list of leaves.");
//Base case: 0 leaves
if(leaves.length === 0){
candidates.push([]);
return candidates;
}
//Recursive case: at least 1 terminal. Consider all candidates where the first i words are grouped together
for(var i = 1; i <= leaves.length; i++){
//First, create the right sides:
var rightLeaves = leaves.slice(i, leaves.length);
//recursion at top level
//var test_output = gen(rightLeaves,options);
var rightsides = addRecCatWrapped(gen(rightLeaves, options), options);
/*if(options.noUnary){
//console.log("gen:",test_output);
//console.log("rightsides:",rightsides);
};*/
//recursion at lower levels
if(pushRecCat(options)){
var wRightsides = addRecCatWrapped(gen(rightLeaves, options), options);
rightsides.concat(wRightsides);
popRecCat(options);
}
//Then create left sides and combine them with the right sides.
//Case 1: the first i leaves attach directly to parent (no wrapping in a recursive category)
var leftside = leaves.slice(0,i);
// We don't need to check the left side for nonrecursivity, because it's all leaves
//Combine the all-leaf leftside with all the possible rightsides that have a phi at their left edge (or are empty)
for(var j = 0; j<rightsides.length; j++){
var currRightside = rightsides[j];
var firstRight = currRightside[0];
if(!currRightside.length || (firstRight.children && firstRight.children.length) || (firstRight.cat != options.terminalCategory && !isLower(pCat, firstRight.cat, options.terminalCategory)))
{
cand = leftside.concat(currRightside);
candidates.push(cand);
}
}
if(i<leaves.length){
if(options.noUnary && i<2){
continue;
//Don't generate any candidates where the first terminal is in an intermediate level node by itself.
}
//Case 2: the first i words are wrapped in an intermediate level node
//Case 2a: first recursive category
var phiLeftsides = gen(leaves.slice(0,i), options);
for(var k = 0; k<phiLeftsides.length; k++)
{
var phiNode = wrapInRecCat(phiLeftsides[k], options);
if (!phiNode){
continue;
}
var leftside = [phiNode];
for(var j = 0; j<rightsides.length; j++)
{
cand = leftside.concat(rightsides[j]);
candidates.push(cand);
}
}
//Case 3
//Try to build left-sides that are wrapped in the next lower recursive category but aren't wrapped in the current recursive category
if(pushRecCat(options)){
var wLeftsides = gen(leaves.slice(0,i), options);
for(var k = 0; k<wLeftsides.length; k++){
var wLeftside = wrapInRecCat(wLeftsides[k], options);
if(wLeftside){
//console.log(i, "wLeftside:", wLeftside);
//Combine the all-leaf leftside with all the possible rightsides that aren't empty
for(var j = 0; j<rightsides.length; j++){
if(rightsides[j].length)
{
cand = [wLeftside].concat(rightsides[j]);
candidates.push(cand);
}
}
}
}
popRecCat(options);
}
}
}
//Now try to use recursion at the next recursive category
if (pushRecCat(options)) {
var wCands = gen(leaves, options);
//Add things that are entirely wrapped in [ ]
for (var i = 0; i < wCands.length; i++) {
cand = wCands[i];
var wrappedCand = wrapInRecCat(cand, options);
if(wrappedCand)
candidates.push([wrappedCand]);
}
popRecCat(options);
}
return candidates;
}
function wrapInRecCat(candidate, options){
// Check for Exhaustivity violations below the phi, if phi is listed as one of the exhaustivity levels to check
if (options && options.obeysExhaustivity){
if ((typeof options.obeysExhaustivity === "boolean" || options.obeysExhaustivity.indexOf(options.recursiveCategory)>=0) && !obeysExhaustivity(options.recursiveCategory, candidate))
return null;
}
if (options && options.obeysNonrecursivity){
for (var i = 0; i < candidate.length; i++)
if (candidate[i].cat === options.recursiveCategory){
return null;
}
}
if (options && options.noUnary && candidate.length === 1){
return null;
}
// Don't wrap anything in a recursive category that is already wrapped in one
if (candidate.length === 1 && (candidate[0] && candidate[0].cat === options.recursiveCategory)){
if(candidate[0].cat==='phi')
console.log("wrapInRecCat", options.recursiveCategory, candidate);
//console.log("Not wrapping ", candidate);
return null;
}
return {id: options.recursiveCategory+(options.counters.recNum++), cat: options.recursiveCategory, children: candidate};
}
//Takes a list of candidates and doubles it to root each of them in a phi
//If options.noUnary, skip wrapInRecCat-ing candidates that are only 1 terminal long
function addRecCatWrapped(candidates, options){
var origLen = candidates.length;
var result = [];
if (!options.requireRecWrapper) {
result = candidates;
}
for(var i=0; i<origLen; i++){
var candLen = candidates[i].length;
if(candLen) {
var phiNode = wrapInRecCat(candidates[i], options);
if (phiNode){
result.push([phiNode]);
}
}
}
return result;
}
//Move to the next recursive category, if there is one.
function pushRecCat(options){
var nextIndex = options.recursiveCatIndex + 1;
if(nextIndex > options.recursiveCats.length-1){
return false;
}
else{
var nextRecCat = options.recursiveCats[nextIndex];
options.recursiveCategory = nextRecCat;
options.recursiveCatIndex = nextIndex;
return true;
}
}
//Move to the previous recursive category, if there is one.
function popRecCat(options){
var prevIndex = options.recursiveCatIndex - 1;
if(prevIndex < 0){
return false;
}
else{
var prevRecCat = options.recursiveCats[prevIndex];
options.recursiveCategory = prevRecCat;
options.recursiveCatIndex = prevIndex;
return true;
}
}
})();
/* Takes a list of words and returns the candidate set of trees (JS objects)
Options is an object consisting of the parameters of GEN. Its properties can be:
- obeysExhaustivity (boolean or array of categories at which to require conformity to exhaustivity)
- obeysHeadedness (boolean)
- obeysNonrecursivity (boolean)
- rootCategory (string)
- recursiveCategory (string) --> '-' separated list of categories, from highest to lowest (e.g. 'phi-w', not 'w-phi')
-> saved in recursiveCats (see below) + becomes a string rep of the current recursive category
- terminalCategory (string)
- recursiveCatIndex (int): tracks which recursive category we're currently using
- recursiveCats (list of strings): list of recursive categories to use
- addTones (string). Possible values include:
- "addJapaneseTones"
- "addIrishTones_Elfner"
- "addIrishTones_Kalivoda"
- noUnary (boolean): if true, don't create any nodes that immediately dominate only a single node.
- maxBranching (numeric): maximum number of children that any node in the tree can have
- requireRecWrapper (boolean). Formerly "requirePhiStem"
- syntactic (boolean): are we generating syntactic trees?
- ph (prosodic heirarchy object):
pCat: custom pCat used in GEN
categoryPairings: custom category pairings passed to makeTableau passed to constraints
*/
window.GEN = function(sTree, words, options){
options = options || {}; // if options is undefined, set it to an empty object (so you can query its properties without crashing things)
//Set prosodic hierarchy if we're making prosodic trees. Don't bother with this for syntactic trees.
if(!options.syntactic){
// Create the ph object if none was passed or what was passed was incomplete, and set it the default PH object, defined in prosodicHierarchy.js
if (!(options.ph && options.ph.pCat && options.ph.categoryPairings)){
options.ph = PH_PHI;
//console.log("The prosodic hierarchy input to GEN was missing or incomplete, so ph has been set by default to PH_PHI, defined in prosodicHierarchy.js");
}
setPCat(options.ph.pCat);
setCategoryPairings(options.ph.categoryPairings);
// give a warning if there are categories from categoryPairings not present in pCat
if (!checkProsodicHierarchy(options.ph.pCat, options.ph.categoryPairings)){
displayWarning("One or more categories in the provided map of syntactic-prosodic correspondences (categoryPairings) do not exist in the provided prosodic hierarchy (pCat). Resetting pCat and categoryPairings to their default values, defined in PH_PHI.");
//set pCat and categoryPairings to their default values
resetPCat();
resetCategoryPairings();
options.ph = PH_PHI;
}
}
//Set the relevant category hierarchy (syntactic or prosodic) based on the GEN option syntactic
var categoryHierarchy = options.syntactic ? sCat : pCat;
var defaultRecCat = options.syntactic ? "xp" : "phi"; //sets the default of recursiveCategory option to "phi" if prosodic, "xp" if syntactic
options.recursiveCategory = options.recursiveCategory || defaultRecCat;
// Check for multiple recursive categories
if(options.recursiveCategory && options.recursiveCategory.length){
if(typeof options.recursiveCategory === "string"){
var recCats = options.recursiveCategory.split('-');
}
else {
var recCats = [];
for(var i = 0; i<options.recursiveCategory.length; i++){
recCats = recCats.concat(options.recursiveCategory[i]);
}
}
if(recCats.length > 1){
//console.log(recCats);
options.recursiveCatIndex = 0;
//Set current recursiveCategory
options.recursiveCategory = recCats[options.recursiveCatIndex];
//Save list of all categories
options.recursiveCats = recCats;
}
if(recCats.length > 2){
this.alert("You have entered more than 2 recursive categories!")
}
}
if(!options.recursiveCats){
options.recursiveCats = [options.recursiveCategory];
}
//Point to first recursiveCat
options.recursiveCatIndex = 0;
/* First, warn the user if they have specified terminalCategory and/or
* rootCategory without specifying recursiveCategory
*/
if(!options.recursiveCategory && (options.rootCategory || options.terminalCategory)){
if(!window.confirm("You have not specified the recursive category for GEN, it will default to "+ defaultRecCat +".\nClick OK if you wish to continue."))
throw new Error("GEN was canceled by user.");
}
/* the prosodic hierarchy should include the categories specified in
* options.rootCategory, options.recursiveCategory and options.terminalCategory
* But if they are not, the default setting code throws unhelpful errors.
* The finally block throws more helpful errors and alert boxes instead
*/
//a flag for whether the user has included a novel category undefined in categoryHierarchy
var novelCategories = false;
try{
options.recursiveCategory = options.recursiveCategory || defaultRecCat;
//sets the default of rootCategory based on recursiveCategory
options.rootCategory = options.rootCategory || categoryHierarchy.nextHigher(options.recursiveCategory);
//sets the default of terminalCategory based on recursiveCategory
options.terminalCategory = options.terminalCategory|| categoryHierarchy.nextLower(options.recursiveCategory);
}
finally{
var novelCatWarning = " is not a valid category with the current settings.\nCurrently valid prosodic categories: " + JSON.stringify(pCat) + "\nValid syntactic categories: " + JSON.stringify(sCat);
//private function to avoid code duplication in warning about novel recursive cats
function novelRecursiveCatEval(recCat){
if(categoryHierarchy.indexOf(recCat)<0){
var err = new Error("Specified recursive category "+recCat+novelCatWarning);
displayError(err.message, err);
novelCategories = true;
throw err;
}
}
if(options.rootCategory && categoryHierarchy.indexOf(options.rootCategory)<0){
var err = new Error("Specified root category "+options.recursiveCategory+novelCatWarning);
displayError(err.message, err);
novelCategories = true;
throw err;
}
//Throw an error for any specified recursive category(s) that are valid.
//if...else structure because there could be more than 1 recursive cat:
//Multiple recursive cats: options.recursiveCats is only defined if options.recursiveCategory contained a hyphen and has been split (line 62 above).
if(options.recursiveCats && options.recursiveCats.length){
for(let i in options.recursiveCats){
novelRecursiveCatEval(options.recursiveCats[i]);
}
}
//Only one recursive cat
else{
novelRecursiveCatEval(options.recursiveCategory);
}
// Throws an error for the defined terminal category if it is not a valid category.
// Don't check terminal category if we're building syntactic trees.
if(!options.syntactic && options.terminalCategory && categoryHierarchy.indexOf(options.terminalCategory)<0){
var err = new Error("Specified terminal category "+options.recursiveCategory+novelCatWarning);
displayError(err.message, err);
novelCategories = true;
throw err;
}
}
//Warnings for adverse GEN options combinations:
if(options.rootCategory === options.recursiveCategory && options.obeysNonrecursivity){
displayWarning("You have instructed GEN to produce non-recursive trees and to produce trees where the root node and intermediate nodes are of the same category. Some of the trees GEN produces will be recursive.");
}
if(options.rootCategory === options.terminalCategory && options.obeysNonrecursivity){
displayWarning("You have instructed GEN to produce non-recursive trees and to produce trees where the root node and terminal nodes are of the same category. All of the trees GEN produces will be recursive.");
}
if(options.recursiveCategory === options.terminalCategory && options.obeysNonrecursivity){
displayWarning("You have instructed GEN to produce non-recursive trees and to produce trees where the intermediate nodes and the terminal nodes are of the same category. You will only get one bracketing.");
}
//Perform additional checks of layering if novel categories are not involved.
if(!novelCategories){
if(categoryHierarchy.isHigher(options.recursiveCategory, options.rootCategory) || categoryHierarchy.isHigher(options.terminalCategory, options.recursiveCategory)){
displayWarning("You have instructed GEN to produce trees that do not obey layering. See pCat and sCat in prosodicHierarchy.js");
}
else{
//Check that the highest recursive category is immediately below the selected root category.
if(options.recursiveCategory !== categoryHierarchy.nextLower(options.rootCategory) && options.recursiveCategory !== options.rootCategory)
{
displayWarning(""+options.recursiveCategory+" is not directly below "+options.rootCategory+" in the prosodic hierarchy. None of the resulting trees will be exhaustive because GEN will not generate any "+categoryHierarchy.nextLower(options.rootCategory)+"s. See pCat and sCat in prosodicHierarchy.js");
}
//Check that the lowest recursive category is immediately above the chosen terminal category.
if(!options.recursiveCats){
options.recursiveCats = [options.recursiveCategory];
}
var lowestRecCat = options.recursiveCats[options.recursiveCats.length-1];
if(options.terminalCategory !== categoryHierarchy.nextLower(lowestRecCat) && options.terminalCategory !== lowestRecCat){
displayWarning(""+options.terminalCategory+" is not directly below "+lowestRecCat+" in the prosodic hierarchy. None of the resulting trees will be exhaustive because GEN will not generate any "+categoryHierarchy.nextLower(lowestRecCat)+"s. Current pCat: "+pCat);
}
}
}
if(typeof words === "string") { // words can be a space-separated string of words or an array of words; if string, split up into an array
if (!words) { // if empty, scrape words from sTree
if(sTree.cat && sTree.id){
words = getLeaves(sTree);
}
else{
let message = "window.GEN() was called no valid input!";
displayError(message);
return [];
}
} else {
words = words.split(' ');
words = deduplicateTerminals(words);
}
} else {
words = deduplicateTerminals(words);
}
var leaves = [];
options.counters = {
recNum: 0
}
for(var i=0; i<words.length; i++){
leaves.push(wrapInLeafCat(words[i], options.terminalCategory, options.syntactic));
}
return window.GEN_impl(sTree, leaves, options);
}
function deduplicateTerminals(terminalList) {
//Check for duplicate words
var occurrences = {};
var dedupedTerminals = [];
for(var i=0; i<terminalList.length; i++){
var t = terminalList[i];
//If this is the first occurrence of t, don't append an index
if(!occurrences.hasOwnProperty(t)){
dedupedTerminals.push(t);
occurrences[t] = 1;
}
// If we've seen t before, then add an index to it such that the 2nd occurrence of t
// becomes t_1.
else{
dedupedTerminals.push(t+'_'+occurrences[t]);
occurrences[t] = occurrences[t] + 1;
}
}
return dedupedTerminals;
}
/** Function to take a string and category and return an object wordObj with attributes
* wordObj.id = word
* wordObj.cat = cat
*
* Also convert hyphenated information about accent and status as a clitic that is
* appended to the word argument to attributes of wordObj.
*
* If input word is already an object, return it after checking its category.
* - if word.cat == cat, return as is
* - if word.cat == "clitic" and syntactic==true, create an x0 layer over the clitic
* - if word.cat == "clitic" and syntactic==false, change word.cat to "syll"
* - if word.cat != cat, and word.cat != clitic, change word.cat to cat.
*/
function wrapInLeafCat(word, cat, syntactic){
var wordObj;
//If word is already an object with appropriate properties, then check categories and return.
if(typeof word === "object"){
if(word.cat && word.id){
wordObj = JSON.parse(JSON.stringify(word)); //deep copy shortcut
//convert "clitic" to "syll" if we're making a prosodic tree
if(wordObj.cat==="clitic"){
if(!syntactic){
wordObj.cat = "syll";
}
else{ //if it's a clitic and we're making syntactic trees, then give it an x0 layer
var cliticObj = wordObj;
wordObj = addParent(cliticObj);
}
}
//otherwise change cat to the specified cat if they don't match
else if (wordObj.cat !== cat){
wordObj.cat = cat;
}
return wordObj;
}
else displayWarning("wrapInLeafCat: argument word is already an object but lacks an id or cat.");
}
//Otherwise, word is a string and must be converted into an object.
else{
var myCat = cat || 'w'; //by default, the leaf category is 'w'
var wordId = word;
//check if the input specifies this is a clitic and set category appropriately
var isClitic = word.indexOf('-clitic')>=0;
if (isClitic){
myCat = syntactic ? 'clitic' : 'syll'; //syntactic tree vs prosodic trees
wordId = wordId.split('-clitic')[0];
}
wordObj = {cat: myCat};
//check if the input specifies this is an accented word, and set accent to true if so
if(word.indexOf('-accent') >= 0){
wordObj.accent = true;
wordId = wordId.split('-accent')[0];
}
wordObj.id = wordId;
//add an x0 layer if this is a (syntactic) clitic
if(myCat==="clitic"){
wordObj = addParent(wordObj);
}
return wordObj;
}
}
function addParent(child, parentCat="x0", parentId="clitic_x0"){
return {cat:parentCat, id:parentId, children:[child]};
}
function containsClitic(x) {
return x.indexOf("clitic") > -1;
}
function generateWordOrders(wordList, clitic) {
if (typeof wordList === 'string') {
var cliticTagIndex = wordList.indexOf("-clitic");
if (cliticTagIndex > 0) {
var wordListParts = wordList.split("-clitic");
wordList = wordListParts[0] + wordListParts[1];
}
wordList = wordList.split(' ');
}
//Find the clitic to move around
var cliticIndex = wordList.indexOf(clitic);
try {
if (cliticIndex < 0)
throw new Error("The provided clitic " + clitic + " was not found in the word list");
}
catch(err) {
displayError(err.message, err);
}
//Slice the clitic out
var beforeClitic = wordList.slice(0, cliticIndex);
var afterClitic = wordList.slice(cliticIndex + 1, wordList.length);
var cliticlessWords = beforeClitic.concat(afterClitic);
var orders = new Array(wordList.length);
for (var i = 0; i <= cliticlessWords.length; i++) {
beforeClitic = cliticlessWords.slice(0, i);
afterClitic = cliticlessWords.slice(i, cliticlessWords.length);
orders[i] = beforeClitic.concat([clitic + "-clitic"], afterClitic);
}
return orders;
}
/* Arguments:
stree: a syntatic tree, with the clitic marked as cat: "clitic"
words: optional string or array of strings which are the desired leaves
options: options for GEN
Returns: GEN run on each possible order of the words, where possible orders
are those where terminals other than the clitic remian in place but the clitic can occupy any position.
Caveat: If there are multiple clitics, only the first will be moved.
*/
function GENwithCliticMovement(stree, words, options) {
if(!words && (!stree.cat || !stree.id)){
displayError("GENwithCliticMovement was called with no valid input!");
return [];
}
// Identify the clitic of interest
var clitic = '';
// First try to read words and clitic off the tree
var leaves = getLeaves(stree);
if (leaves.length > 0 && leaves[0].id) {
//console.log(leaves);
var leaf = 0;
while (clitic === '' && leaf < leaves.length) {
if (leaves[leaf].cat === "clitic")
clitic = leaves[leaf].id;
leaf++;
}
if (clitic === '') {
displayWarning("You selected GEN settings that move clitics, but one or more input trees do not have a clitic lableled.");
return GEN(stree, words, options);
//throw new Error("GENWithCliticMovement was called but no node in stree has category clitic was provided in stree");
}
}
//Otherwise, get the clitic from words
else {
// Make sure words is an array
if (typeof words === "string") {
words = words.split(' ');
}
var x = words.find(containsClitic);
if (!x) { //x is undefined if no word in "words" contains "clitic"
displayWarning("You selected GEN settings that move clitics, but one or more input trees do not have a clitic lableled.");
return GEN(stree, words, options);
}
clitic = x.split('-clitic')[0];
words[words.indexOf(x)] = clitic;
}
//Make sure words is defined before using it to generate word orders
if (!words || words.length < leaves.length) {
words = new Array(leaves.length);
for (var i in leaves) {
words[i] = leaves[i].id;
}
}
var wordOrders = generateWordOrders(words, clitic);
var candidateSets = new Array(wordOrders.length);
for (var i = 0; i < wordOrders.length; i++) {
candidateSets[i] = GEN(stree, wordOrders[i], options);
}
//candidateSets;
return [].concat.apply([], candidateSets);
}
/**
* GENwithPermutation: function that takes an stree or a list of words and returns a set of candidates
* <input, output> in which input = stree and the outputs are GEN run on all orders of the words.
* Word orders are computed using Heap's algorithm, implemented in allOrdersInner().
*
* @param {*} stree A syntactic tree to use as the input in the candidate pairs <input, output>
* @param {*} words A list of words. Can be a string of space-separated words, or an array of words
* @param {*} options An object of options to pass along to GEN()
*/
//If both an stree and words are provided, words take priority.
function GENwithPermutation(stree, words, options){
options = options || {};
var leaves = getLeaves(stree);
if(!leaves[0].cat){
leaves = [];
}
var permutations = [];
var words = words || [];
//function for swapping elements in an array, takes array and indexes of elements to be swapped
function swap(array, index1, index2){
var swapped = [];
for(var i = 0; i<array.length; i++){
if(i === index1){
swapped.push(array[index2]);
}
else if(i === index2){
swapped.push(array[index1]);
}
else{
swapped.push(array[i]);
}
}
return swapped;
}
//actual implementation of Heap's algorithm
function allOrdersInner(innerList, k){
if(k == 1){
permutations.push(innerList);
}
else{
allOrdersInner(innerList, k-1); //recursive function call
for(var i = 0; i < k-1; i++){
if(k%2 === 0){
//swap innerList[i] with innerList[k-1]
allOrdersInner(swap(innerList, 0, k-1), k-1); //recursive function call
}
else {
//swap innerList[0] with innerList[k-1]
allOrdersInner(swap(innerList, i, k-1), k-1); //recursive function call
}
}
}
}
// Make sure words is an array
if (typeof words === "string") {
words = words.split(' ');
if (words[0] === ""){
words = [];
}
}
//Make sure words is defined before using it to generate word orders
//Display warning if:
// -There are no words or leaves
// -There are mismatching words and leaves
if(!words.length && !leaves.length){
displayWarning("GENwithPermutation() was not given any syntactic tree or words to permute.");
return '';
}
else if(words.length && leaves.length && leaves.length !== words.length){
displayWarning("The arguments words and stree to GENwithPermutation() are mismatched. The function will use words and ignore the stree.");
}
else if(!words.length && leaves.length){
words = new Array(leaves.length);
for(var i in leaves){
words[i] = leaves[i].id;
}
}
allOrdersInner(words, words.length);
var candidateSets = [];
for(var i = 0; i<permutations.length; i++){
candidateSets[i] = GEN(stree, permutations[i], options);
}
//candidateSets;
return [].concat.apply([], candidateSets);
}
/* Add minimal phi heads
Takes list of ptrees and returns list of all possible iterations of input such that
each minimal phi in the input has a left- or right-aligned head
Max Tarlov 12/2020
*/
// Make a deep copy of a tree node
function copyNode(node) {
if (node === null || typeof node !== 'object') {
return node;
}
let result = node.constructor();
for (var key in node) {
result[key] = copyNode(node[key]);
}
return result;
}
// Takes node and returns true if any of node's children had a true 'head' attribute
function isHeaded(node) {
let result = false;
for (let child of node.children) {
if (child.head) {
result = true;
}
}
return result;
}
// Accept node and add attribute head: true to the leftmost child
function addLeftHead(node) {
if(node.children && node.children.length) {
node.children[0].head = true;
}
return node;
}
// Accept node and add attribute head: true to the rightmost child
function addRightHead(node) {
if(node.children && node.children.length){
node.children[node.children.length - 1].head = true;
}
return node;
}
// take tree and return minimal nodes of specified category
function getMinimalNodes(root, cat='phi') {
let result = [];
function getNodesInner(node) {
if(node.children && node.children.length) {
for(let child of node.children) {
getNodesInner(child);
}
}
if(isMinimal(node) && node.cat == cat) {
result.push(node);
}
}
getNodesInner(root);
return result;
}
/** Function that takes a single tree
* and returns a list of trees consisting of all permutations
* of edge-aligned head placements for minimal nodes of category cat
* */
function genHeadsForTree(ptree, cat='phi') {
let result = [];
//add left heads to all minimalNodes
let localCopy = copyNode(ptree);
const minimals = getMinimalNodes(localCopy, cat);
for(let node of minimals) {
addLeftHead(node);
}
result.push(localCopy);
//progressively change minimal nodes to right-headed for all combinations
for(let i = 0; i < minimals.length; i++) {
const resultLength = result.length; //note that the length of result increases with each iteration of the outer for-loop
for(let j = 0; j < resultLength; j++) {
localCopy = copyNode(result[j]);
let thisMinimal = getMinimalNodes(localCopy, cat)[i];
if(thisMinimal.children && thisMinimal.children.length > 1) {
// Skip unary nodes to avoid duplicate trees
thisMinimal.children[0].head = false;
addRightHead(thisMinimal);
result.push(localCopy);
}
}
}
return result;
}
/** Main function.
*
* Arguments:
* - treeList: a list of trees, or a list of pairs of trees (GEN output)
* - cat: a category to pass along to addHeadsTo()
*
* Returns: a list of all combinations of left- and right-headed minimal
* nodes of category 'cat' for each tree. If treeList is a list of pairs of
* trees, the return value will also be a list of pairs of trees, preserving
* the inputs and iterating through the possible headed outputs.
*
* Helper functions: addHeadsTo()
*/
function genHeadsForList(treeList, cat='phi') {
let result = [];
for(let tree of treeList) {
if(tree.length && tree.length === 2) // treeList is a list of pairs of trees (GEN output)
{
let headedTrees = genHeadsForTree(tree[1], cat);
var interimResult = [];
for(let ht in headedTrees){
interimResult.push([tree[0], headedTrees[ht]]); //push the pair [stree, headedPTree]
}
result = result.concat(interimResult);
}
else if(tree.cat) // treeList's elements are plain trees, not pairs of trees
{
result = result.concat(genHeadsForTree(tree, cat));
}
else throw new Error("addMinimalNodeHeads(treeList, cat): Expected treeList to be a list of pairs of trees or a list of trees.");
}
return result;
}/* Function that calls GEN from candidategenerator.js to generate syntactic input trees
* rather than output prosodic trees.
* By default, this creates unary and binary-branching strees rooted in xp, with all terminals mapped to x0.
* Intermediate levels are xps, and structures of the form [x0 x0] are excluded as being
* syntactically ill-formed, since they only arise from head movement.
*
* Options:
* - rootCategory: default = 'xp'
* - recursiveCategory: default = 'xp'
* - terminalCategory: default = 'x0'
* - noAdjacentHeads: are x0 sisters allowed? [x0 x0]. Defaults to true.
* - noAdjuncts: are xp sisters allowed? [xp xp]. Defaults to false.
* - maxBranching: determines the maximum number of branches that are tolerated in
* the resulting syntactic trees. Default = 2
* - minBranching: determines the maximum number of branches that are tolerated in
* the resulting syntactic trees. Default = 2
* - noBarLevels: if false (default), bar levels are treated as phrasal.
* If true, bar levels are not represented, and ternary branching is permitted.
* - addClitics: 'right' or 'left' determines whether clitics are added on the
* righthand-side or the left; true will default to right. false doesn't add any clitics.
* Default false.
* - cliticsAreBare: false by default. If false, clitics will be wrapped in unary XPs.
* If true, clitics will not be wrapped in XPs, but will be bare heads with category clitic.
* - cliticsInsideFirstRoot: false by default. If true, clitics are positioned "inside" the highest
* XP as sister to an invisible X' layer. Otherwise, clitics are sister to the highest XP.
* - headSide: 'right', 'left', 'right-strict', 'left-strict'.
* Which side will heads be required to be on, relative to their complements?
* Also, must heads be at the very edge (strict)?
* Also has all the options from the underlying output candidate generator -- see
* GEN() in candidategenerator.js. Most relevant is probably noUnary which excludes
* non-branching intermediate nodes.
*/
function sTreeGEN(terminalString, options)
{
options = options || {};
// Options that default to true
if(options.noAdjacentHeads === undefined){
options.noAdjacentHeads = true;
}
options.syntactic = true;
options.recursiveCategory = options.recursiveCategory || 'xp';
options.terminalCategory = options.terminalCategory || 'x0';
options.rootCategory = options.rootCategory || 'xp';
// If bar levels are not treated as phrasal, then we need to allow ternary XPs and CPs, but not ternary x0s.
// Furthermore, clitics should be positioned in the "specifier", as a daughter to the existing root, not a sister.
if(options.cliticsInsideFirstRoot){
options.noBarLevels = true;
}