-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathConlangWorkspace.py
1298 lines (1166 loc) · 43.5 KB
/
ConlangWorkspace.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
# coding=utf-8
secret_key = 0
# BUGS
"""
- FIXED - adjectives left out in translations (3275104 to 73; 1 to 2)
- FIXED - adjective-noun ordering is the reverse in example sentences from what is
said at the top (3275104, 73)
- FIXED - list index out of range on translate when pos is "?"
- MEH TOO LAZY - general messiness in exception handling (not really a bug)
- still happening - roots in lexicon display forms that never surface (e.g. in a lang where
uu > u always, the root "ruum" should be displayed in the lexicon as "rum")
- program exits on certain errors (my fault) instead of just stopping that
command and doing the loop again (I just need to learn how to do this)
- -d=z is changed to -r=z in some languages (just need to restrict that
morphophonemic rule somehow, and prevent similar things in the future)
- translating to or from seeds with large absolute values gives a completely
different language and thus returns errors with high likelihood
(this is a bug with vet_seed, switch_sign, and the like. check also translate)
- infinite loop rarely (seed 3842282112524023590), with "(" in parse_structure
"""
# TO DO
"""
- add verb / sentence negation and possibly other morphemes
- add more affix categories (infix, isolating) and variability of affix type
by morpheme (e.g. "non parlerò", "ar v-nax-av-t") (will require lots of restructuring to
change the "prefix" truth value to an enumerable (does not actually have to
be enum, but should fall within a global set that can be a declared list))
- maybe allow for smaller affixes, but this is not that important
- print out morphophonemic and phonological rules; people won't have to
use them for composition, but they will receive messages in collapsed form
in their own language
"""
# auxiliary functionality
def r():
for i in range(secret_key):
# waste a random value
a = random.random()
return random.random()
def intable(s):
"""
Returns True if a string can be converted to an integer,
False otherwise.
"""
try:
int(s)
return True
except:
return False
def list_nested_dict(d):
"""
Takes a dictionary nested to arbitrarily many dimensions,
returns a list of all the values at the ends of paths,
i.e. those values which are not dicts.
"""
result = []
for key in sorted(d):
if type(d[key]) == dict:
result.extend(list_nested_dict(d[key]))
else:
result.append(d[key])
return result
def list_locations(list_of_lists):
"""
Takes a list of lists, returns a dict with lists of the indices
of lists in which each item appears. Used for union and intersection.
"""
locations = {}
i = -1
for lst in list_of_lists:
i += 1
for e in lst:
if e in locations and i not in locations[e]:
# prevents double-counting of items that appear more than once
# in the same list
locations[e].append(i)
else:
locations[e] = [i]
return locations
def union(list_of_lists):
"""
Takes a list of lists, returns a list of the items found in any list.
"""
result = []
locations = list_locations(list_of_lists)
for u in sorted(locations):
if len(locations[u]) > 0:
result.append(u)
return result
def intersection(list_of_lists):
"""
Takes a list of lists, returns a list of the items found in all lists.
"""
result = []
locations = list_locations(list_of_lists)
for u in sorted(locations):
if locations[u] == [i for i in range(len(list_of_lists))]:
result.append(u)
return result
def partial_intersection(list_of_lists, n):
"""
Takes a list of lists and an integer,
returns a list of the items found in at least n of the lists.
"""
result = []
locations = list_locations(list_of_lists)
for u in sorted(locations):
if len(locations[u]) >= n:
result.append(u)
return result
def prob(x, y, seed):
"""
Takes two integers x and y, returns True with probability x/y.
"""
random.seed(seed)
return random.randrange(y) < x
def remove_duplicates(lst):
result = []
for el in lst:
if el not in result:
result.append(el)
return result
def add_pos(word, pos):
entry = word + " ("+ pos_to_letter[pos] + ")"
return entry
def remove_pos(entry):
if "(" in entry:
i = entry.index("(")
word = entry[:i-1] # excludes the space before the parenthesis
else:
word = entry
return word
def choose(d, seed):
"""
Takes a dict of entries and relative probabilities,
chooses one of them. Probabilities need not add to 1.
"""
random.seed(seed)
t = (sum(d.values()))
sel = t * random.random()
for key in sorted(d):
sel -= d[key]
if sel <= 0:
return key
def vet_seed(s, seed):
random.seed(seed)
if intable(s):
j = int(s)
j = j % sys.maxsize
else:
j = random.randrange(-sys.maxsize/2, sys.maxsize/2+1)
# note that ints in Python 3 have no maximum,
# so these bounds could be anything
return j
def truncnorm(mu, sigma, lower, upper, seed):
random.seed(seed)
result = random.normalvariate(mu, sigma)
result = max(result, lower)
result = min(result, upper)
return result
def switch_sign(s):
if type(s) != int:
return s
if s < sys.maxsize - s:
t = s
else:
t = s - sys.maxsize
return t
dead_keys = ["=", "<", ">", "^"]
ipa_symbols = {
">n":"ŋ",
"^h":"ʰ",
"=s":"ʃ",
"=z":"ʒ",
"=g":"ɣ",
">o":"ø",
"<a":"æ"
}
def render_ipa(s):
result = ""
i = 0
while i < len(s):
if s[i] in dead_keys:
result += ipa_symbols[s[i:i+2]]
i += 2
else:
result += s[i]
i += 1
return result
# phonology functionality
C_moas = ["nasal", "plosive", "fricative", "affricate", "approximant"]
C_poas = ["labial", "coronal", "dorsal"]
C_voicing = ["voiceless", "voiced", "aspirated"]
V_backness = ["front", "back"]
V_height = ["close", "mid", "open"]
V_roundedness = ["unrounded", "rounded"]
C_book = {
"nasal" : {
"labial" : {
"voiceless" : None,
"voiced" : "m",
"aspirated" : None
},
"coronal" : {
"voiceless" : None,
"voiced" : "n",
"aspirated" : None
},
"dorsal" : {
"voiceless" : None,
"voiced" : "ŋ",
"aspirated" : None
}
},
"plosive" : {
"labial" : {
"voiceless" : "p",
"voiced" : "b",
"aspirated" : "pʰ"
},
"coronal" : {
"voiceless" : "t",
"voiced" : "d",
"aspirated" : "tʰ"
},
"dorsal" : {
"voiceless" : "k",
"voiced" : "g",
"aspirated" : "kʰ"
}
},
"fricative" : {
"labial": {
"voiceless" : "f",
"voiced" : "v",
"aspirated": None
},
"coronal" : {
"voiceless" : "s",
"voiced" : "z",
"aspirated" : None
},
"dorsal" : {
"voiceless" : "x",
"voiced" : "ɣ",
"aspirated" : "h"
}
},
"affricate" : {
"labial" : {
"voiceless" : None,
"voiced" : None,
"aspirated" : None
},
"coronal" : {
"voiceless" : "tʃ",
"voiced" : "dʒ",
"aspirated" : "tʃʰ"
},
"dorsal" : {
"voiceless" : "kx",
"voiced" : None,
"aspirated" : None
}
},
"approximant" : {
"labial" : {
"voiceless" : None,
"voiced" : "w",
"aspirated" : None
},
"coronal" : {
"voiceless" : None,
"voiced" : "r",
"aspirated" : None
},
"dorsal" : {
"voiceless" : None,
"voiced" : "j",
"aspirated" : None
}
}
}
V_book = {
"front" : {
"close" : {
"unrounded" : "i",
"rounded" : "y"
},
"mid" : {
"unrounded" : "e",
"rounded" : "ø"
},
"open" : {
"unrounded" : "æ"
}
},
"back" : {
"close" : "u",
"mid" : "o",
"open" : "a"
}
}
phonological_rulesets = {
"long_vowel_diphthongization":{"aa":"aj", "ee":"ej", "ei":"ej", "ii":"ij", "oo":"ow", "ou":"ow", "uu":"uw"},
"long_vowel_monophthongization":{"aa":"a", "ee":"e", "ej":"e", "ei":"e", "ii":"i", "ij":"i", "oo":"o", "ow":"o", "ou":"o", "uu":"u", "uw":"u"}
}
""" # don't need anymore?
def list_inventory(categorized_inventory, dimensions = 1):
workspace = list(categorized_inventory) # list of the keys
for i in range(dimensions):
key_list = workspace
workspace = []
for key in key_list:
workspace.append(key_list[key])
#for category in categorized_inventory:
#for i in categorized_inventory[category]:
#inventory.append(i)
inventory = workspace
print(inventory)
return inventory
"""
def phonemes_with_features(d, features):
"""
Takes a feature dictionary (C_book or V_book)
and a list of features, e.g., ["plosive", "coronal"],
returns a list of the phonemes in that dict with those features.
This is an AND operator. The example above will give ["t", "d", "th"].
"""
counts = {}
findings = []
result = []
for feature in sorted(features):
if feature in d: # features on the same level of the dicts are MX
if type(d[feature]) == dict:
findings.extend(phonemes_with_features(d[feature], features))
elif d[feature] != None:
findings.append(d[feature]) # d[feature] is the phoneme
else:
for key in sorted(d):
if type(d[key]) == dict:
findings.extend(phonemes_with_features(d[key], features))
elif d[key] != None:
findings.append(d[key])
for u in findings:
if u in counts:
counts[u] += 1
else:
counts[u] = 1
for phoneme in sorted(counts):
if counts[phoneme] > len(features):
print("Error: things are being counted more than once per feature")
elif counts[phoneme] == len(features):
result.append(phoneme)
return result
def gen_features(c_or_v, seed):
"""
Takes a type, "C" or "V".
Selects a group of features for use in creating the phoneme inventory.
"""
random.seed(seed)
features = []
if c_or_v == "C":
features.extend(["plosive", "nasal"])
for i in C_moas:
if prob(2,3, r()) and i not in features:
features.append(i)
for i in C_poas:
if prob(2,3, r()) and i not in features:
features.append(i)
for i in C_voicing:
if prob(2,3, r()) and i not in features:
features.append(i)
if c_or_v == "V":
for i in V_backness:
if prob(1,1, r()) and i not in features:
features.append(i)
for i in V_height:
if prob(1,1, r()) and i not in features:
features.append(i)
for i in V_roundedness:
if prob(1,1, r()) and i not in features:
features.append(i)
return features
def gen_inventory(categories, seed):
"""
Takes a category list, generates a phoneme inventory,
returns it formatted by category (but not feature).
"""
random.seed(seed)
categorized_inventory = {} # dict of lists
for category in sorted(categories): # sorted() prevents random() bug
categorized_inventory[category] = []
while categorized_inventory[category] == [] and categories[category] != []:
for i in categories[category]:
if prob(1, 1, r()):
categorized_inventory[category].append(i)
return categorized_inventory
def gen_syllable_structure(categorized_inventory, seed):
# format: onset-nucleus-coda
# within onset: initial|other
# within coda: other|final
# notation: "1|2-3-4|5"
# example: "C(R)|C-V-(C)|(N)"
# initial = "C(R)V(C)"; medial = "CV(C)"; final = "CV(N)"
random.seed(seed)
p1 = choose({"C":2, "(C)":1, "C(R)":1, "":1}, r())
p2 = "C" + choose({"(C)":1, "(R)":1, "":4}, r())
p3 = "V" + choose({"(V)":1, "":5}, r())
p4 = choose({"C":1, "(C)":3, "(R)":2, "(N)":3, "":5}, r())
p5 = choose({"C":1, "(C)":2, "(N)":2, "":7}, r())
full_structure = p1 + "|" + p2 + "-" + p3 + "-" + p4 + "|" + p5
return full_structure
def parse_structure(full_structure, position):
"""
Takes the full syllable structure and creates the individual
syllable structure for the position ("initial", "medial", "final",
or "peripheral").
"""
onset = full_structure.split("-")[0].split("|")[1]
nucleus = full_structure.split("-")[1]
coda = full_structure.split("-")[2].split("|")[0]
if position == "initial" or position == "peripheral":
onset = full_structure.split("-")[0].split("|")[0]
if position == "final" or position == "peripheral":
coda = full_structure.split("-")[2].split("|")[1]
if position == "medial":
# don't change the defaults
pass
structure = onset + nucleus + coda
return structure
def gen_syllable(categorized_inventory, structure, seed):
"""
Takes a categorized inventory, such as that produced by gen_inventory(),
a string that represents a syllable structure, and the syllable position,
returns a random syllable that is viable given these parameters.
"""
random.seed(seed)
syllable = ""
i = 0
while i < len(structure):
advance = 0
if structure[i] in sorted(categorized_inventory):
syllable = syllable + categorized_inventory[structure[i]][random.randrange(len(categorized_inventory[structure[i]]))]
advance = 1
elif structure[i] == "(":
opens = 1
optional = ""
j = i+1
#if structure[j] == "(":
#for k in range(j, len(structure)):
#if structure[k] == ")":
#optional = optional + structure[j]
#j += 1
#break
#if prob(1, 2):
#syllable = syllable + gen_syllable(categorized_inventory, optional)
while j < len(structure) and opens > 0:
# currently assuming no nested parentheses
if structure[j] == "(":
opens += 1
elif structure[j] == ")":
opens -= 1
if opens != 0:
optional = optional + structure[j]
j += 1
advance = j-i+1
if random.randrange(2) == 0:
syllable = syllable + gen_syllable(categorized_inventory, optional, r())
i += advance
return syllable
def gen_word(categorized_inventory, full_structure, num_syllables, seed):
random.seed(seed)
word = ""
if num_syllables < 1:
print("You have to have at least one syllable!")
return None
if num_syllables == 1:
word = gen_syllable(categorized_inventory, parse_structure(full_structure, "peripheral"), r())
else:
for i in range(num_syllables):
if i == 0:
word = word + gen_syllable(categorized_inventory, parse_structure(full_structure, "initial"), r())
elif i == num_syllables - 1:
word = word + gen_syllable(categorized_inventory, parse_structure(full_structure, "final"), r())
else:
word = word + gen_syllable(categorized_inventory, parse_structure(full_structure, "medial"), r())
return word
# morphology functionality
def affix(word, key, function, prefix):
"""
Takes a word, the function of the affix, and a truth value for prefixing.
Returns the word with the affix added.
"""
affix = key["function"][function]
if prefix:
return affix + "-" + word
else:
return word + "-" + affix
def collapse(gloss, pre_rules, post_rules):
"""
Takes a string of words separated into morphemes,
collapses them into surface forms.
"""
result = gloss
for rank in sorted(pre_rules):
for key in sorted(pre_rules[rank]):
if key in result:
result = result.replace(key, pre_rules[rank][key])
result = result.replace("-", "")
for rank in sorted(post_rules):
for key in sorted(post_rules[rank]):
if key in result:
result = result.replace(key, post_rules[rank][key])
"""
if prob(1, 2, r()):
# remove double letters (naive because of digraphs, but whatevs)
new_result = ""
for i in range(len(result)-1):
if result[i] != result[i+1]:
new_result += result[i]
new_result += result[-1]
result = new_result
"""
return result
# syntax functionality
def gen_word_order(seed):
"""
Chooses one of the six word orders with similar probability to IRL.
Does not support others, such as V2.
"""
random.seed(seed)
# realistic weights
#return choose({"SOV": 0.45, "SVO": 0.42, "VSO": 0.09, "VOS": 0.03, "OVS": 0.005, "OSV": 0.005}, r())
# give some more love to the underdogs
return choose({"SOV": 0.25, "SVO": 0.25, "VSO": 0.15, "VOS": 0.15, "OVS": 0.1, "OSV": 0.1}, r())
def infer(roots, key, pos_profile, word_order, adjective_noun):
if "X" in pos_profile:
return infer(roots, key, pos_profile.replace("X", ""), word_order, adjective_noun)
l = len(pos_profile)
possibilities = ["This string should never get returned."]
if adjective_noun:
seg = "AN"
else:
seg = "NA"
if l == 3:
return word_order.replace("S", "N").replace("O", "N")
elif l == 4:
possibilities = [word_order.replace("S", seg).replace("O", "N"), word_order.replace("S", "N").replace("O", seg)]
elif l == 5:
return word_order.replace("S", seg).replace("O", seg)
acceptables = []
for p in possibilities:
use_it = True
for pos_i in range(len(p)):
if roots[pos_i] not in key[letter_to_pos[p[pos_i]]]:
use_it = False
break
if use_it:
acceptables.append(p)
if len(acceptables) == 0:
print("There were no possible readings of this sentence.")
sys.exit()
if len(acceptables) != 1:
print("There were {0} possible readings of this sentence.\n"
"The reading {1} was used.".format(len(acceptables), acceptables[0]))
#print("acceptables:", acceptables)
return acceptables[0]
# GRAVEYARD OF IMPLEMENTATION ATTEMPTS
# THEY WERE SO YOUNG
"""
if word_order[0] == "V":
if pos_profile[0] == "?":
pos_profile = "V" + pos_profile[1:]
"""
"""
if adjective_noun:
max_profile = word_order.replace("S", "AN").replace("O", "AN")
else:
max_profile = word_order.replace("S", "NA").replace("O", "NA")
"""
"""
q = 0
for i in pos_profile:
if i == "?":
q += 1
if q == 0:
return pos_profile
"""
"""
if adjective_noun:
ender = "N"
else:
ender = "A"
x = pos_profile.index("?")
"""
"""
if q == 1:
if "V" not in pos_profile:
return pos_profile.replace("?", "V")
elif adjective_noun:
if
"""
def parse(pos_profile, word_order, adjective_noun):
"""
Given a string representing the parts of speech of the words
in a sentence, the word order, and the truth value for AN,
outputs a dict of dicts telling the index of each word in the syntax.
This description is badly worded, so look at this:
Example input: ("ANVN", SVO, True)
Resulting output: {
"subj": {"noun": 1, "adjective": 0},
"obj": {"noun": 3},
"verb": {"verb": 2}
}
"""
result = {"subj": {}, "obj": {}, "verb": {}}
verb_location = pos_profile.index("V")
result["verb"]["verb"] = verb_location
if adjective_noun:
adjective_to_noun = -1
else:
adjective_to_noun = 1
noun_locations = [m.start() for m in re.finditer("N", pos_profile)]
#print(noun_locations)
first_noun_location = noun_locations[0]
first_adjective_location = -1
try:
a = pos_profile[first_noun_location + adjective_to_noun]
if a == "A":
first_adjective_location = first_noun_location + adjective_to_noun
except:
pass
second_noun_location = noun_locations[1]
second_adjective_location = -1
try:
a = pos_profile[second_noun_location + adjective_to_noun]
if a == "A":
second_adjective_location = second_noun_location + adjective_to_noun
except:
pass
if word_order.index("S") < word_order.index("O"):
np1 = "subj"
np2 = "obj"
else:
np1 = "obj"
np2 = "subj"
result[np1]["noun"] = first_noun_location
if first_adjective_location != -1:
result[np1]["adjective"] = first_adjective_location
result[np2]["noun"] = second_noun_location
if second_adjective_location != -1:
result[np2]["adjective"] = second_adjective_location
#print(result)
return result
# lexicon functionality
pos_to_letter = {"noun" : "N", "verb" : "V", "adjective" : "A", "function" : "F"}
letter_to_pos = {"N" : "noun", "V" : "verb", "A" : "adjective", "F" : "function"}
V_functions = ["past"]
N_functions = ["plural"]
eng_lex = {
"noun" : ["man", "woman", "boy", "girl", "cat", "dog", "tree", "car", "house", "ship", "guitar", "gun", "shoe", "book", "cake"],
"verb" : ["see", "eat", "want", "like", "have", "find", "need", "buy"],
"adjective" : ["good", "bad", "tall", "short", "big", "small", "red", "blue", "black", "white", "green", "yellow", "old", "new"],
"function" : [i for i in V_functions] + [i for i in N_functions]
}
def gen_NP(lex, seed):
"""
Takes a lexicon, returns a dict with the NP information.
"""
random.seed(seed)
NP = {}
if prob(1, 2, r()):
NP["adjective"] = lex["adjective"][random.randrange(len(lex["adjective"]))]
NP["noun"] = lex["noun"][random.randrange(len(lex["noun"]))]
NP["plural"] = (random.randrange(2) == 0)
return NP
def gen_VP(lex, seed):
"""
Takes a lexicon, returns a dict with the VP information.
"""
random.seed(seed)
VP = {}
VP["verb"] = lex["verb"][random.randrange(len(lex["verb"]))]
VP["past"] = prob(1, 2, r())
return VP
def gen_sentence(lex, seed):
"""
Takes a lexicon.
Returns a dict of "subj", "obj", and "verb" mapping to
the corresponding constituents (dicts of features).
"""
random.seed(seed)
subj = gen_NP(lex, r())
obj = gen_NP(lex, r()) # "object" is a keyword in Python
verb = gen_VP(lex, r())
return {"subj":subj, "obj":obj, "verb":verb}
# should probably remove this function in favor of using
# render_lang for everything including English
# WARNING: this function was creating global vars for adjective_noun, etc.
"""
def render_eng(sentence):
#"#"#"
#Creates an English sentence from the sentence structure.
#Currently supports only rudimentary caveman speak.
#"#"#"
local_sentence_words = []
local_word_order = "SVO"
local_adjective_noun = True
for i in local_word_order:
if i == "S":
noun = sentence["subj"]["noun"]
if sentence["subj"]["plural"]:
noun = noun + "-s"
if "adjective" in sentence["subj"]:
adjective = sentence["subj"]["adjective"]
if local_adjective_noun:
local_sentence_words.append(adjective)
local_sentence_words.append(noun)
else:
local_sentence_words.append(adjective)
local_sentence_words.append(noun)
else:
local_sentence_words.append(noun)
elif i == "O":
noun = sentence["obj"]["noun"]
if sentence["obj"]["plural"]:
noun = noun + "-s"
if "adjective" in sentence["obj"]:
adjective = sentence["obj"]["adjective"]
if local_adjective_noun:
local_sentence_words.append(adjective)
local_sentence_words.append(noun)
else:
local_sentence_words.append(adjective)
local_sentence_words.append(noun)
else:
local_sentence_words.append(noun)
elif i == "V":
verb = sentence["verb"]["verb"]
if sentence["verb"]["past"]:
verb = verb + "-ed"
local_sentence_words.append(verb)
result = " ".join(sentence_words)
return result
"""
def render_lang(sentence, key, word_order, adjective_noun, prefix):
"""
Creates a sentence in the conlang from the sentence structure.
"""
### DOES NOT DISTINGUISH BETWEEN HOMOPHONES
# this is due to its use of eng_to_lang as key, ignoring the pos
# the key should be sorted by the pos
sentence_words = []
for i in word_order:
if i == "S":
noun = key["noun"][sentence["subj"]["noun"]]
if sentence["subj"]["plural"]:
noun = affix(noun, key, "plural", prefix)
if "adjective" in sentence["subj"]:
adjective = key["adjective"][sentence["subj"]["adjective"]]
if adjective_noun:
sentence_words.append(adjective)
sentence_words.append(noun)
else:
sentence_words.append(noun)
sentence_words.append(adjective)
else:
sentence_words.append(noun)
elif i == "O":
noun = key["noun"][sentence["obj"]["noun"]]
if sentence["obj"]["plural"]:
noun = affix(noun, key, "plural", prefix)
if "adjective" in sentence["obj"]:
adjective = key["adjective"][sentence["obj"]["adjective"]]
if adjective_noun:
sentence_words.append(adjective)
sentence_words.append(noun)
else:
sentence_words.append(noun)
sentence_words.append(adjective)
else:
sentence_words.append(noun)
elif i == "V":
verb = key["verb"][sentence["verb"]["verb"]]
if sentence["verb"]["past"]:
verb = affix(verb, key, "past", prefix)
sentence_words.append(verb)
result = " ".join(sentence_words)
return result
def translate(message, f, t):
Lf = L(f)
Lt = L(t)
sentence = {"subj":{}, "obj":{}, "verb":{}}
"""
for i in Lf.word_order:
if i == "V":
#constituents.append("VP")
pass
elif i == "S" or i == "O":
#constituents.append("NP")
pass
"""
message = render_ipa(" ".join(message)).split(" ")
pos_profile = ""
for word in message:
still_looking = True
best_pos = "?"
morphemes = word.split("-")
i = 0
while still_looking and i < len(morphemes):
possibilities = {}
for pos in Lf.lang_lex:
if morphemes[i] in Lf.lang_lex[pos]:
possibilities[pos]=Lf.lang_to_eng[pos][morphemes[i]]
#print(morphemes[i], possibilities)
if len(possibilities) == 1:
if "function" in possibilities:
if possibilities["function"] in V_functions:
best_pos = "V"
still_looking = False
elif possibilities["function"] in N_functions:
best_pos = "N"
still_looking = False
elif "verb" in possibilities:
best_pos = "V"
still_looking = False
elif "noun" in possibilities:
best_pos = "N"
still_looking = False
elif "adjective" in possibilities:
best_pos = "A"
still_looking = False
else:
# should not happen, pos not recognized
best_pos = "!"
still_looking = False
elif len(possibilities) == 0:
# the morpheme is not recognized
best_pos = "X"
still_looking = False
else:
best_pos = "?"
# continue looking
i += 1
pos_profile = pos_profile + best_pos
#print(pos_profile)
roots = [word for word in message]
if Lf.prefix:
root_loc = 1
else:
root_loc = 0
for word_i in range(len(message)):
if "-" in message[word_i]:
roots[word_i] = message[word_i].split("-")[root_loc]
pos_profile = infer(roots, Lf.lang_to_eng, pos_profile, Lf.word_order, Lf.adjective_noun)
#print(pos_profile, "(inferred)")
constituents = parse(pos_profile, Lf.word_order, Lf.adjective_noun)
#print(constituents)
sentence["subj"]["plural"] = False
sentence["obj"]["plural"] = False
sentence["verb"]["past"] = False
for role in constituents:
for pos in constituents[role]:
if "-" in message[constituents[role][pos]]:
b = message[constituents[role][pos]].split("-")
if Lf.prefix:
c = 0
else:
c = 1
function = Lf.lang_to_eng["function"][b[c]]
root = Lf.lang_to_eng[pos][b[1-c]]
sentence[role][function] = True
sentence[role][pos] = root
else:
b = message[constituents[role][pos]]
root = Lf.lang_to_eng[pos][b]
sentence[role][pos] = root
#print(sentence)
#if t == "English":
#return render_eng(sentence)
#else:
print("Translation of \"{0}\" from L#{1} to L#{2}:".format(" ".join(message), switch_sign(f), switch_sign(t)))
tl = render_lang(sentence, Lt.eng_to_lang, Lt.word_order, Lt.adjective_noun, Lt.prefix)
print("Underlying:", tl)
print("Surface:", collapse(tl, Lt.morphophonemics, Lt.phonologics))
# construct the sentence from the word order
# may need to go through the randomizations so they take seed as parameter
# language class creation
class L:
def __init__(self, seed):
# random seed control
if seed != "E":
random.seed(seed)
self.seed = seed
# phonology construction
self.C_features = gen_features("C", r())
self.V_features = gen_features("V", r())
self.all_features = union([self.C_features, self.V_features])
self.possible_phonemes = []
for f in self.C_features:
self.possible_phonemes.extend(phonemes_with_features(C_book, [f]))
for f in self.V_features:
self.possible_phonemes.extend(phonemes_with_features(V_book, [f]))
self.possible_phonemes = remove_duplicates(self.possible_phonemes)
self.categories = {
"P": intersection([phonemes_with_features(C_book, ["plosive"]), self.possible_phonemes]),
"F": intersection([phonemes_with_features(C_book, ["fricative"]), self.possible_phonemes]),
"R": intersection([phonemes_with_features(C_book, ["approximant"]), self.possible_phonemes]),
"V": intersection([phonemes_with_features(V_book, ["unrounded"]), self.possible_phonemes]),
"N": intersection([phonemes_with_features(C_book, ["nasal"]), self.possible_phonemes]),
"J": intersection([phonemes_with_features(C_book, ["affricate"]), self.possible_phonemes])
}
for f in sorted(self.categories):
if f != "V":
self.categories[f] = intersection([self.categories[f], self.possible_phonemes])
if self.categories[f] == []:
del self.categories[f]
self.categories["C"] = union([self.categories[x] for x in sorted(self.categories) if x != "V"])