-
Notifications
You must be signed in to change notification settings - Fork 0
/
Agent.py
1285 lines (984 loc) · 34.6 KB
/
Agent.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 Convention, Prototype, Game_fns, Vowel
Last update November 2017 HJMS'''
#For now, these are just arbitrary numbers, but that may change
def e1_max():
return 14.5 #first formant maximum in ERB
def e1_min():
return 6.8 #first formant minimum in ERB
def e2_max():
return 23.25 #second formant max
def e2_min():
return 12.5 #second formant minimum
max_e1 = e1_max()
min_e1 = e1_min()
max_e2 = e2_max()
min_e2 = e2_min()
import Vowel, Word, datetime
from random import uniform, randint
class Agent:
"""Agents have
#a vowel repertoire (initially empty list of Vowels),
#a vocabulary (initially empty dictionary of Prototype->Word),
#an age (initially zero),
#a binary discern/ignore length flag,
#perception in ERB units"""
def __init__(self, g, a, perc, prox, phone_radius, noise, lf, adapt, prestige):
'''Arguments: generation number gen and agent index a.
repertoire is initially empty'''
self.group = g #agents are appended to the population in groups
self.ind = a #agent's index within its group
self.repertoire = [] #list of Vowels an agent "knows"
self.idio = dict() #of the form {"word.id": word}
self.length_flag = lf #True means the agent recognizes long vs short
self.age = 0 #agents are removed when they reach an age limit
self.perception = perc #margin within which vowels are matched (neighbor search distance)
self.phone_radius = phone_radius #guess_by_margin radius; internal representation accuracy
self.phone_radius_noise = noise #phonetic representation (noise added to copy of word.proto)
self.prox_margin = prox #margin within which vowels conflict
self.name = (str(self.group)+str(self.ind)) #String id
self.chosen = False #micro view highlights a single agent
self.family = [] #list of agent ids in this agent's "nuclear family"
self.wall_bias = True
self.adaptive = adapt #defunct
self.prestige = prestige #defunct
self.pot_spreadables = ["nasal", "labial", "rounded"]
def set_phone_radius(self, prod):
self.phone_radius = prod
def set_noise(self, noise):
self.phone_radius_noise = noise
def print_vocab(self):
words = self.idio.values()
if (not words):
print("(Baby--no vocabulary yet)")
else:
print("\n{0:25}\t{1:14}\t{2:15}".format("Word", "Agent's Vowel", "Formant Values"))
for w in sorted(words, key=lambda w: w.id):
#
#use get_vowel() for the utterance instead of internal representation
p = w.percept
original_nuc = w.id.split("][")[1]
if p.name != original_nuc: #detect whether vowel has changed
print("{0:25}>\t{1:14}\t{2:15}".format(w.id, p.name, str(p)))
else:
print("{0:25}\t{1:14}\t{2:15}".format(w.id, p.name, str(p)))
def get_vocab_str(self):
si = []
if self.age <= 1:
return("baby")
else:
si.append("{0:25}{1:14}{2:15}".format("Word", "Agent's Vowel", "Formant Values"))
for w in sorted(self.idio.values(), key=lambda w: w.id.split("][")[1]):
p = w.percept
original_nuc = w.id.split("][")[1]
if p.name != original_nuc: #detect whether vowel has changed
si.append("{0:25}>\t{1:14}{2:15}".format(w.id, p.name, str(p)))
else:
si.append("{0:25}\t{1:14}{2:15}".format(w.id, p.name, str(p)))
si_str = "\n".join(si)
return si_str
def print_rep(self):
for v in self.repertoire:
print(v.name+": ", v)
def get_rep_set(self, match_vowel):
'''returns a list which is the agent's rep as a set
the vowels in the list are mean centers of vowels
grouped by convention prototype counterpart
Renames vowels which have merged/shifted'''
V = Vowel.Vowel
rep_set_dict = dict()
rep_set = list()
for v in self.repertoire:
real_name = match_vowel(v).name
v.name = real_name
if v.name in rep_set_dict:
rep_set_dict[v.name].append(v)
else:
rep_set_dict[v.name] = [v]
for (v_name, v_list) in rep_set_dict.items():
n = len(v_list)
e1 = (sum([v.e1 for v in v_list]) / n)
e2 = (sum([v.e2 for v in v_list]) / n)
l = (sum([v.length for v in v_list]) / n)
proto_vowel = V(e1, e2, l, v_name)
rep_set.append(proto_vowel)
return rep_set
def guess_by_margin(self, unknown_v):
#radius = perception margin in ERB units
#imitation will be a randomly selected point inside this circle
radius = self.phone_radius
if not radius:
return self.copy_vowel(unknown_v)
e1 = unknown_v.e1
e2 = unknown_v.e2
l = int(unknown_v.length)
#find the domain of circle fn to get x-coord (f2 value)
left = e2 + radius
right = e2 - radius
rand_x = uniform(right, left) #generate x
#find the range for y-coord (f1 value at x = rand_x)
floor, c = circle_range(rand_x, e2, e1, radius)
ceiling = min(rand_x, c) #constraint: f1 <= f2
rand_y = uniform(floor, ceiling) #generate y
#constraint: length of imitation needs to be in range [100..300]
#random number in that range and within original length+-50
length_min = max([100, (l - 25)])
length_max = min([length_min+50, 300])
new_e1, new_e2 = rand_y, rand_x
new_length = randint(length_min, length_max)
w = unknown_v.name #match the name for the incoming signal
if new_e1 > max_e1:
new_e1 = max_e1
if new_e2 > max_e2:
new_e2 = max_e2
if new_e1 < min_e1:
new_e1 = min_e1
if new_e2 < min_e2:
new_e2 = min_e2
new_v = Vowel.Vowel(new_e1, new_e2, new_length, w)
new_v.set_features(max_e1, max_e2, min_e1, min_e2)
return new_v
def inc_age(self):
'''Increments the agent's age'''
self.age += 1
def purge_vwls(self):
#self.weigh_vowels()
vocab = self.idio.values()
dist_vwls = set([w.percept for w in vocab])
#rep = [v for v in self.repertoire if v.weight > 0]
self.repertoire = list(dist_vwls)
for w in self.idio.values():
w.fixed = True
def euc(self, v, w):
e1_dif = (v.e1 - w.e1)
e2_dif = (v.e2 - w.e2)
return ((e1_dif * e1_dif) + (e2_dif * e2_dif))**.5
#MATCHING
######## CASES ##############################################
#children #
# ( New vowel + new word ) | ( New vowel + known word ) #
# ( Known vowel + new word ) | ( Known vowel + known word)#
# #
#babies #
# New vowel | Known vowel #
#############################################################
def call_matchers_nh(self, w):
'''
Match the vowel, then the word if age > 0
use assimilation/deassimilation
resist homophone creation
'''
w_form = w.get_form() #may be an alternation
inc_vwl = w_form.get_vowel()
corr_vwl = self.dissimilate( (w.onset, inc_vwl, w.coda) )
v = self.vowel_match_nh(corr_vwl, w)
if self.chosen:
print("\nAgent", self.name, "hears", w.id, inc_vwl, "corrects to", corr_vwl, end=", ")
if v is None: #new vowel or possibly homophone avoidance
v = self.vowel_match_rb(corr_vwl)
if v is None: #definitely a new vowel
#? should babies use corr_vwl or inc_vwl?
v = self.guess_by_margin(corr_vwl) #generate an imitation within margin
self.add_vowel(v) #add vowel to rep
if self.chosen:
print("adds", v, "to repertoire", end=" ")
else: #known vowel
v.weight += .001 #crude priming
if self.chosen: #micro view printing
print("matches vowel to", v, end=" ")
if self.age > 0: #baby--agents under 1 only hear the vowel
self.word_match(v, w) #child--add word to vocabulary
#micro view printing and micro change detection
if self.chosen:
ivn = inc_vwl.name
vn = v.name
if ivn != vn:
print("\n", ivn, ">", vn)
if self.adaptive:
print( "\nPerception = {0:.4f}".format(self.perception), end=" ")
return v
def call_matchers(self, w):
'''
Match the vowel, then the word if age > 0
This is the method used if 'armchair mode' is on
'''
#speaker uses the word
formed_word = w.get_form() #word object; may be an alternation
inc_vwl = formed_word.get_vowel() #vowel object; assimilation
#listener processes the word
corr_vwl = self.dissimilate( (w.onset, inc_vwl, w.coda) )
v = self.vowel_match(corr_vwl, w)
if self.chosen:
print("\nAgent", self.name, "hears", w.id, inc_vwl, "corrects to", corr_vwl, end=", ") #Cases:
#if no match was found, babies will expand their repertoire
if v is None:
if self.age < 1: #new vowel
#? should babies use corr_vwl or inc_vwl?
#^This is why we need intelligent agents in a MAS...
v = self.guess_by_margin(corr_vwl) #generate an imitation within margin
self.add_vowel(v) #add vowel to rep
if self.chosen:
print("adds", v, "to repertoire", end=" ")
else: #Agent couldn't find a match, but isn't a baby (not good)
whole_rep = [phone for phone in self.repertoire]
#print("*Something's not right in 'Agent.call_matchers()'")
print("*Agent couldn't find a match for", corr_vwl)
v = self.rec_vowel_match(corr_vwl, whole_rep)[0] #nothing matched the length
print("*Found possible match", v, ". Check phonology coarticulation functions.")
else: #known vowel
if self.chosen: #micro view printing
print("matches vowel to", v, end=" ")
#BABIES WEIGHING VOWELS
if self.age < 1:
v.weight += .001
if self.prox_margin:
#t0 = datetime.datetime.now()
self.settle_conflicts()
#t1 = datetime.datetime.now()
#dif = t1 - t0
#print(dif)
if self.age > 0: #baby--agents under 1 only hear the vowel
self.word_match(v, w) #child--add word to vocabulary
#micro view printing and micro change detection
if self.chosen:
ivn = inc_vwl.name
vn = v.name
if ivn != vn:
print("\n", ivn, ">", vn)
if self.adaptive:
print( "\nPerception = {0:.4f}".format(self.perception), end=" ")
return v
def call_matchers_no_coart(self, w):
'''
DEFUNCT
Match the vowel, then the word if age > 0
'''
inc_vwl = w.get_vowel()
v = self.vowel_match_rb(inc_vwl)
if self.chosen:
print("\nAgent", self.name, "hears", w.id, inc_vwl, end=", ")
if v is None:
v = self.guess_by_margin(inc_vwl) #generate an imitation within margin
self.add_vowel(v) #add vowel to rep
if self.chosen:
print("adds", v, "to repertoire", end=" ")
else:
if self.chosen:
print("matches vowel to", v, end=" ")
if self.age > 0: #agents under 1 only hear the vowel
self.word_match(v, w) #add word to vocabulary
if (self.chosen and self.adaptive):
print( "\nPerception = {0:.4f}".format(self.perception), end=" ")
return v
def add_vowel(self, v):
#work-around just appends vowel directly without filtering
self.append_vowel(v)
#Here's where you can toggle agent functions
def vowel_match(self, v, w):
#with homophone avoidance
#children use perceptual margin
#self.vowel_match_nh(v, w)
#with no lexical preservation
#children use perceptual margin
#self.vowel_match_rb(v)
#with homophone tolerance
#children do not use perceptual margin (babies do)
if self.age < 1:
return self.vowel_match_rb(v)
else:
return self.vowel_match_armchair(v)
def vowel_match_nh(self, v, w):
'''
with homophone resistance
v is the vowel being heard
w is the context of the vowel (v is w's nucleus)
'''
vl = v.length <= 200
vpd = self.euc
closest = 999
heaviest = 0
best_phone = None
isa_baby = self.age < 1
perc = self.perception
nh = self.no_homo
def lm(vi, p):
#ld = ( (p.length > 200) == (v.length > 200) ) #old method
diff = abs(p.length - vi.length)
ld = diff <= (p.length * .5) #signal length is within 50% difference of phone length
return ld
lf = self.length_flag
if lf:
rep = ((p, vpd(v, p)) for p in self.repertoire if (lm(v, p) and (vpd(v, p) <= perc)) )
else:
rep = ((p, vpd(v, p)) for p in self.repertoire if (vpd(v, p) <= perc))
for (phone, d) in rep:
if isa_baby: #pick the closest
if d < closest:
best_phone = phone
closest = d
else: #pick the heaviest that doesn't create homophone
if ( ( (phone.weight > heaviest) or ( (not heaviest) and (d < closest) )) and
nh(phone, w) ):
best_phone = phone
heaviest = phone.weight
closest = d
return best_phone
def no_homo(self, phone, w):
'''
True when adding the word with phone as nucleus would NOT create a homophone
where a homophone is multiple meanings (word IDs) mapped to a single phonetic sequence
example: speaker says "bed" with nucleus [epsilon],
listener applies deassimilation and finds a nearby phone [I]
which is mapped to "bid" already.
This would create a homophone where [b][I][d] is mapped to both
"[b][I][d]" and "[b][epsilon][d]".
The listener would not allow the micro-change,
so would either choose another nearby phone or add a new one,
i.e. not recognize the match
Will always return True if the agent has
'''
w_ons = w.onset
w_cod = w.coda
w_nuc = w.nucleus
phone_n = phone.name
pot_w = Word.Word(w_ons, w_nuc, w_cod)
if (phone_n != w_nuc and pot_w.id in self.idio):
return False
return True
def length_matcher(self, incom_v, intern_p):
diff = abs(incom_v.length - intern_p.length)
ld = diff <= (intern_p.length * .5) #signal length is within 50% difference of phone length
return ld
def vowel_match_armchair(self, v):
'''
no perception margin
uses length matching
no homophone consideration
'''
lm = self.length_matcher
rep = [phone for phone in self.repertoire if lm(v, phone)]
match = None
if len(rep):
match = self.rec_vowel_match(v, rep)[0]
if not match:
print("Something's wrong with the armchair matching")
return match
def vowel_match_rb(self, p):
'''look for a vowel in repertoire within perceptual margin radius'''
# vvvv RB code
'''lf = self.length_flag
euc = self.euc
nearest_dist = 999
margin = max([0, self.perception])
nearest = None
dist = 999
perception = self.perception
for e in self.repertoire:
if ( (not lf) or
( lf and
( (e.length < 200) is (p.length < 200) ) ) ):
dist = euc(e, p)
if (dist < nearest_dist and dist <= margin):
nearest = e
nearest_dist = dist
return nearest'''
#p is the incoming signal
def lm(v):
#ld = ( (p.length > 200) == (v.length > 200) ) #old method
diff = abs(p.length - v.length)
ld = diff <= (v.length * .5) #signal length is within 50% difference of phone length
return ld
lf = self.length_flag
if lf:
rep = [v for v in self.repertoire if lm(v)]
else:
rep = self.repertoire
#find the closest acoustic match
def rec_vowel_match(vwls):
if len(vwls) < 2:
d0 = self.euc(p, vwls[0])
return (vwls[0], d0)
else:
l = len(vwls)
m = int(l/2)
l_c, l_d = rec_vowel_match(vwls[:m])
r_c, r_d = rec_vowel_match(vwls[m:])
if l_d < r_d:
return(l_c, l_d)
return(r_c, r_d)
#find the heaviest match
#if no potentials have weight, find the closest
perc = self.perception
def heaviest_match(vwls):
neighbors = [v1 for v1 in vwls if ( (p.euc(v1) <= perc) )] # (v1.weight > 0) and
if (not neighbors and len(vwls)):
return rec_vowel_match(vwls)
if (len(neighbors) > 1 and self.adaptive):
self.perception = max([0, (self.perception-self.adaptive)]) #recognize a crowded system
self.phone_radius = max([0, (self.phone_radius-self.adaptive)]) #imitate signals more closely
heaviest = neighbors[0]
for neighbor in neighbors:
if neighbor.weight > heaviest.weight:
heaviest = neighbor
distance = p.euc(heaviest)
return (heaviest, distance)
if rep:
c_v, c_d = heaviest_match(rep)
if c_d <= self.perception:
return c_v
elif self.adaptive: #the closest vowel is not within perception margin
self.perception += (self.adaptive/2) #adjust agent's perception
return None
def rec_vowel_match(self, p, vwls):
'''
find the closest acoustic match
'''
if len(vwls) < 2:
d0 = self.euc(p, vwls[0])
return (vwls[0], d0)
else:
l = len(vwls)
m = int(l/2)
l_c, l_d = self.rec_vowel_match(p, vwls[:m])
r_c, r_d = self.rec_vowel_match(p, vwls[m:])
if l_d < r_d:
return(l_c, l_d)
return(r_c, r_d)
def word_match(self, v, w):
'''match known word or add new word.
If the word is 'fixed' i.e. not in probationary period,
then the agent doesn't respond.
Otherwise, it adds to the word's history and re-weighs its vowels'''
wi = w.id
if wi in self.idio:
word = self.idio[wi]
word.add_hist(v)
if self.chosen:
print(", updates", w.id, end="")
else:
pn = self.phone_radius_noise
new_word = Word.Word(w.onset, w.nucleus, w.coda, None, pn)
new_word.add_hist(v)
self.idio[wi] = new_word
if self.chosen:
print(", adds", w.id, "to vocabulary", end="")
#update weights
#self.weigh_vowels()
#uncomment both of these to reinstate conflict resolution
#self.settle_conflicts()
#self.weigh_vowels()
def weigh_vowels(self):
'''Vowels are weighed according to the number of words using them'''
if self.age > 0:
vocab = self.idio.values()
vocab_size = len(vocab)
rep = [v for v in self.repertoire]
for i in range(len(rep)):
v = rep[i]
count = 0
#words = [w.vowel for w in vocab if w.vowel is v]
#count = len(words)
for w in vocab:
if w.percept is v:
count += 1
####WEIGHT WEIGHT
if (count and vocab_size):
v.weight = min([(count/vocab_size)* 10, 5])
#v.weight = (count/vocab_size)
else:
v.weight = 0
def settle_conflicts(self):
'''settle proximity confrontations between neighboring vowels
only iterate through original repertoire once
i.e. don't settle conflicts from results of resolutions
otherwise it may never terminate'''
rep = [v for v in self.repertoire]
perc = self.perception
ld = self.length_matcher
for i in range(len(rep)):
v = rep[i]
if v.weight:
prox = v.weight + self.prox_margin
prox = max( 0, prox )
v.neighbors = [v1 for v1 in rep[i+1:] if ( v1.weight and (v.euc(v1) <= prox) and ld(v, v1))]
while v.neighbors:
n = v.neighbors.pop()
if v in n.neighbors:
n.neighbors.remove(v)
self.settle(v, n)
def copy_vowel(self, v):
V = Vowel.Vowel
nv = V(v.e1, v.e2, v.length, v.name)
nv.weight = v.weight
return nv
def get_midpt(self, v1, v2):
nv_e1 = int( (v1.e1 + v2.e1) / 2 )
nv_e2 = int( (v1.e2 + v2.e2) / 2 )
if nv_e1 > nv_e2:
nv_e1 = nv_e2
nv_l = int( (v1.length + v2.length) / 2 )
###########################################################
#Not sure what to do here...
#If the names don't match then new vowel should be compared
#to the convention prototypes, except we can't access those
#Maybe if the names match they should merge to one vowel
#but if the names differ they should join to form a diphthong?
##############################################################
name = v1.name
nv = Vowel.Vowel(nv_e1, nv_e2, nv_l, name)
for w in self.idio.values():
w.merge_midpoint(v1, v2, nv)
return nv
def settle(self, v1, v2):
'''Determine whether a vowel needs to shift/merge'''
#Chance to avoid (shift_away) or merge (merge_abs)
merge_chance = 49
#merge_chance = 0 -> merging only
#merge_chance = 100 -> shifting only
if (v1 in self.repertoire and
v2 in self.repertoire):
#cases:
# v has higher functional load:
# n avoids v or is absorbed
# n has higher functional load:
# v avoids n or is absorbed
# n and v have equal functional load:
# v and n merge to midpoint
if (v1.weight == v2.weight):
if (not v1.weight):
return
else:
self.merge_mid(v1, v2)
return
elif v1.weight < v2.weight:
weaker = v1
stronger = v2
else:
weaker = v2
stronger = v1
roll = randint(1, 100)
if self.prox_margin <= 0:
return
if (roll > merge_chance or
weaker.weight is 0): #adding rule: weightless vowels get automatically absorbed
self.merge_abs(weaker, stronger)
else:
if self.wall_bias:
self.shift_wall_bias(weaker, stronger)
else:
self.shift_away(weaker, stronger)
def merge_mid(self, v1, v2):
'''two vowels of equal fnl load merge to their midpoint'''
nv_e1 = ( (v1.e1 + v2.e1) / 2 )
nv_e2 = ( (v1.e2 + v2.e2) / 2 )
if nv_e1 > nv_e2:
nv_e1 = nv_e2
nv_l = int( (v1.length + v2.length) / 2 )
###########################################################
#Not sure what to do here...
#If the names don't match then new vowel should be compared
#to the convention prototypes, except we can't access those
#UPDATE: Convention fixes this in get_rep_set method
# ^Not a great fix
#Maybe if the names match they should merge to one vowel
#but if the names differ they should join to form a diphthong?
##############################################################
#name = ""
name = v1.name
nv = Vowel.Vowel(nv_e1, nv_e2, nv_l, name)
nv.weight = v1.weight + v2.weight
#
if self.chosen:
print("\nCONFLICT:", v1, "and", v2, "merging to midpoint at", nv)
v1n = v1.name
v2n = v2.name
nvn = nv.name
if v1n != nvn:
print(v1n, ">", nvn)
if v2n != nvn:
print(v2n, ">", nvn)
for w in self.idio.values():
w.merge_midpoint(v1, v2, nv)
rep = self.repertoire
rep.remove(v1)
rep.remove(v2)
rep.append(nv)
def merge_abs(self, weaker_vwl, stronger_vwl):
'''stronger vowel absorbs the other'''
if self.chosen:
print("\nCONFLICT:", weaker_vwl, "absorbed by", stronger_vwl)
wvn = weaker_vwl.name
svn = stronger_vwl.name
if wvn != svn:
print(wvn, ">", svn)
if (weaker_vwl in self.repertoire and stronger_vwl in self.repertoire):# and weaker_vwl is not stronger_vwl):
sv = stronger_vwl
words = [w for w in self.idio.values() if w.has_record(weaker_vwl)]
for w in words:
w.merge_absorb(weaker_vwl, sv)
#
self.repertoire.remove(weaker_vwl)
def shift_wall_bias(self, wv, sv):
'''
shift the weaker vowel away with biasing
weaker vowel tries to escape boundaries and stronger vowel
weaker vowel calculates sum distance from nearby walls + stronger vowel
and picks the direction (up/down/left/right) with max sum distance
'''
wv_c = self.copy_vowel(wv)
words = [w for w in self.idio.values() if w.has_record(wv_c)]
ne2, ne1 = self.get_dest(wv, sv)
wv.e1 = ne1
wv.e2 = ne2
if sv.length > wv.length:
if wv.length - 10 > 100:
wv.length -= 10
elif wv.length + 10 < 300:
wv.length += 10
for word in words:
ind = word.vowel_record_i(wv_c)
v, counts = word.vowel_hist.pop(ind)
if counts > word.vowel_hist[0][1]:
word.vowel_hist.insert(0, (wv, counts))
else:
word.vowel_hist.append((wv, counts))
#
if self.chosen:
print("\nCONFLICT:", wv_c, "shifting away from", sv, "to new position", wv)
wvcn = wv_c.name
wvn = wv.name
if wvcn != wvn:
print(wvcn, ">", wvn)
def get_dest(self, weaker_vwl, stronger_vwl):
wv = weaker_vwl
sv = stronger_vwl
wve1 = wv.e1
wve2 = wv.e2
dist = self.coord_dist
perc = self.perception
margin = (perc*2) #use diameter instead of radius
#figure out if there are any walls to avoid
w_above = ( (wve1 - margin) <= min_e1 ) #there is a wall above within margin distance
w_below = ( (wve1 + margin) >= max_e1 )
w_left = ( (wve2 + margin) >= max_e2 )
w_right = ( (wve2 - margin) <= min_e2 )
#make a list of positions we want to avoid
avoid_li = [(sv.e2, sv.e1)] #the stronger vowel
ala = avoid_li.append
pos_li = []
pla = pos_li.append
#if the wall is in range, add the coordinates
#to the list of positions to prioritize distance from
#and cut off the direction at the limit
#otherwise, add the coordinates
#to the list of potential new positions
#note: di_perc has a margin of error of approx ( 4 / (10^15) )
di_perc = ( (perc*perc)/2.0) ** (.5) #convert diagonal distance to formant adjustment amount
ur = ( (wve2-di_perc), (wve1-di_perc) ) #position if it shifts diagonally up-right
dr = ( (wve2-di_perc), (wve1+di_perc) ) #position if it shifts diagonally down and right
ul = ( (wve2+di_perc), (wve1-di_perc) ) #position if it shifts up-left
dl = ( (wve2+di_perc), (wve1+di_perc) ) #position if it shifts down-left
if w_above: #there's a wall above--avoid it
up = (wve2, min_e1) #intercept coord of the wall above
ala(up)
else: #there's no nearby wall above, include upward three directions
up = (wve2, (wve1-perc)) #position if it shifts straight upward
pla(up)
if not w_right:
pla(ur)
if not w_left:
pla(ul)
if w_below: #there's a wall below--avoid it
down = (wve2, max_e1) #intercept coord of the wall below
ala(down)
else:
down = (wve2, (wve1+perc)) #position if it shifts downward
pla(down)
if not w_right:
pla(dr)
if not w_left:
pla(dl)
if w_left: #there's a wall to the left
left = (max_e2, wve1) #intercept coordinates to the left
ala(left)
else:
left = ((wve2+perc), wve1) #position if it shifts left
pla(left)
if not w_above:
pla(ul)
if not w_below:
pla(dl)
if w_right: #there's a wall to the right
right = (min_e2, wve1) #intercept coord to the right
ala(right)
else:
right = ((wve2-perc), wve1) #position if it shifts right
pla(right)
if not w_above:
pla(ur)
if not w_below:
pla(dr)
#mind the e1 < e2 constraint
if (wve1 + margin) >= wve2:
ala( (wve2, (wve1+margin)) )
if (wve2 - margin) < wve1:
ala( ((wve2-margin), wve1) )
best_pos = (wve2, wve1)
best_dist = wv.euc(sv)
for position in pos_li: #for each potential new location
total_dist = sum([dist(p, position) for p in avoid_li]) #sum distance from all points to avoid
if total_dist > best_dist:
best_dist = total_dist
best_pos = position
return best_pos
def coord_dist(self, p1, p2):
'''yet another euc method, but for coordinates'''
p1x, p1y = p1
p2x, p2y = p2
return (((p1y - p2y)**2) + ((p1x - p2x)**2))**.5
def shift_away(self, weaker_vwl, stronger_vwl):
'''weaker vowel moves away from stronger one
distance is currently 1% of perception'''
#move dist = 10% of perceptual margin away from stronger vowel
dist = self.perception #* .1
wv = weaker_vwl
wv_c = self.copy_vowel(wv)
sv = stronger_vwl
words = [w for w in self.idio.values() if w.has_record(wv_c)]
if sv.e1 > wv.e1:
wv.e1 -= dist
if wv.e1 <= min_e1:
wv.e1 += dist
else:
wv.e1 += dist
e1_constraint = wv.e2 - wv.e1
if (e1_constraint < 0 or wv.e1 >= max_e1):
wv.e1 -= dist
if sv.e2 > wv.e2:
wv.e2 -= dist
e1_constraint = wv.e2 - wv.e1
if (e1_constraint < 0 or wv.e2 <= min_e2):
wv.e2 += dist
else:
wv.e2 += dist
if wv.e2 >= self.max_e2:
wv.e2 -= dist
if ((sv.length > wv.length) and (wv.length - 10 > 100)):
wv.length -= 10
elif (wv.length + 10 < 300):
wv.length += 10
for word in words:
ind = word.vowel_record_i(wv_c)
v, counts = word.vowel_hist.pop(ind)
if counts > word.vowel_hist[0][1]:
word.vowel_hist.insert(0, (wv, counts))
else:
word.vowel_hist.append((wv, counts))
#
if self.chosen:
print("\nCONFLICT:", wv_c, "shifting away from", sv, "to new position", wv)