-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgroupFormation_identity.nlogo
3227 lines (2857 loc) · 96.2 KB
/
groupFormation_identity.nlogo
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
;; Model for study of mutual interaction between public opinion and network structure.
;; RQ: How polarisation of public opinion shapes the network structure
;; and how the network structure shapes public opinion and influences individual opinions?
;;
;; This code is from project of Mike, Ashley, Ashwin and FranCesko,
;; we apply Hegselmann-Krausse model in more than 1D and look how agents adapt in >1D opinion space and whether they form groups,
;; then we include small-world network (Watts-Strogatz) as another constraint, features of spiral of silence, and
;; individual assignment of uncertainity, tollerance, comformity and outspokeness.
;;
;; !!!EXPERIMENTAL FEATURE: IDENTITY!!!
;; !!!SUPER EXPERIMENTAL: INDIVIDUAL IDENTITY VISION!!!
;;
;; Created: 2021-10-21 FranCesko
;; Edited: 2022-02-09 FranCesko
;; Encoding: windows-1250
;; NetLogo: 6.2.2
;;
;; IDEA: What about simply employ Spiral of Silence?
;; Just simply -- general parameter on scale (0; 1> and probability of speaking her attitude/opinion,
;; baseline is p==1, everybody speaks always, if p==0.5 so everybody has 0.5 probability to speak her opinion/attitude at given step,
;; if succeeds - speaks in given step, if not - falls silent for the respective step.
;; In HK mechanism, agent computes mean opinion of all speaking agents who are inside 'opinion boundary' (are not further than threshold).
;; In Defuant, agent randomly takes one speaking agent inside the 'opinion boundary' and sets opinon as average of their opinions.
;; DONE!
;;
;; IDEA: Handle P-speaking as Uncertainty -- besides constant value for every agent, create random mode (random uniform for the start),
;; where all agents will have their own value of speaking probability which they will follow.
;; DONE!
;;
;; IDEA: Choose, how many opinions agents update: sometimes 1, 2, 3, 4 ...
;; DONE!
;;
;; IDEA: Employ Schelling principle -- if the agents are unhappy in their neighborhood,
;; the cut off all the links and create new set of links, i.e., join new neighborhood.
;; DONE!
;;
;; IDEA: Give weights to opinions... Taken from media, or from interpersonal communication:
;; - agents pick opinion according the importance, and update importance according number of contacts regarding the opinion
;;
;; IDEA: Compute clusters.
;; Elle: I do cluster detection using igraph:: cluster_walktrap() in R
;;
;; WISHLIST:
;; - differentiate between interpersonal communication and social media communication -- two overlapping networks with their own rules
;; - how radicalization is possible? How polarization happens?
;; - differential attraction
;; - repulsion
;; - media exposure will be crucial…we can ask abt opinion consistent content, opinion contrary, and “mainstream/mixed”…
;; how to we conceptualize/model those in ABM? Is this too simplistic (eg, think of the different flavors of conservative media,
;; ranging from CDU type media to extremist hate groups).
;; - how to think about social media influencers (eg Trump before deplatforming)…
;; is it possible to designate “superagents” who influence everyone sharing certain beliefs and see their effects…
;; both reach everyone in a group and their opinions are very highly weighted (or people vary in how much they weight that opinion?
;; Could estimate Twitter effect that way! Perhaps one could even model how movement towards an opinion might influence the superagent
;; to increase communication or change focus…
;; - Employ homophily/heterophily principle at model start.
;; - Control degree of opinion randomness at the start (different mean and SD of opinion for different groups)
;; - Mike was thinking…after we do “superagents”, the Trump/foxnews avatars…one thing that would be neat and represent social reality
;; is to have some kind of attraction to those who share beliefs (including superagents), but that decreases with close proximity…
;; that way we have less ability/willingness to select attitude consistent sources around us (eg can’t escape family and coworkers),
;; but can seek them elsewhere. That might allow us to look at what happens in a more or less diverse local opinion environment, among other things.
;; - Use clustering algorithm for creating group identities
;; TO-DO:
;; 1) constructing file name for recording initial and final state of simulation
;; DONE!
;; 2) implementing recording into the model -- into setup and final steps (delete component detection and just record instead)
;; DONE!
;;
;; 3) Reviewer's comments:
;; The reviewer for your computational model Simulating Components of the Reinforcing Spirals Model and Spiral of Silence v1.0.0 has recommended that changes be made to your model. These are summarized below:
;; Very interesting model! It needs better documentation though, both within the code as comments, and the accompanying narrative documentation. Please consider following the ODD protocol or equivalent to describe your model in sufficient detail so that another could replicate the model based on the documentation.
;; Has Clean Code:
;; The code should be cleaned up and have more comments describing the intent and semantics of the variables.
;; Has Narrative Documentation:
;; The info tab is empty and the supplementary doc does not include sufficient detail to replicate the model. For example documentation please see ODD examples from other peer reviewed models in the library.
;; Is Runnable:
;; Runs well.
;; On behalf of the [email protected], thank you for submitting your computational model(s) to CoMSES Net! Our peer review service is intended to serve the community and we hope that you find the requested changes will improve your model’s accessibility and potential for reuse. If you have any questions or concerns about this process, please feel free to contact us.
;;
;; 4) Adapt recording data for cluster computation -- machine's root independent.
;; DONE!
;;
;; 5) Appropriate recorded data format -- we want it now as:
;; a) dynamical multilayer network, one row is one edge of opinion distance network,
;; b) separate file with agent's traits (P-speaking, Uncertainty etc.)
;; c) as it was before, contextual variables of one whole simulation run are coded in the filenames
;; DONE!
;;
;; 6) Implement K-clusters algorithm for addressing just 2 clusters.
;;
extensions [nw]
breed [centroids centroid]
undirected-link-breed [comms comm]
undirected-link-breed [l-distances l-distance]
turtles-own [Opinion-position P-speaking Speak? Uncertainty Record Last-opinion
Tolerance Conformity Satisfied? group distance_to_centroid Group-threshold Identity-group Opponents-ratio id-threshold-level]
l-distances-own [l-weight]
comms-own [op-weight]
globals [main-Record components positions network-changes agents positions_clusters
polarisation normalized_polarisation unweighted_polarisation unweighted_normalized_polarisation ESBG_polarisation id_threshold_set]
;; Initialization and setup
to setup
;; Redundant conditions which should be avoided -- if the boundary is drawn as constant, then is completely same whether agents vaguely speak or openly listen,
;; seme case is for probability speaking of 100%, then it's same whether individual probability is drawn as constant or uniform, result is still same: all agents has probability 100%.
if avoid-redundancies? and mode = "vaguely-speak" and boundary-drawn = "constant" [stop]
if avoid-redundancies? and p-speaking-level = 1 and p-speaking-drawn = "uniform" [stop]
;; these two conditions cover 7/16 of all simulations, approx. the half! This code should stop them from running.
;; We erase the world and clean patches
ca
ask patches [set pcolor patch-color]
;; We initialize small-world network with random seed
if set-seed? [random-seed RS]
if HK-benchmark? [set n-neis (N-agents - 1) / 2]
nw:generate-watts-strogatz turtles comms N-agents n-neis p-random [
fd (max-pxcor - 1)
set size (max-pxcor / 10)
]
;; To avoid some random artificialities due to small-world network generation,
;; we have to set random seed again.
if set-seed? [random-seed RS]
;; Then we migh initialize agents/turtles
ask turtles [
set Opinion-position n-values opinions [precision (1 - random-float 2) 3] ;; We set opinions...
set Last-opinion Opinion-position ;; ...set last opinion as present opinion...
set Record n-values record-length [0] ;; ... we prepare indicator of turtle's stability, at all positions we set 0 as non-stability...
set P-speaking get-speaking ;; ...assigning individual probability of speaking...
set speak? speaking ;; ...checking whether agent speaks...
set Uncertainty get-uncertainty ;;... setting value of Uncertainty.
set Tolerance get-tolerance ;; Setting individual tolerance level, as well as ...
set Conformity get-conformity ;; setting individual conformity level, and ...
set Group-threshold get-group-threshold ;; Individual sensitivity for group tightness/threshold.
set Identity-group no-turtles ;; Now, we just initialize it, later may be... we use it also here meaningfully.
set Opponents-ratio 0 ;; Fraction of opponents
getColor ;; Coloring the agents according their opinion.
getPlace ;; Moving agents to the opinion space according their opinions.
]
set agents turtle-set turtles ;; Note: If we just write 'set agents turtles', then variable 'agents' is a synonym for 'turtles', so it will contain in the future created centroids!
ask agents [create-l-distances-with other agents] ;; Creating full network for computing groups and polarisation
ask l-distances [set hidden? true] ;; Hiding links for saving comp. resources
compute-identity-thresholds
;; Coloring patches according the number of agents/turtles on them.
ask patches [set pcolor patch-color]
;; Hiding links so to improve simulation speed performance.
ask comms [set hidden? TRUE]
;; Setting the indicator of change for the whole simulation, again as non-stable.
set main-Record n-values record-length [0]
;; Setting communication and distances links' weights
update-links-weights
;; Setting agents' identity groups
ifelse use_identity? [
if identity_type = "global" [set-group-identities]
if identity_type = "individual" [set-individual-group-identities]
][
ask agents [set Identity-group agents]
]
;; update satisfaction
ask agents [set Satisfied? get-satisfaction]
;; Setting control variable of network changes
set network-changes 0
;; Compute polarisation
compute-polarisation-repeatedly
reset-ticks
;;;; Finally, we record initial state of simulation
;; If we want we could construct filename to contain all important parameters shaping initial condition, so the name is unique stamp of initial state!
if construct-name? [set file-name-core (word RS "_" N-agents "_" p-random "_" n-neis "_" opinions "_" updating "_" boundary "_" boundary-drawn "_" p-speaking-level "_" p-speaking-drawn "_" mode)]
;; recording itself
if record? [record-state-of-simulation]
end
;; Just envelope for updating agent at the begining of GO procedure
to set-group-identities
;; Cleaning environment
ask centroids [die]
;; Detection of clusters via Louvain: Detection itself
let selected-agents agents with [2 < count my-l-distances with [l-weight >= id_threshold]] ;; Note: We take into account only not loosely connected agents
nw:set-context selected-agents l-distances with [l-weight >= id_threshold] ;; For starting centroids we take into account only not loosely connected agents, but later we set groups for all.
let communities nw:louvain-communities
;repeat N-agents [set communities nw:louvain-communities]
set N_centroids length communities
;; Computing clusters' mean 'opinion-position'
set positions_clusters [] ;; List with all positions of all clusters
foreach communities [c ->
let one [] ;; List for one position of one cluster
foreach range opinions [o -> set one lput precision (mean [item o opinion-position] of c) 3 one]
set positions_clusters lput one positions_clusters
]
;; Preparation of centroids -- feedeing them with communities
create-centroids N_centroids [
set heading (who - min [who] of centroids)
set Opinion-position item heading positions_clusters ;; We set opinions, we try to do it smoothly...
set shape "circle"
set size 1.5
set color 5 + (who - min [who] of centroids) * 10
getPlace
]
;; Assignment of agents to groups
ask agents [set group [who] of min-one-of centroids [opinion-distance]] ;; Sic! Here we intentionally use all agents, including loosely connected.
;; Computation of centroids possitions
compute-centroids-positions (agents)
;; Iterating cycle -- looking for good match of centroids
while [sum [opinion-distance3 (Last-opinion) (Opinion-position)] of centroids > Centroids_change] [
;; turtles compute whether they are in right cluster and
ask agents [set group [who] of min-one-of centroids [opinion-distance]]
;; Computation of centroids possitions
compute-centroids-positions (agents)
]
;; Saving Identity group as agent-set
ask agents [
set Identity-group agents with [group = [group] of myself]
if count Identity-group < 3 [set Identity-group agents]
]
;; Killing centroids without connected agents
ask centroids [
let wom who
if (not any? agents with [group = wom]) [die]
]
set N_centroids count centroids
;; Final coloring and killing of centroids
if centroid_color? [ask agents [set color (5 + 10 * (group - min [who] of centroids))]]
if killing_centroids? [ask centroids [die]]
end
;to set-individual-group-identities
; ask agents [
; ;; Cleaning environment
; set Identity-group no-turtles
; let my-Group-threshold Group-threshold
;
; ;; Detection of clusters via Louvain: Detection itself
; ;let selected-agents agents with [2 < count my-l-distances with [l-weight >= my-Group-threshold]] ;; Note: We take into account only not loosely connected agents
; nw:set-context agents l-distances with [l-weight >= my-Group-threshold] ;; For starting centroids we take into account only not loosely connected agents, but later we set groups for all.
; let communities nw:louvain-communities ;; Louvain detection of communitites
; foreach communities [c -> if member? self c [set Identity-group c]] ;; Looking for 'self' in communities -- community which includes '(my)self' is set as Identity group.
; if count Identity-group < 3 [set Identity-group agents] ;; CHECK: If Identity group is (almost) empty, then set all agents as Identity group
; ]
;end
; Setting identity groups individually via threshold levels to account for differences in sensitivity to group relationships
to set-individual-group-identities
foreach range identity_levels[ i ->
let idthresh item i id_threshold_set
;; Cleaning environment
ask centroids [die]
;; Detection of clusters via Louvain: Detection itself
let selected-agents agents with [2 < count my-l-distances with [l-weight >= idthresh]] ;; Note: We take into account only not loosely connected agents
nw:set-context selected-agents l-distances with [l-weight >= idthresh] ;; For starting centroids we take into account only not loosely connected agents, but later we set groups for all.
let communities nw:louvain-communities
;repeat N-agents [set communities nw:louvain-communities]
set N_centroids length communities
;; Computing clusters' mean 'opinion-position'
set positions_clusters [] ;; List with all positions of all clusters
foreach communities [c ->
let one [] ;; List for one position of one cluster
foreach range opinions [o -> set one lput precision (mean [item o opinion-position] of c) 3 one]
set positions_clusters lput one positions_clusters
]
;; Preparation of centroids -- feedeing them with communities
create-centroids N_centroids [
set heading (who - min [who] of centroids)
set Opinion-position item heading positions_clusters ;; We set opinions, we try to do it smoothly...
set shape "circle"
set size 1.5
set color 5 + (who - min [who] of centroids) * 10
getPlace
]
;; Assignment of agents to groups
ask agents [set group [who] of min-one-of centroids [opinion-distance]] ;; Sic! Here we intentionally use all agents, including loosely connected.
;; Computation of centroids possitions
compute-centroids-positions (agents)
;; Iterating cycle -- looking for good match of centroids
while [sum [opinion-distance3 (Last-opinion) (Opinion-position)] of centroids > Centroids_change] [
;; turtles compute whether they are in right cluster and
ask agents [set group [who] of min-one-of centroids [opinion-distance]]
;; Computation of centroids possitions
compute-centroids-positions (agents)
]
;; Saving Identity group as agent-set
ask agents with [id-threshold-level = i] [
set Identity-group agents with [group = [group] of myself]
if count Identity-group < 3 [set Identity-group agents]
]
;; Killing centroids without connected agents
ask centroids [
let wom who
if (not any? agents with [group = wom]) [die]
]
set N_centroids count centroids
;; Final coloring and killing of centroids
if centroid_color? [ask agents [set color (5 + 10 * (group - min [who] of centroids))]]
if killing_centroids? [ask centroids [die]]
]
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;; G O ! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Main routine
to go
;;;; Preparation part ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Redundant conditions which should be avoided -- if the boundary is drawn as constant, then is completely same whether agents vaguely speak or openly listen,
;; seme case is for probability speaking of 100%, then it's same whether individual probability is drawn as constant or uniform, result is still same: all agents has probability 100%.
if avoid-redundancies? and mode = "vaguely-speak" and boundary-drawn = "constant" [stop]
if avoid-redundancies? and p-speaking-level = 1 and p-speaking-drawn = "uniform" [stop]
;; All preparations of agents, globals, avoiding errors etc. in one sub-routine
prepare-everything-for-the-step
;;;; Main part ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
ask agents [
;; Firstly, we have to determine satisfaction with the neighborhood via 'get-satisfaction' sub-routine
set Satisfied? get-satisfaction
;; NOTE: Updating of 'Satisfied?' in sub-routine 'prepare-everything-for-the-step' leads to run-time errors.
;; Mechanism of own opinion or network change -- decision and rossolution
;; In case of dissatisfaction agents changes network
if not satisfied? [change-of-network]
;; Now it's implemented, that agents update opinion with probability regulated by
;; slider 'dissatisfied_updates_opinion' or value of variable 'Opponents-ratio'
;; in cases they are still not satisfied with their network neighborhood
;; TO-DO: Discuss this with the team!
let value ifelse-value (use_opponents_ratio?) [1 - Opponents-ratio][dissatisfied_updates_opinion]
if Satisfied? or value > random-float 1 [
;if not satisfied? [show "I'm not satisfied!!!" show ticks]
if model = "HK" [change-opinion-HK]
;; Note: Now here is only Hegselmann-Krause algorithm, but in the future we might easily employ other algorithms here!
;if not satisfied? [show Opponents-ratio show value]
]
]
;; The main algorithm might produce lonely agents, now we connect them to one/more other speaking agent/s
connect-loners
;;;; Final part ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Recoloring patches, agents, computing how model settled down
updating-patches-and-globals
tick
;; Finishing condition:
;; 1) We reached state, where no turtle changes for RECORD-LENGTH steps, i.e. average of MAIN-RECORD (list of averages of turtles/agents RECORD) is 1 or
;; 2) We reached number of steps specified in MAX-TICKS
recording-situation-and-computing-polarisation
if (mean main-Record = 1 and network-changes <= 5) or ticks = max-ticks [stop]
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;; SUB/PROCEDURES ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
to prepare-everything-for-the-step
;; Just checking and avoiding runtime errors part of code
avoiding-run-time-errors
;; Before a round erasing indicator of change
set network-changes 0
;; Update group identities via Louvain
ifelse use_identity? [
update-l-distances-weights
if identity_type = "global" [set-group-identities]
if identity_type = "individual" [set-individual-group-identities] ; and (ticks mod identity_update = 0)
][
ask agents [set Identity-group agents]
]
;; speaking, coloring, updating and SATISFACTION!!!
ask agents [preparing-myself]
end
to preparing-myself
;; Updating speaking, color and place
set speak? speaking
getColor
getPlace
;; storing previous opinion position as 'Last-opinion'
set Last-opinion Opinion-position
end
;; for computing thresholds and assigning levels to each agent as per drawing parameters
to compute-identity-thresholds
;; computing values
set id_threshold_set n-values identity_levels [0]
foreach range identity_levels [ i -> set id_threshold_set replace-item i id_threshold_set precision (i / (identity_levels)) 3]
;set id_threshold_set replace-item (identity_levels - 1) id_threshold_set 0.999 ;; since 1 throws an error
;; now implementing distribution possibilities
;;
;; splitting into a major and minor group as 80%-20%. The 80% takes on either the highest (right skew) or lowest values of threshold.
let eighty_percent_size int N-agents * 0.8
let major_partition n-of eighty_percent_size agents
let minor_partition agents with [ not member? self major_partition]
ifelse (draw_id_threshold = "uniform")[
ask agents [ set id-threshold-level random identity_levels ]
][
ifelse (identity_levels > 3)[
;; if identity levels > 3, only the highest two or lowest two levels will contain 80% of the population
ask major_partition [
let dice random 2
set id-threshold-level dice
if(draw_id_threshold = "right-skewed") [ set id-threshold-level (id-threshold-level + identity_levels - 2) ]
]
ask minor_partition [
let dice random (identity_levels - 2)
set id-threshold-level dice
if(draw_id_threshold = "left-skewed") [ set id-threshold-level (id-threshold-level + 2) ]
]
][
;; if identity levels < 4, only use one level for major partition
ask major_partition [
if(draw_id_threshold = "right-skewed") [ set id-threshold-level identity_levels ]
if(draw_id_threshold = "left-skewed") [ set id-threshold-level 0 ]
]
ask minor_partition [
let dice random (identity_levels - 1)
set id-threshold-level dice
if(draw_id_threshold = "left-skewed") [ set id-threshold-level (id-threshold-level + 1) ]
]
]
]
end
;; sub-routine computing whether the agent is satisfied with the neighborhood
to-report get-satisfaction
;; initialization of agent set 'opponents' containing agents whose opinion positions are key for agent's satisfaction
let opponents nobody
;; 1) updating agent uses only visible link neighbors in small-world network
let visibles comm-neighbors with [speak?]
;; TO-DO: Discuss with Mike, Ashwin and Ashley what scope in Identity group and what in comm-neis.
;; Now I use the IG only for updating opinion in HK, not used in rewiring of comm network, not for satisfaction etc.
;; 2) we have different modes for finding supporters:
;; 2.1) in mode "I got them!" agent looks outside her boundary (opinion +/- uncertainty),
;; i.e. agent takes as opponents agents that are too far from her opinion
if mode = "openly-listen" [
;; we compute 'lim-dist' -- it is the numerical distance in given opinion space
let lim-dist (Uncertainty * sqrt(opinions * 4))
;; we set as opponents agents with opinion further than 'lim-dist'
set opponents visibles with [opinion-distance > lim-dist]
]
;; 2.1) in mode "They got me!" agent looks outside whose boundaries (opinion +/- uncertainty) she is,
;; i.e. she takes as opponents agents that speak with such a low uncertainty that it doesn't match her own opinion
if mode = "vaguely-speak" [
;; Note: Here is used the 'Uncetainty' value of called agent, agent who might be used for updating,
;; not 'Uncertainty' of calling agent who updates her own opinion.
set opponents visibles with [opinion-distance > (Uncertainty * sqrt(opinions * 4))]
]
;; Now we can return the True/False value, whether the agent is satisfied
;; (among visible network neighbors from identity group are not too much opponents)
set Opponents-ratio ifelse-value (count visibles > 0) [precision (count opponents / count visibles) 3][0] ;; In case no visibles are in the neighborhood, no opponent is there.
report ifelse-value (count visibles > 0) [Opponents-ratio <= Tolerance][TRUE] ;; In case no visibles are in the neighborhood, then agent is happy.
end
;; envelope controlling the way, how we change the network
to change-of-network
if network-change = "link" [rewire-one-link]
if network-change = "community" [leave-the-neighborhood-join-a-new-one]
;; Note: here might be other ways in the future, that's why the 'ifelse' structure is not used here
;; We advance the counter of network changes -- now, one just happened.
set network-changes network-changes + 1
;; We check if the changing of network helps
set Satisfied? get-satisfaction
end
;; subroutine for leaving the neighborhood and joining a new one -- agent is decided to leave, we just process it here
to leave-the-neighborhood-join-a-new-one
;; Firstly, we have to count agents neighbors, to determine how many links agent has to create in the main part of the procedure
let to-visibles my-comms with [[speak?] of other-end]
let nei-size count to-visibles
;; Secondly, we cut off all the links
ask to-visibles [die]
;; Catching possible error with not enough visible agents for creating 'comms'
let speaking-others other agents with [speak?]
if (nei-size > count speaking-others) [set nei-size count speaking-others]
;; Thirdly, random VS intentional construction of new neighborhood.
ifelse create-links-randomly? [
;; We set new neighborhood randomly or...
create-comms-with n-of nei-size speaking-others
][
;; ...creates it out of the closest neighbors.
create-comms-with min-n-of nei-size speaking-others [opinion-distance]
]
;; P.S. Just hiding links for better speed of code -- when we change/cut a link, all links become visible and that slows down the simulation.
ask comms [set hidden? TRUE]
end
;; TO-DO: agents should cut-off only neighbors that they previously heard speak,
;; we probably should create their memory whom they heard speak and onlythose agents might cut-off.
;;
;; Note: Now I implement it in modest variant: agent cuts off the most annoying/random presently speaking agent --
;; there must be at least one, since agents are satisfied by the rule with the empty neighborhood and
;; they update neighborhood only in case of dissatisfaction.
;; subroutine for changing one link
to rewire-one-link
;; Firstly, we find speaking agents who are both: in Identity group and connected by communication link.
let visibles comm-neighbors with [speak?]
;; Cutting-off of the link itself:
let a-visible one-of visibles
let annoyer max-one-of visibles [opinion-distance]
ask one-of my-comms with [other-end = ifelse-value (cut-links-randomly?) [a-visible][annoyer]] [die]
;; Secondly, we choose for the agent a new speaking partner with the random/most-close opinion
;let cha count my-comms
let potentials other agents with [speak? and not comm-neighbor? myself]
;if 128 != (count potentials + cha) [show "!!!!!!!!!!!!!!!!!!!MISTAKE!!!!!!!!!!!!!!!!!!!! wrong potentials/my-comms" show ticks]
;if count potentials = 0 [show "!!!!!!!!!!!!!!!!!!!MISTAKE!!!!!!!!!!!!!!!!!!!! zero potentials" show ticks]
let a-partner one-of potentials
let the-partner min-one-of potentials [opinion-distance]
create-comm-with ifelse-value (create-links-randomly?) [a-partner] [the-partner]
;if not (count my-comms > cha) [show "!!!!!!!!!!!!!!!!!!!MISTAKE!!!!!!!!!!!!!!!!!!!! no link created!" show ticks]
;; P.S. Just hiding links for better speed of code -- when we change/cut a link, all links become visible and that slows down the simulation.
ask comms [set hidden? TRUE]
end
;; Procedure for connecting agents with not enough comm-neigbours
to connect-loners
;; We check whether each agent has enough neighbors
ask agents with [count comm-neighbors < min-comm-neis] [
;; !!!WARNING!!!: If there are many agents classified as 'loners',
;; then early running agents might connect some later going agents,
;; and then might happen that when later running agent runs this algorithm,
;; she has enough connections (because she was connected by earlier running agents).
;; SOLUTION: Check before creating new link whetwer agent is still demanding these new links.
;; Defining needed agentset and variables:
let potentials other agents with [speak?] ; We set 'potentials' to all other speaking agents and then...
let p count potentials ; 'p' stands for potentials
;; Catch of potential BUG via 'if' structure --
;; a) if there is no-one speaking, then the lone agent has to wait until the next round.
;; b) if agent was demanding new links, but was served by previous demanders, then needs no new link
if p > 0 and count comm-neighbors < min-comm-neis [
let n min-comm-neis - count comm-neighbors ; 'n' stands for needed
let ap ifelse-value(p >= n)[n][p] ; 'ap' stands for asked potentials
create-comms-with ifelse-value (create-links-randomly?) [n-of ap potentials][min-n-of ap potentials [opinion-distance]] ;... it depends on scenario: we choose randomly or with the closest opinion
]
]
;; P.S. Just hiding links for better speed of code -- when we change/cut a link, all links become visible and that slows down the simulation.
ask comms [set hidden? TRUE]
end
;; sub-routine for updating opinion position of turtle according the Hegselmann-Krause (2002) model
to change-opinion-HK
;; initialization of agent set 'influentials' containing agents whose opinion positions uses updating agent
let influentials no-turtles
;; 1) updating agent uses only visible link neighbors in small-world network who are also members of her Identity group
let visibles (turtle-set filter [vis -> member? vis Identity-Group] sort comm-neighbors with [speak?])
;; 2) we have different modes for finding influentials:
;; 2.1) in mode "openly-listen" agent looks inside his boundary (opinion +/- uncertainty),
;; i.e. agent takes opinions not that much far from her opinion
if mode = "openly-listen" [
;; we compute 'lim-dist' -- it is the numerical distance in given opinion space
let lim-dist (Uncertainty * sqrt(opinions * 4))
;; we set as influentials agents with opinion not further than 'lim-dist'
set influentials visibles with [opinion-distance <= lim-dist]
]
;; 2.1) in mode "vaguely-speak" agent looks inside whose boundaries (opinion +/- uncertainty)
;; she is, i.e. agents takes opinions spoken with such a big uncertainty that it matches her own opinion
if mode = "vaguely-speak" [
;; Note: Here is used the 'Uncetainty' value of called agent, agent who might be used for updating,
;; not 'Uncertainty' of calling agent who updates her opinion.
set influentials visibles with [opinion-distance <= (Uncertainty * sqrt(opinions * 4))]
]
;; 3) we also add the updating agent into 'influentials'
set influentials (turtle-set self influentials)
;; we check whether there is someone else then calling/updating agent in the agent set 'influentials'
if count influentials > 1 [
;; here we draw a list of dimensions which we will update:
;; by 'range opinions' we generate list of integers from '0' to 'opinions - 1',
;; by 'n-of updating' we randomly take 'updating' number of integers from this list
;; by 'shuffle' we randomize order of the resulting list
let op-list shuffle n-of updating range opinions
;; we initialize counter 'step'
let step 0
;; we go through the while-loop 'updating' times:
while [step < updating] [
;; we initialize/set index of updated opinion dimension according the items on the 'op-list',
;; note: since we use while-loop, we go through each item of the 'op-list', step by step, iteration by iteration.
let i (item step op-list)
;; then we update dimension of index 'i' drawn from the 'op-list' in the previous line:
;; 1) we compute average position in given dimension of the calling/updating agent and all other agents from agent set 'influentials'
;; by the command '(mean [item i opinion-position] of influentials)', and
;; 2) the new value of opinion 'val' is not directly average, but it is weighted by the 'Conformity' (individual trait),
;; the closer 'Conformity' to 1, the closer agent jumps into the mean of others, the closer to 0, the less agent moves.
;; 3) we set value as new opinion position by command 'set opinion-position replace-item i opinion-position X' where 'X' is the mean opinion (ad 1, see line above)
;; ad 1: averge position computation
let val precision (mean [item i opinion-position] of influentials) 3 ;; NOTE: H-K model really assumes that agent adopts immediatelly the 'consesual' position
;; ad 2: updating/weighting 'val' by 'Conformity' and own opinion
let my item i opinion-position
set val my + ((val - my) * Conformity)
;; ad 3: assigning the value 'val'
set opinion-position replace-item i opinion-position val
;; advancement of counter 'step'
set step step + 1
]
]
end
;; sub-routine for computing opinion distance of two comparing agents
to-report opinion-distance
;; we store in temporary variable the opinion of the called and compared agent
let my opinion-position
;; we store in temporary variable the opinion of the calling and comparing agent
let her [opinion-position] of myself
;; we initialize counter of step of comparison -- we will compare as many times as we have dimensions
let step 0
;; we initialize container where we will store squared distance in each dimension
let dist 0
;; while loop going through each dimension, computiong distance in each dimension, squarring it and adding in the container
while [step < opinions] [
;; computiong distance in each dimension, squarring it and adding in the container
set dist dist + (item step my - item step her) ^ 2
;; advancing 'step' counter by 1
set step step + 1
]
;; computing square-root of the container 'dist' -- computing Euclidean distance -- and setting it as 'dist'
set dist sqrt dist
;; reporting Euclidean distance
report dist
end
;; sub-routine for computing opinion distance of two comparing opinion positions -- relative distance weighted as 1 for minimal distance and 0 for the maximal one
to-report opinion-distance2 [my her]
;; we initialize counter of step of comparison -- we will compare as many times as we have dimensions
let step 0
;; we initialize container where we will store squared distance in each dimension
let dist 0
;; while loop going through each dimension, computiong distance in each dimension, squarring it and adding in the container
while [step < opinions] [
;; computiong distance in each dimension, squarring it and adding in the container
set dist dist + (item step my - item step her) ^ 2
;; advancing 'step' counter by 1
set step step + 1
]
;; computing square-root of the container 'dist' -- computing Euclidean distance -- and setting it as 'dist'
set dist sqrt dist
;; Turning 'dist' into 'weight'
let weight (sqrt(4 * opinions) - dist) / sqrt(4 * opinions)
;; reporting weight of distance
report precision weight 10
end
;; sub-routine for computing opinion distance of two comparing opinion positions -- absolute distance without weighting
to-report opinion-distance3 [my her]
;; we initialize counter of step of comparison -- we will compare as many times as we have dimensions
let step 0
;; we initialize container where we will store squared distance in each dimension
let dist 0
;; while loop going through each dimension, computiong distance in each dimension, squarring it and adding in the container
while [step < opinions] [
;; computiong distance in each dimension, squarring it and adding in the container
set dist dist + (item step my - item step her) ^ 2
;; advancing 'step' counter by 1
set step step + 1
]
;; computing square-root of the container 'dist' -- computing Euclidean distance -- and setting it as 'dist'
set dist sqrt dist
;; reporting weight of distance
report precision dist 10
end
to recording-situation-and-computing-polarisation
;; Finishing condition:
;; 1) We reached state, where no turtle changes for RECORD-LENGTH steps, i.e. average of MAIN-RECORD (list of averages of turtles/agents RECORD) is 1 or
;; 2) We reached number of steps specified in MAX-TICKS
if ((mean main-Record = 1 and network-changes <= 5) or ticks = max-ticks) [compute-polarisation-repeatedly]
if ((mean main-Record = 1 and network-changes <= 5) or ticks = max-ticks) and record? [record-state-of-simulation]
;; Recording and computing polarisation on the fly...
if (ticks / polarisation-each-n-steps) = floor (ticks / polarisation-each-n-steps) [compute-polarisation-repeatedly]
if (ticks / record-each-n-steps) = floor(ticks / record-each-n-steps) and record? [record-state-of-simulation]
end
;; Updating patches and global variables
to updating-patches-and-globals
;; Patches update color according the number of turtles on it.
ask patches [set pcolor patch-color]
;; We have to check here the change of opinions, resp. how many agents changed,
;; and record it for each agent and also for the whole simulation
;; Turtles update their record of changes:
ask agents [
;; we take 1 if opinion is same, we take 0 if opinion changes, then
;; we put 1/0 on the start of the list Record, but we omit the last item from Record
set Record fput ifelse-value (Last-opinion = Opinion-position) [1][0] but-last Record
]
;; Then we might update it for the whole:
set main-Record fput precision (mean [mean Record] of agents) 3 but-last main-Record
;; Coloring agents according identity group
if centroid_color? [ask agents [set color (5 + 10 * (group - min [group] of agents))]]
end
;; Procedure reporting ESBG/Ashwin's polarisation
to-report Ash-polarisation
;; Preparation
create-centroids 2 [set shape "square" set Opinion-position n-values opinions [precision (1 - random-float 2) 8]]
let cent1 max [who] of centroids ;; Storing 'who' of two new centroids
let cent0 cent1 - 1
ask agents [set group (cent0 + (who mod 2))] ;; Random assignment of agents to the groups
updating-centroids-opinion-position (cent0) (cent1) ;; Initial update
;; Iterating until centroids are stable
while [Centroids_change < sum [opinion-distance3 Opinion-position Last-opinion] of centroids with [who >= cent0]][
update-agents-opinion-group (cent0) (cent1)
updating-centroids-opinion-position (cent0) (cent1)
]
;; Computing polarisation -- cutting-out agents too distant from centroids
ask agents [set distance_to_centroid [opinion-distance] of centroid group]
let a0 agents with [group = cent0]
set a0 min-n-of (count a0 - ESBG_furthest_out) a0 [opinion-distance3 ([opinion-position] of self) ([opinion-position] of centroid cent0)]
let a1 agents with [group = cent1]
set a1 min-n-of (count a1 - ESBG_furthest_out) a1 [opinion-distance3 ([opinion-position] of self) ([opinion-position] of centroid cent1)]
;; Updating centroids and agents opinion position (without furthest agents)
ask centroid cent0 [foreach range opinions [o -> set opinion-position replace-item o opinion-position precision (mean [item o opinion-position] of a0) 8] getPlace]
ask a0 [set distance_to_centroid [opinion-distance] of centroid cent0]
ask centroid cent1 [foreach range opinions [o -> set opinion-position replace-item o opinion-position precision (mean [item o opinion-position] of a1) 8] getPlace]
ask a1 [set distance_to_centroid [opinion-distance] of centroid cent1]
;; Preparing final distances and diversity
let cent-dist opinion-distance3 ([opinion-position] of centroid cent0) ([opinion-position] of centroid cent1)
let div0 (mean [distance_to_centroid] of a0)
let div1 (mean [distance_to_centroid] of a1)
;; Cleaning and reporting
ask centroids with [who >= cent0] [die]
report (cent-dist / (1 + div0 + div1)) / sqrt(opinions * 4)
end
to update-agents-opinion-group [cent0 cent1]
;; Checking the assignment -- is the assigned centroid the nearest? If not, reassign!
ask agents [set group group - ([who] of min-one-of centroids with [who >= cent0] [opinion-distance])] ; set color 15 + group * 10]
let wrongly-at-grp0 turtle-set agents with [group = -1] ;; they are in 0, but should be in 1: 0 - 1 = -1
let wrongly-at-grp1 turtle-set agents with [group = 1] ;; they are in 1, but should be in 0: 1 - 0 = 1
ifelse count wrongly-at-grp0 = count wrongly-at-grp1 [
ask agents [set group [who] of min-one-of centroids with [who >= cent0] [opinion-distance]]
][
let peleton agents with [group = 0]
ifelse count wrongly-at-grp0 < count wrongly-at-grp1 [
set peleton (turtle-set peleton wrongly-at-grp0 max-n-of (count wrongly-at-grp0) wrongly-at-grp1 [opinion-distance3 ([opinion-position] of self) ([opinion-position] of centroid cent0)]) ;; all agents assigned correctly + smaller group of wrong + from bigger group 'n of size of smaller group'
let stayed agents with [not member? self peleton]
ask peleton [set group [who] of min-one-of centroids with [who >= cent0] [opinion-distance] ;set color 15 + group * 10
]
ask stayed [set group cent1 ;set color 15 + group * 10
]
][
set peleton (turtle-set peleton wrongly-at-grp1 max-n-of (count wrongly-at-grp1) wrongly-at-grp0 [opinion-distance3 ([opinion-position] of self) ([opinion-position] of centroid cent1)]) ;; all agents assigned correctly + smaller group of wrong + from bigger group 'n of size of smaller group'
let stayed agents with [not member? self peleton]
ask peleton [set group [who] of min-one-of centroids with [who >= cent0] [opinion-distance] ;set color 15 + group * 10
]
ask stayed [set group cent0 ;set color 15 + group * 10
]
]
]
end
to updating-centroids-opinion-position [cent0 cent1]
;; Storing opinion as Last-opinion
ask centroids with [who >= cent0] [set Last-opinion Opinion-position]
;; Computing groups mean 'opinion-position'
set positions_clusters [] ;; List with all positions of both 2 groups
foreach range 2 [c ->
let one-position [] ;; List for one position of one cluster
foreach range opinions [o -> set one-position lput precision (mean [item o opinion-position] of agents with [group = cent0 + c]) 8 one-position]
set positions_clusters lput one-position positions_clusters
]
;; Setting opinions of centroids
ask centroid cent0 [set opinion-position item 0 positions_clusters getPlace]
ask centroid cent1 [set opinion-position item 1 positions_clusters getPlace]
end
;; Envelope for combined update of weights of all links
to update-links-weights
update-comms-weights
update-l-distances-weights
end
;; Sub-routine for updating Communication links' weights,
;; according opinion distance of both their ends
to update-comms-weights
;; We use function 'opinion-distance2', which needs two opinion positions as input and
;; receives their distance as output, but this distance is converted to weight:
;; weight = 1 means that both positions are same, weight = 0 means that their distance is maximal,
;; i.e. both positions are in oposit corners of respective N-dimensional space.
ask comms [set op-weight opinion-distance2 ([opinion-position] of end1) ([opinion-position] of end2)]
ask comms [set hidden? TRUE]
end
;; Sub-routine for updating Distances links' weights,
;; according opinion distance of both their ends
to update-l-distances-weights
;; We use function 'opinion-distance2', which needs two opinion positions as input and
;; receives their distance as output, but this distance is converted to weight:
;; weight = 1 means that both positions are same, weight = 0 means that their distance is maximal,
;; i.e. both positions are in oposit corners of respective N-dimensional space.
ask l-distances [set l-weight opinion-distance2 ([opinion-position] of end1) ([opinion-position] of end2)]
ask l-distances [set hidden? TRUE]
end
;; We compute polarisation several times and then set it for the average
to compute-polarisation-repeatedly
;; Initialization of temporal variables
let r 0
let p []
let np []
let up []
let unp []
let ap []
update-links-weights
;; Repeating cycle
while [r < polar_repeats] [
compute-polarisation
set p lput polarisation p
set np lput normalized_polarisation np
set up lput unweighted_polarisation up
set unp lput unweighted_normalized_polarisation unp
set ap lput Ash-polarisation ap
set r r + 1
]
;; Setting variables back
set polarisation precision (mean p) 3
set normalized_polarisation precision (mean np) 3
set unweighted_polarisation precision (mean up) 3
set unweighted_normalized_polarisation precision (mean unp) 3
set ESBG_polarisation precision (mean ap) 3
end
;; NOTE: Now I am iplementing it for N = 2 centroids, but I prepare code for easy generalisation for N > 2.
to compute-polarisation
;; Preparation
ask centroids [die]
;; Detection of clusters via Louvain
let selected-agents agents with [2 < count my-l-distances with [l-weight >= d_threshold]] ;; Note: We take into account only not loosely connected agents
nw:set-context selected-agents l-distances with [l-weight >= d_threshold]
let communities nw:louvain-communities
set N_centroids length communities
;; Computing clusters' mean 'opinion-position'
let positions-clusters [] ;; List with all positions of all clusters
foreach communities [c ->
let one [] ;; List for one positio nof one cluster
foreach range opinions [o -> set one lput precision (mean [item o opinion-position] of c) 8 one]
set positions-clusters lput one positions-clusters
]
;; Preparation of centroids -- feedeing them with communities
create-centroids N_centroids [
set heading (who - min [who] of centroids)
set Opinion-position item heading positions-clusters ;; We set opinions, we try to do it smoothly...
set shape "circle"
set size 1.5
set color 5 + (who - min [who] of centroids) * 10
getPlace
]
;; Assignment of agents to groups
ask selected-agents [set group [who] of min-one-of centroids [opinion-distance]]
;; Computation of centroids possitions
compute-centroids-positions (selected-agents)
;; Iterating cycle -- looking for good match of centroids
while [sum [opinion-distance3 (Last-opinion) (Opinion-position)] of centroids > Centroids_change] [
;; turtles compute whether they are in right cluster and
ask selected-agents [set group [who] of min-one-of centroids [opinion-distance]]
;; Computation of centroids possitions