-
Notifications
You must be signed in to change notification settings - Fork 0
/
Convention.py
2029 lines (1631 loc) · 71.7 KB
/
Convention.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
'''Vowel evolution program.
Run with Vowel, Prototype, Game_fns, Agent, Word
Also import time, random and graphics modules
Last update July 2017 HJMS'''
import Vowel, Prototype, time, random, Word, re, Agent, Segment
from graphics import *
class Convention:
'''
A convention is a set of prototypical vowels
representing the collective repertoires of a population of speakers.
The convention is like a model speaker, which may not exist.
A convention is what linguists use to make a language tangible.
Prototypes are updated by averaging the Agents' vowels/phones for each word.
This Convention class handles the representation (output) of the system,
e.g. the vowel chart, mean centers, color-coding,
and the IPA "master set" used to 'strap' the ancestor group.
'''
def __init__(self, show = False, color_on = True, ls = 50):
'''
Can be initialized with no arguments.d
show == True means more output e.g. step reports.
color_on == True means vowels are color-coded,
where the colors are static according to master set (IPA symbol names).
ls is the minimum lexicon size,
where the actual size is determined by the size of the convention
(the number of prototypes active in the base set).
'''
self.show = show
self.lf = True #length flag (whether length is contrastive)
self.win = False #No window drawn yet (use to prevent multiples)
self.color_on = color_on
self.color_list = []
self.circles = []
self.set_formant_limits() #sets up the f1, f2 ranges
self.base_vowel_dict = dict() #vowels in base convention
self.base_proto_dict = dict() #doesn't change
self.proto_dict = dict() #live prototypes
self.base_weights = dict()
self.lexicon = dict() #words
self.lex_size = ls #number of words in lexicon
self.curr_proto_pts = [] #live graphic prototype points
self.curr_sampling = [] #live graphic agent vowel points
self.updating_label = None #center graphic label if no color chart
self.proto_label = None #live prototype graphic label
self.color_key = False #side key of proto-color map
self.param_str = "" #center label
self.set_vowels() #creates ipa_dict "master set"
self.plot = self.plot_spots #plot_symbols will use symbols instead
self.func_load_max = 5
def __str__(self):
pl = self.proto_dict.values()
if pl:
ps = [str(p) for p in pl]
s = ",".join(ps)
else:
s = "Empty Convention"
return s
def set_param_str(self, s):
'''
the current parameters e.g. perception
'''
self.param_str = s
def reset(self, base):
'''
reset the prototypes to the IPA originals
'''
self.str_to_protos(base) #for new games (not extensions)
def enter_protos(self): #user input of list prototypes
'''
prompt user for input
initialize convention using a custom list of protos (i.e. not a preset)
'''
base = input("Base convention (e.g. i:, retracted_a, o, u): ")
self.str_to_protos(base)
return base
def str_to_protos(self, vs): #instantiate base convention from String list
'''Uses list of vowel names to create convention dictionary and Prototype list'''
if not vs: #user enters nothing -- assume they don't want to change anything
print("Convention overwrite canceled.")
return
P = Prototype.Prototype
v_strlist = vs.split(", ")
self.proto_dict = dict()
self.base_proto_dict = dict()
#base = self.base_proto_dict
self.base_vowel_dict = dict()
ipa = self.ipa_dict
for v in v_strlist:
#use regular expressions to get symbol name for grouping
p_class = "".join(re.findall("[a-zA-Z_:]+", v))
#error handling: all prototypes must be in the master set
while p_class not in ipa:
pc = p_class.copy()
del p_class
p_class = input((pc+" is not a recognized vowel. Please re-enter: "))
ip = ipa[p_class] #lookup the IPA prototype
self.base_vowel_dict[p_class] = P(ip.e1, ip.e2, ip.length, ip.name)
def strap_protos(self):
'''
you can switch between un/balanced distr. lexicon
by commenting the one you don't want to use.
'''
#self.lexicon = self.uni_lexicon()
#self.lexicon = self.cust_lexicon() #manually set each proto weight
self.lexicon = self.rand_lexicon()
def match_proto(self, im, ipa = False):
'''
Matches a signal imitation against ACTIVE IPA Prototypes.
If the imitation is in fact closer to some other ACTIVE IPA proto, it will return that proto.
If the imitation is closest to the signal it will return the signal.'''
P = Prototype.Prototype
def lm(p):
if not self.lf:
return True
else:
return( (p.length > 200) is (im.length > 200) )
#use this version to match against all in master set
#(enables splitting / phonological change):
if ipa:
p_list = [p for p in self.ipa_dict.values() if lm(p)]
#use this one to match against all active prototypes (present in base convention)
else:
p_list = [p for p in self.proto_dict.values() if lm(p)]
def rec_match_proto(protos):
if len(protos) < 2:
d0 = euc(im, protos[0])
if not lm(protos[0]):
d0 = 999
return (protos[0], d0)
else:
l = len(protos)
mid = int(l/2)
left_closest, dl = rec_match_proto(protos[:mid])
right_closest, dr = rec_match_proto(protos[mid:])
if dl < dr:
return (left_closest, dl)
return (right_closest, dr)
real_proto = (rec_match_proto(p_list)[0])
rpn = real_proto.name
if rpn not in self.proto_dict: #something has gone wrong, fix it
self.proto_dict[rpn] = P(im.e1, im.e2, im.length, rpn)
#activate if it hasn't been already
#if real_proto.name not in self.proto_dict:
# self.proto_dict[real_proto.name] = real_proto
return real_proto
def activate(self, str_list, c):
'''
Used by trigger function (unlisted command)
Add a new word to the lexicon
'''
if c < 1:
c = 1
P = Prototype.Prototype
W = Word.Word
for p in (str_list.split(", ")):
if (p in self.ipa_dict and p not in self.proto_dict):
ip = self.ipa_dict[p]
#self.proto_dict[p] = P(ip.e1, ip.e2, ip.length, ip.name)
np = P(ip.e1, ip.e2, ip.length, ip.name) # self.proto_dict[p]
self.base_proto_dict[p] = np
else:
p_correction = input("{0} is invalid. Retry:".format(p))
if p_correction:
ip = self.ipa_dict[p]
np = P(ip.e1, ip.e2, ip.length, ip.name)
self.base_proto_dict[p] = np
np.carriers = c
#name = "{0}{1}{2:02d}".format(np.name, "-", 0)
null_seg = Segment.Segment("-", [])
new_word = W(null_seg, np.name, null_seg, np)
self.lexicon[name] = (new_word)
self.proto_label = False #label needs to be redrawn to include new prototype
self.color_key = False #color map needs to be redrawn to include new prototype
def f1f2_to_e1e2(self, f1, f2 = None):
'''
direct implementation of traunmuller formula to convert from hertz to ERB
just converts a tuple (f1, f2) in hz to erb
benefit is that it doesn't have to be a Vowel, just the values
>>>f1f2_to_e1e2(2400, 800) = (22.44472228978699, 13.58504853003826)
'''
from math import log
def conv(f):
b_n = f/1000 + .312
b_d = f/1000 + 14.680
b_r = b_n/b_d
prod =(11.17 * (log(b_r)))
s = prod + 43
return s
e1 = conv(f1)
if f2:
e2 = conv(f2)
else:
e2 = 0
return (e1, e2)
def p_hz(self, f1, f2, l, n):
'''creates a prototype from hertz values
f1 = first formant, f2 = second formant,
l = length in ms, n is name (string) '''
P = Prototype.Prototype
e1, e2 = self.f1f2_to_e1e2(f1, f2)
return P(e1, e2, l, n)
############################################################
# MASTER SET (IPA VOWELS) #
############################################################
def set_vowels(self):
'''
To add a new Prototype, copy and paste this line:
new_pro( p_hz(f1, f2, length, name) )
anywhere within this function above the ######### line
and replace f1, f2, length, name with values.
You can also adjust the formant values here.
Name must be unique, may contain {[A..Z], [a..z], :, _}
For the translation dictionary, see global IPA_trans dict
^used for IPA symbol representation (unicode)
'''
p_hz = self.p_hz
ipa_list = list()
new_pro = ipa_list.append
######## ADD NEW PROTOS BELOW THIS LINE ############
#FRONT
new_pro( p_hz(331, 2368, 100, "i") ) #unrounded [i]
new_pro( p_hz(331, 2368, 250, "i:") ) #unrounded [i:]
new_pro( p_hz(331, 1968, 100, "y") ) #rounded [y]
new_pro( p_hz(331, 1968, 250, "y:") ) #rounded [y:]
new_pro( p_hz(395, 2034, 100, "I") ) #singleton [I]
new_pro( p_hz(395, 2034, 250, "I:") ) #singleton [I:]
new_pro( p_hz(395, 1750, 100, "Y") ) #singleton [Y]
new_pro( p_hz(395, 1750, 250, "Y:") ) #singleton [Y:]
new_pro( p_hz(462, 2309, 100, "e") ) #unrounded[e]
new_pro( p_hz(462, 2309, 250, "e:") ) #unrounded[e:]
new_pro( p_hz(462, 1950, 100, "o_slash") ) #rounded [o_slash]
new_pro( p_hz(462, 1950, 250, "o_slash:") ) #rounded [o_slash:]
new_pro( p_hz(622, 2077, 100, "epsilon") ) #unrounded [epsilon]
new_pro( p_hz(622, 2077, 250, "epsilon:") ) #unrounded [epsilon:]
new_pro( p_hz(622, 1700, 100, "oe") ) #rounded [oe]
new_pro( p_hz(622, 1700, 250, "oe:") ) #rounded [oe:]
new_pro( p_hz(775, 1952, 100, "ae") ) #singleton [ae]
new_pro( p_hz(775, 1952, 250, "ae:") ) #singleton [ae:]
new_pro( p_hz(900, 1670, 100, "a") ) #unrounded [a]
new_pro( p_hz(900, 1670, 250, "a:") ) #unrounded [a:]
new_pro( p_hz(900, 1470, 100, "OE") ) #[OE]
new_pro( p_hz(900, 1470, 250, "OE:") ) #[OE:]
#CENTRAL
new_pro( p_hz(331, 1600, 150, "barred_i") ) #unrounded [barred_i]
new_pro( p_hz(331, 1600, 250, "barred_i:") ) #unrounded [barred_i:]
new_pro( p_hz(331, 1370, 150, "barred_u") )#rounded [barred_u]
new_pro( p_hz(331, 1370, 250, "barred_u:") )#rounded [barred_u:]
new_pro( p_hz(460, 1550, 150, "rev_e") ) #unrounded [schwa]
new_pro( p_hz(460, 1550, 250, "rev_e:") ) #unrounded [schwa:]
new_pro( p_hz(459, 1300, 150, "barred_o") ) #rounded [barred_o]
new_pro( p_hz(459, 1300, 250, "barred_o:") ) #rounded [barred_o:]
new_pro( p_hz(530, 1400, 150, "schwa") ) #singleton [turned_schwa]
new_pro( p_hz(530, 1400, 250, "schwa:") ) #singleton [turned_schwa:]
new_pro( p_hz(605, 1500, 150, "rev_eps") ) #unrounded [rev_eps]
new_pro( p_hz(605, 1500, 250, "rev_eps:") ) #unrounded [rev_eps:]
new_pro( p_hz(605, 1250, 150, "lil_bum") ) #rounded [closed_rev_eps] <Needs a new name
new_pro( p_hz(605, 1250, 250, "lil_bum:") ) #rounded [closed_rev_eps:] <Needs a new name
new_pro( p_hz(700, 1450, 150, "turned_a") ) #singleton [turned_a]
new_pro( p_hz(700, 1450, 250, "turned_a:") ) #singleton [turned_a:]
new_pro( p_hz(824, 1400, 150, "retracted_a") ) #singleton [hod]
new_pro( p_hz(824, 1400, 250, "retracted_a:") ) #singleton [hod:]
#BACK
new_pro( p_hz(331, 999, 150, "turned_m") ) #unrounded [turned_m]
new_pro( p_hz(331, 999, 250, "turned_m:") ) #unrounded [turned_m:]
new_pro( p_hz(331, 850, 150, "u") ) #rounded [u]
new_pro( p_hz(331, 850, 250, "u:") ) #rounded [u:]
new_pro( p_hz(405, 1150, 150, "horseshoe") ) #singleton [omega]
new_pro( p_hz(405, 1150, 250, "horseshoe:") ) #singleton [omega:]
new_pro( p_hz(465, 1000, 150, "rams_horn") ) #unrounded [rams_horn]
new_pro( p_hz(465, 1000, 250, "rams_horn:") ) #unrounded [rams_horn:]
new_pro( p_hz(465, 850, 150, "o") ) # rounded [o]
new_pro( p_hz(465, 850, 250, "o:") ) # rounded [o:]
new_pro( p_hz(600, 1000, 150, "wedge") ) #unrounded [wedge] aka ^
new_pro( p_hz(600, 1000, 250, "wedge:") ) #unrounded [wedge:] aka ^
new_pro( p_hz(600, 850, 150, "open_o") ) #rounded [open_o]
new_pro( p_hz(600, 850, 250, "open_o:") ) #rounded [open_o:]
new_pro( p_hz(734, 1020, 150, "script_a") ) #unrounded [script_a]
new_pro( p_hz(734, 1020, 250, "script_a:") ) #unrounded [script_a:]
new_pro( p_hz(734, 850, 150, "rev_script_a") ) #rounded [rev_script_a]
new_pro( p_hz(734, 850, 250, "rev_script_a:") ) #rounded [rev_script_a:]
############Add new prototypes above this line##############
self.ipa_dict = dict((p.name, p) for p in ipa_list)
self.assign_colors(ipa_list)
def get_size(self):
'''returns the number of currently active Prototypes'''
return len(self.proto_dict.values())
def get_load_avg(self):
'''average functional load of vowels in convention'''
s = self.get_size()
v_list = self.proto_dict.values()
if s:
total = sum(v.weight for v in v_list)
avg = total/s
return avg
else:
print("Not enough vowels to get an average.")
def print_list(self):
for p in self.proto_dict.values():
print(p)
def sorted_protos(self):
#using modified insertion sort
#because the list will always be shortish (n < 56)
protos = [p for p in self.proto_dict.values()]
for i in range(len(protos)):
curr = protos[i]
j = i
while j >= 0 and protos[j-1].e1 < curr.e1:
protos[j] = protos[j-1]
j = j-1
protos[j] = protos
return protos
def rand_lexicon(self):
'''
Returns a dictionary.
Uses the base vowel convention to generate a lexicon.
The minimum lex size is set in Game_fns.
The prototypical vowels are given a random number of environments (words).
The dictionary keys are the word IDs i.e. String.
the dictionary values are the Word objects.
The elder group will use a close imitation of the prototypical vowel
to pronounce the word for the child Agents.
e.g. a five-vowel system "Spanish" {i, e, o, retracted_a, u}
with a min lex size of fifty will produce a lexicon
where each vowel has [10, 40] words.
Each word is a unique combination of CVC
where each C (consonant) is a segment
(a list of articulatory features)
and V is one of the base protos.
See Phonology class for articulations.
'''
r = random
W = Word.Word
p_list = self.base_vowel_dict.values()
lex_size = self.lex_size
pl_len = len(p_list)
min_words_vowel = int(lex_size/pl_len)+1
lexicon = dict()
#CONSONANTS
from Phonology import get_feature_dict
self.consonant_dict = get_feature_dict() #default is English (sorry)
cd = self.consonant_dict
consonants = [c for c in cd.keys()]
#proto balance (functional load)
#should probably seed instead of generating inside the loop.
#ex. ratio_lim = 5 means any proto can have up to 5x as many words as another proto
ratio_lim = self.func_load_max # (min_words_vowel) <= number of words in class <= (min_words_vowel * ratio lim)
for nucleus in p_list:
num_words_vowel = r.randint(min_words_vowel, min_words_vowel*ratio_lim)
for i in range(num_words_vowel):
onset_name = r.choice(consonants)
onset = Segment.Segment(onset_name, cd[onset_name])
coda_name = r.choice(consonants)
coda = Segment.Segment(coda_name, cd[coda_name])
#name = "{0}+{1}+{2}".format(onset, nucleus.name, coda)
#new_word = W(name, nucleus, None)
new_word = W(onset, nucleus.name, coda, nucleus)
lexicon[new_word.id] = new_word
self.base_weights[nucleus.name] = num_words_vowel
lex_size = len(lexicon.keys())
for n in p_list:
num_words = self.base_weights[n.name]
weight = (num_words/lex_size) * 10
self.base_weights[n.name] = weight
return lexicon
def cust_lexicon(self):
'''
Returns a dictionary.
Uses the base vowel convention to generate a lexicon.
The minimum lex size is set in Game_fns.
The prototypical vowels are given a random number of environments (words).
The dictionary keys are the word IDs i.e. String.
the dictionary values are the Word objects.
The elder group will use a close imitation of the prototypical vowel
to pronounce the word for the child Agents.
'''
r = random
W = Word.Word
p_list = self.base_vowel_dict.values()
lex_size = self.lex_size
pl_len = len(p_list)
min_words_vowel = int(lex_size/pl_len)+1
lexicon = dict()
#CONSONANTS
from Phonology import get_feature_dict
self.consonant_dict = get_feature_dict()
consonants = [c for c in self.consonant_dict.keys()]
for nucleus in p_list:
num_words_vowel = int(input("Number of words for ["+nucleus.name+"] :"))
for i in range(num_words_vowel):
onset = r.choice(consonants)
coda = r.choice(consonants)
#name = "{0}+{1}+{2}".format(onset, nucleus.name, coda)
#new_word = W(name, nucleus, None)
new_word = W(onset, nucleus.name, coda, nucleus)
lexicon[new_word.id] = new_word
self.base_weights[nucleus.name] = num_words_vowel
lex_size = len(lexicon.keys())
for n in p_list:
num_words = self.base_weights[n.name]
weight = (num_words/lex_size) * 10
self.base_weights[n.name] = weight
return lexicon
def uni_lexicon(self):
'''
Returns a dictionary.
Uses the base vowel convention to generate a lexicon.
The prototypical vowels are represented equally among words.
The dictionary keys are the word IDs i.e. String.
the dictionary values are the Word objects.
The elder group will use a close imitation of the prototypical vowel
to pronounce the word for the child Agents.
e.g. a five-vowel system "Spanish" {i, e, o, retracted_a, u}
with a lex size of fifty will produce a lexicon
where each vowel has eleven words.
Each word is a unique combination of CVS
where each C (consonant) is a set of articulatory gestures.
See Phonology class for articulations.
'''
r = random
W = Word.Word
p_list = self.base_vowel_dict.values()
lex_size = self.lex_size
pl_len = len(p_list)
num_words_vowel = int(lex_size/pl_len)+1
lexicon = dict()
#CONSONANTS
from Phonology import get_feature_dict
self.consonant_dict = get_feature_dict()
consonants = [c for c in self.consonant_dict.keys()]
for nucleus in p_list:
for i in range(num_words_vowel):
onset = r.choice(consonants)
coda = r.choice(consonants)
#name = "{0}+{1}+{2}".format(onset, nucleus.name, coda)
#new_word = W(name, nucleus, None)
new_word = W(onset, nucleus.name, coda, nucleus)
lexicon[new_word.id] = new_word
self.base_weights[nucleus.name] = (num_words_vowel/(num_words_vowel*pl_len))
return lexicon
def get_word_prototype(self, vg, p_name):
'''
Find the prototype of a word by averaging its pronunciation
among all agents.
vg is a generator of Vowels (tokens)
w_id is the ID tag of the Word we are updating
'''
P = Prototype.Prototype
e1_sum = 0
e2_sum = 0
l_sum = 0
nc = 0 #number of carriers
for v in vg:
nc += 1
e1_sum += v.e1
e2_sum += v.e2
l_sum += v.length
e1_avg = (e1_sum / nc)
e2_avg = (e2_sum / nc)
l_avg = ( l_sum / nc)
proto = P(e1_avg, e2_avg, l_avg, p_name)
proto.carriers = nc
return proto
def group_word_protos(self, radius, pl):
'''
Update the prototype dictionary with current averages.
radius is for clustering (not currently in use--maybe in future phase).
pl is the list of Prototypes.
'''
for p in pl:
self.proto_dict[p.name] = p
#############################
# Graphical functions #
#############################
def assign_colors(self, ipa_vl):
'''
Set up color mapping for chart
Sampling shows each vowel as a different color in reports
ipa_vl is the list of vowels to be mapped to colors.
color_map is a dict {"proto_name": color(r, g, b)} for each proto.
This is a sortof fragile method;
it will break if there are too many IPA prototypes (in master set).
Creates a collection of contrastive colors,
so that each prototype can be assigned one statically.
Several base colors are used, then several shades of each base color.
Recall that long/short vowels are stacked and that vowels move and spread.
If you want to edit this . . . good luck. :/ :D...
'''
self.color_map = dict()
color_map = self.color_map
vl = [v.name for v in ipa_vl]
scm = self.build_color_lists
cl = self.color_list
shade_list = []
sla = shade_list.append #list of shades of base colors
teal = [5, 109, 79] #"base" color
sla(scm([], teal, (27, 29, 39))) #list of shades of base color
red = [90, 0, 0] #"base" color
sla(scm([], red, (39, 10, 9)))
green = [0, 55, 0]
sla(scm([], green, (11, 37, 14)))
purple = [255, 0, 255]
sla(scm([], purple, (-47, 8, -47)))
orange = [255, 130, 30]
sla(scm([], orange, (-21, -18, -9)))
blue = [0, 0, 65]
sla(scm([], blue, (20, 20, 40)))
brown = [100, 49, 0]
sla(scm([], brown, (41, 45, 40)))
yellowgreen = [50, 100, 10]
sla(scm([], yellowgreen, (50, 50, -2)))
gray = [49, 59, 69]
sla(scm([], gray, (39, 29, 19)))
violet = [75, 0, 26]
sla(scm([], violet, (43, 33, 48)))
yellow = [105, 105, 49]
sla(scm([], yellow, (35, 35, -11)))
indigo = [37, 0, 79]
sla(scm([], indigo, (30, 23, 38)))
i = 0
while shade_list:
base = shade_list[i] #list of shades
if base: #base list is not empty
shade = base.pop()
cl.append(shade)
else: #out of shades for that base color
shade_list.pop(i)
i += 1
if i >= len(shade_list):
i = 0
self.assign_contrast_colors(cl, ipa_vl)
def build_color_lists(self, bcl, base, sups):
'''cl is a list of values to use as the "base color"
vl is a list of vowel names which should match the keys in color map
sups is a tuple of ints used to increment (r, g, b)'''
#recall color(0, 0, 0) = black, color(255, 255, 255) = white
a, b, c = sups
c1, c2, c3 = base[0], base[1], base[2]
while (c1 <= 255 and c1 >= 0 and
c2 <= 255 and c2 >= 0 and
c3 <= 255 and c3 >= 0):
new_color = (c1, c2, c3)
bcl.append(new_color)
c1 += a
c2 += b
c3 += c
return bcl
def assign_contrast_colors(self, cl, vwl_li):
'''
Assign the colors to prototypes in Convention.
Uses a dictionary where key is prototype name, value is color.
'''
pl = [v.name for v in vwl_li]
i = 0
color = color_rgb
if not self.color_on:
for p in vwl_li:
self.color_map[p] = color(150, 150, 150)
return
while (pl and cl):
r, g, b = cl.pop()
p = pl.pop()
self.color_map[p] = color(r, g, b)
#print(p, ":", r, g, b) #see what shade is assigned to which proto
def plot_spots(self, pause = 0, mc = 1, s = None):
'''
Plots the list of active Prototypes.
pause is the number of seconds window will stay open.
pause = 0 will wait for mouse click to close
mc is minimum carriers (a number of agents)
s is the text which will appear below the vowel chart.
Used in step reports if Game_fns.show is on.
'''
#redraw window if necessary, but don't make a duplicate
if (not self.win or self.win.isClosed()):
self.win = self.formant_space(s)
win = self.win
#set heights for labels
h_side = self.win_margin - 20
h = self.chart_h + 130 #int(win.getHeight()*.92)
#set up text
h2 = h + 30 #next line
cp = self.proto_dict.values()
if not cp:
cp = self.ipa_dict.values() #used in plot_protos()--show all
protos = []
for p in cp:
#if p.carriers >= mc:
p_class = "".join(re.findall("[a-zA-Z_:]+", p.name))
if p_class not in protos:
protos.append(p_class)
#reset list so we know last step has been cleared
curr_proto_pts = list()
coord = self.proto_to_xy #converts Prototype to x, y coordinates
#update the printout of prototypes
if self.color_on:
w = self.chart_w+(self.win_margin*2)+145
message1 = self.side_label("Convention Vowels", w, h_side)
message2 = self.label(self.param_str, h)
else:
message3 = self.label("Currently Active Prototypes:", h)
#if there are a lot of prototypes, break into lines
if len(protos) > 11:
vl1 = "["+("], [".join([v for v in protos[:11]]))+"],"
vl2 = "\n ["+("], [".join([v for v in protos[11:]]))+"]"
proto_names = vl1+vl2
else:
proto_names = "["+("], [".join([v for v in protos]))+"]"
#if there are a shit ton of prototypes, decrease the font size
if len(protos) > 24:
message2 = self.label(proto_names, h2, 8)
#otherwise, leave it alone
else:
message2 = self.label(proto_names, h2)
if not self.proto_label:
message3.draw(win)
if (not self.updating_label and message1):
message1.draw(win)
#message2.draw(win)
self.updating_label = message2
#draw the side chart with the colored spots and proto names
self.draw_color_map()
#draw all prototypes with enough carriers
#these are the spots outlined in black (i.e. the mean centers)
pts = cp
if pts:
for pt in pts:
x, y = coord(pt)
circle = Circle(Point(x, y), 6)
if "[" in pt.name:
p_class = ((pt.name).split("[")[2])[:-1] #"".join(re.findall("[a-zA-Z_:]+", pt.name))
else:
p_class = "".join(re.findall("[a-zA-Z_:]+", pt.name))
if self.color_on:
color = self.color_map[p_class]
else:
color = 'black'
circle.setFill(color) #mean center fill color
circle.setOutline('black') #mean center outline color
circle.setWidth(1) #width (thickness) of outline
circle.draw(win)
curr_proto_pts.append(circle) #store so we can undraw later
#undraw the previous step sampling if it is still showing
if self.curr_proto_pts:
for p in self.curr_proto_pts:
p.undraw()
self.curr_proto_pts = curr_proto_pts
#if pause is 0, wait for user to click before moving on
if pause is 0:
print("(Click on the chart to continue.)")
win.getMouse()
def plot_symbols(self, pause = 0, mc = 1, s = None):
'''
plot symbols using ipa_trans table instead of spots
Plots the list of active Prototypes.
pause is the number of seconds window will stay open.
pause = 0 will wait for mouse click to close
mc is minimum carriers (a number of agents)
s is the text which will appear below the vowel chart.
Used in step reports if Game_fns.show is on.
'''
#redraw window if necessary, but don't make a duplicate
if (not self.win or self.win.isClosed()):
self.win = self.formant_space(s)
win = self.win
#set heights for labels
h_side = self.win_margin - 20
h = self.chart_h + 130 #int(win.getHeight()*.92)
#set up text
h2 = h + 30 #next line
cp = self.proto_dict.values()
if not cp:
cp = self.base_vowel_dict.values() #used in plot_protos()--show all
protos = []
for p in cp:
#if p.carriers >= mc:
p_class = "".join(re.findall("[a-zA-Z_:]+", p.name))
if p_class not in protos:
protos.append(p_class)
#reset list so we know last step has been cleared
curr_proto_pts = list()
coord = self.proto_to_xy #converts Prototype to x, y coordinates
#update the printout of prototypes
if self.color_on:
w = self.chart_w+(self.win_margin*2)+145
message1 = self.side_label("Convention Vowels", w, h_side)
message2 = self.label(self.param_str, h)
else:
message3 = self.label("Currently Active Prototypes:", h)
#if there are a lot of prototypes, break into lines
if len(protos) > 11:
vl1 = "["+("], [".join([v for v in protos[:11]]))+"],"
vl2 = "\n ["+("], [".join([v for v in protos[11:]]))+"]"
proto_names = vl1+vl2
else:
proto_names = "["+("], [".join([v for v in protos]))+"]"
#if there are a shit ton of prototypes, decrease the font size
if len(protos) > 24:
message2 = self.label(proto_names, h2, 8)
#otherwise, leave it alone
else:
message2 = self.label(proto_names, h2)
if not self.proto_label:
message3.draw(win)
if not self.updating_label:
message1.draw(win)
#message2.draw(win)
self.updating_label = message2
#draw the side chart with the colored spots and proto names
self.draw_color_map(True)
#draw all prototypes with enough carriers
#these are the spots outlined in black (i.e. the mean centers)
pts = cp
if pts:
for pt in pts:
x, y = coord(pt)
circle = Circle(Point(x, y), 6)
#find out the vowel's 'true identity'
if "[" in pt.name:
p_class = ((pt.name).split("[")[2])[:-1] #"".join(re.findall("[a-zA-Z_:]+", pt.name))
else:
p_class = "".join(re.findall("[a-zA-Z_:]+", pt.name))
#use color-coding for symbol to match dots
if self.color_on:
color = self.color_map[p_class]
else:
color = 'black'
tp = Point(x, y) #proto's location in the chart
symb = ipa_trans[p_class] #proto's name (may be unicode)
#black outlines of the symbols
proto_symb_stroke = self.get_symbol_obj(symb, tp, 30, 'gray4', 'bold')
proto_symb_stroke.draw(win)
curr_proto_pts.append(proto_symb_stroke) #store so we can undraw later
if self.color_on:
proto_symb = self.get_symbol_obj(symb, tp, 30, color)
proto_symb.draw(win)
curr_proto_pts.append(proto_symb)
#undraw the previous step sampling if it is still showing
if self.curr_proto_pts:
for p in self.curr_proto_pts:
p.undraw()
self.curr_proto_pts = curr_proto_pts
#if pause is 0, wait for user to click before moving on
if pause is 0:
print("(Click on the chart to continue.)")
win.getMouse()
def get_symbol_obj(self, symb, loc, size, color, style = ""):
'''
returns the Text object, ready to be drawn in a window.
'''
proto_symb = Text(loc, symb)
proto_symb.setFace('arial')
proto_symb.setSize(size)
proto_symb.setTextColor(color)
if style:
proto_symb.setStyle(style)
return proto_symb
def label(self, m, height, size = 10, color = 'black'):
'''
returns a centered text label, which can be drawn
m is the text to be printed i.e. String
height is height in window (the y coord) i.e. int
size is the font size for the text i.e. int (default 10)
color is the color of the text (default 'black) i.e. String
'''
if not self.win:
return
win = self.win
tp = Point(win.getWidth()*.4, height)
message = Text(tp, m)
message.setTextColor(color)
message.setSize(size)
return message
def side_label(self, m, w, height, color = 'black'):
'''
returns a left-side Label, which can then be drawn
m is the text to be printed i.e. String
height is height in window (the y coord) i.e. int
size is the font size for the text i.e. int (default 10)
color is the color of the text (default 'black) i.e. String
'''
if not self.win:
return
win = self.win
if self.color_on:
tp = Point(w, height)
else:
tp = Point(win.getWidth()/2, height)
message = Text(tp, m)
message.setSize(11)
message.setTextColor(color)
return message