-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgroupFormation_pipeline.nlogo
2816 lines (2521 loc) · 79.4 KB
/
groupFormation_pipeline.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.
;;
;; !!!FROZEN FOR PIPELINE!!!
;;
;; Created: 2021-10-21 FranCesko
;; Edited: 2022-02-04 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 Pol-bias Initial-opinion Tolerance Conformity Satisfied? group distance_to_centroid]
l-distances-own [l-weight]
globals [main-Record components positions network-changes agents polarisation normalized_polarisation unweighted_polarisation unweighted_normalized_polarisation]
;; 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.
;(avoid-redundancies? and mode = "vaguely-speak" and boundary-drawn = "constant") or (avoid-redundancies? and p-speaking-level = 1 and p-speaking-drawn = "uniform")
;; 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.
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!
;; 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 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
;; 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 []
;; 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 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
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]
;let original_centroids_value N_centroids
;; Detection of clusters via Louvain
ask l-distances [die] ;; Cleaning environment
ask agents [create-l-distances-with other agents with [(sqrt(4 * opinions) - opinion-distance) / sqrt(4 * opinions) >= id_threshold] [set l-weight opinion-distance2 ([opinion-position] of end1)([opinion-position] of end2)]]
;show count l-distances
;ask l-distances with [l-weight < d_threshold] [die]
nw:set-context agents l-distances ;with [l-weight >= d_threshold]
let communities nw:louvain-communities
;show count l-distances
ask l-distances [die]
set N_centroids length communities
;; Computing clusters' mean 'opinion-position'
let postions-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) 3 one
]
;show one
set postions-clusters lput one postions-clusters
;show postions-clusters
]
;; Preparation of centroids -- feedeing them with communities
create-centroids N_centroids [
set heading (who - min [who] of centroids)
set Opinion-position item heading postions-clusters ;; We set opinions, we try to do it smoothly...
;show Opinion-position
set shape "circle"
set size 1.5
set color 5 + who * 10
getPlace
]
;; Assignment of agents to groups
;let min_group min [who] of centroids
ask agents [set group [who] of min-one-of centroids [opinion-distance]]
;; Computation of centroids possitions
compute-centroids-positions
;let iter 0
;; Iterating cycle -- looking for good match of centroids
while [sum [opinion-distance3 (Last-opinion) (Opinion-position)] of centroids > Centroids_change] [
;set iter iter + 1
;show (word "Iteration: " iter)
;; 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
]
;; Killing centroids without connected agents
ask centroids [
let wom who
if (not any? agents with [group = wom]) [
set N_centroids N_centroids - 1
die
]
]
;show count centroids
;; Catching the run-time error:
;; If there is just one component since all agents has same opinion, then the polarisation algorithm does produce error --
;; because of computing mean of empty list of distences: this list is empty since the only one existing centroid can't
;; compute distance to itself via double 'while' structuresince 'ai' and 'aj' lists are empty.
;; In this case it is obvious that polarisation is 0, so we set 'polarisation' and 'normalized_polarisation' to 0 directly via 'ifelse' structure
ifelse (count centroids < 2) [
;show "Manual setting of polarisation globals to 0!"
set polarisation 0
set normalized_polarisation 0
set unweighted_polarisation 0
set unweighted_normalized_polarisation 0
][
;; Computing polarization -- preparation of lists and agents
let distances []
let diversity []
let unweighted_distances []
let unweighted_diversity []
let whos sort [who] of centroids ;; List of 'who' of all centroids
;show whos
ask agents [set distance_to_centroid [opinion-distance] of centroid group] ;; Each agent computes her distance to her centroid and stores it as 'distance_to_centroid'.
;; Computing polarization -- distances of all centroids
let ai but-last whos ;; List of all 'i' -- 'who' initializing distances computation
let aj but-first whos ;; List of all 'j' -- 'who' of other end of distances computation
foreach ai [i ->
foreach aj [j ->
;show (word i "; " j)
;; Each distance is weighted by fraction of both centroid groups
;; via formula '(N_centroids ^ 2) * (count agents with [group = i] / count agents) * (count agents with [group = j] / count agents)'
let weight (N_centroids ^ 2) * (count agents with [group = i] / count agents) * (count agents with [group = j] / count agents)
let cent-dist opinion-distance3 ([opinion-position] of centroid i) ([opinion-position] of centroid j)
set distances lput (weight * cent-dist) distances
set unweighted_distances lput cent-dist unweighted_distances
]
set aj but-first aj
]
;; Computing polarization -- diversity in groups
foreach sort [who] of centroids [wg ->
let weight (count agents with [group = wg] / count agents)
let cent-div (mean [distance_to_centroid] of agents with [group = wg])
set diversity lput (weight * cent-div) diversity
set unweighted_diversity lput cent-div unweighted_diversity
]
;; Computing polarization -- polarization indexes
;; Note: Now it is computed to receive same result as for n=2 groups,
;; but might be needed to change it later to get better results for n>2 group,
;; but now it works fine without runtime errors with all numbers of groups.
set polarisation (mean distances) / (1 + 2 * mean diversity) ;; Raw polarization computed as distance divided by heterogeinity in the groups.
set normalized_polarisation precision (polarisation / (2 * sqrt(opinions))) 3
set polarisation precision polarisation 3
set unweighted_polarisation (mean unweighted_distances) / (1 + 2 * mean unweighted_diversity) ;; Raw unweighted polarization computed as unweighted distance divided by unweighted heterogeinity in the groups.
set unweighted_normalized_polarisation precision (unweighted_polarisation / (2 * sqrt(opinions))) 3
set unweighted_polarisation precision unweighted_polarisation 3
;show diversity
;show distances
;show (word polarisation "; " normalized_polarisation "; " unweighted_polarisation "; " unweighted_normalized_polarisation)
]
;; Final coloring and killing of centroids
if centroid_color? [ask agents [set color [color] of centroid group]]
if killing_centroids? [ask centroids [die]]
;set N_centroids original_centroids_value
end
;; Sub-routine of polarization routine
to compute-centroids-positions
;; Preparation
ask centroids [set Last-opinion Opinion-position]
;; Computation of centroids possitions
let grp min [who] of centroids
while [grp <= (max [who] of centroids)] [
ask centroid grp [
ifelse (not any? agents with [group = grp]) [
set Opinion-position Last-opinion
][
let dim 0
while [dim < opinions] [
set Opinion-position replace-item dim Opinion-position mean [item dim Opinion-position] of agents with [group = grp]
set dim dim + 1
]
]
]
set grp grp + 1
]
ask centroids [
getPlace
;show opinion-distance3 (Last-opinion) (Opinion-position)
]
end
;; reporter function for translating a list into one string of values divided by commas
to-report list-to-string [LtS]
;; Initializing empty string and counter
let str ""
let i 0
;; Now we go through the list item by item and add them into string
while [i < length LtS][
set str (word str item i LtS)
set i i + 1
if (i < length LtS) [set str (word str ", ")]
]
report str
end
;; Sub-routine for assigning value of tolerance
to-report get-conformity
;; We have to initialize empty temporary variable
let cValue 0
;; Then we draw the value according the chosen method
if conformity-drawn = "constant" [set cValue conformity-level + random-float 0] ;; NOTE! 'random-float 0' is here for consuming one pseudorandom number to cunsume same number of pseudorandom numbers as "uniform
if conformity-drawn = "uniform" [set cValue ifelse-value (conformity-level < 0.5)
[precision (random-float (2 * conformity-level)) 3]
[precision (1 - (random-float (2 * (1 - conformity-level)))) 3]]
report cValue
end
;; Sub-routine for assigning value of tolerance
to-report get-tolerance
;; We have to initialize empty temporary variable
let tValue 0
;; Then we draw the value according the chosen method
if tolerance-drawn = "constant" [set tValue tolerance-level + random-float 0] ;; NOTE! 'random-float 0' is here for consuming one pseudorandom number to cunsume same number of pseudorandom numbers as "uniform
if tolerance-drawn = "uniform" [set tValue ifelse-value (tolerance-level < 0.5)
[precision (random-float (2 * tolerance-level)) 3]
[precision (1 - (random-float (2 * (1 - tolerance-level)))) 3]]
report tValue
end
;; Sub-routine for assigning value of p-speaking
to-report get-speaking
;; We have to initialize empty temporary variable
let pValue 0
;; Then we draw the value according the chosen method
if p-speaking-drawn = "constant" [set pValue p-speaking-level + random-float 0] ;; NOTE! 'random-float 0' is here for consuming one pseudorandom number to cunsume same number of pseudorandom numbers as "uniform
if p-speaking-drawn = "uniform" [set pValue ifelse-value (p-speaking-level < 0.5)
[precision (random-float (2 * p-speaking-level)) 3]
[precision (1 - (random-float (2 * (1 - p-speaking-level)))) 3]]
if p-speaking-drawn = "function" [set pValue (precision(sqrt (sum (map [ x -> x * x ] opinion-position)) / sqrt opinions) 3) + random-float 0] ;; NOTE! 'random-float 0' is here for consuming one pseudorandom number to cunsume same number of pseudorandom numbers as "uniform
;; Report result back
report pValue
end
;; sub-routine for assigning value of uncertainty to the agent
to-report get-uncertainty
;; We have to initialize empty temporary variable
let uValue 0
;; Then we draw the value according the chosen method
if boundary-drawn = "constant" [set uValue boundary + random-float 0] ;; NOTE! 'random-float 0' is here for consuming one pseudorandom number to cunsume same number of pseudorandom numbers as "uniform"
if boundary-drawn = "uniform" [set uValue precision (random-float (2 * boundary)) 3]
;; reporting value back for assigning
report uValue
end
;; sub-routine for graphical representation -- it takes two opinion dimension and gives the agent on XY coordinates accordingly
to getPlace
;; check whether our cosen dimension is not bigger than maximum of dimensions in the simulation
if X-opinion > opinions [set X-opinion 1]
if Y-opinion > opinions [set Y-opinion 1]
;; then we rotate the agent towards the future place
facexy ((item (X-opinion - 1) opinion-position) * max-pxcor) ((item (Y-opinion - 1) opinion-position) * max-pycor)
;; lastly we move agent on the place given by opinion dimensions chosen for X and Y coordinates
set xcor (item (X-opinion - 1) opinion-position) * max-pxcor
set ycor (item (Y-opinion - 1) opinion-position) * max-pycor
end
;; sub routine for coloring agents according their average opinion across all dimensions --
;; useful for distinguishing agents with same displayed coordinates, but differing in other opinion dimensions,
;; then we see at one place agents with different colors.
to getColor
;; speaking agents are colored from very dark red (average -1) through red (average 0) to very light red (average +1)
ifelse speak? [
set color 15 + 4 * mean(opinion-position)
set size (max-pxcor / 10)
]
;; silent agent are white and of zero size, to just show the speaking one -- later we might parametrize this if we want...
[
set color white
set size 0
]
end
;; Sub routine for dissolving whether agent speaks at the given round/step or not
to-report speaking
;; For the case of function we have to update P-speaking value
if p-speaking-drawn = "function" [set P-speaking precision(sqrt (sum (map [ x -> x * x ] opinion-position)) / sqrt opinions) 3]
report P-speaking > random-float 1
end
;; sub-routine for visual purposes -- colors empty patches white, patches with some agents light green, with many agents dark green, with all agents black
to-report patch-color
report 59.9 - (9.8 * (ln(1 + count turtles-here) / ln(N-agents)))
end
;; Sub routine just for catching run-time errors
to avoiding-run-time-errors
;; 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.
;; Check whether we set properly parameter 'updating' --
;; if we want update more dimensions than exists in simulation, then we set 'updating' to max of dimensions, i.e. 'opinions'
if updating > opinions [set updating opinions]
end
;; Just envelope for updating agent at the begining of GO procedure
to preparing-myself
set speak? speaking
getColor
getPlace
;; storing previous opinion position as 'Last-opinion'
set Last-opinion Opinion-position
;; Firstly we have to determine dissatisfaction with the neighborhood
set Satisfied? get-satisfaction
end
to set-group-identities
;; Preparation
ask centroids [die]
;let original_centroids_value N_centroids
;; Detection of clusters via Louvain
ask l-distances [die] ;; Cleaning environment
ask agents [create-l-distances-with other agents with [(sqrt(4 * opinions) - opinion-distance) / sqrt(4 * opinions) >= id_threshold] [set l-weight opinion-distance2 ([opinion-position] of end1)([opinion-position] of end2)]]
;show count l-distances
;ask l-distances with [l-weight < d_threshold] [die]
nw:set-context agents l-distances ;with [l-weight >= d_threshold]
let communities nw:louvain-communities
;show count l-distances
ask l-distances [die]
set N_centroids length communities
;; Computing clusters' mean 'opinion-position'
let postions-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) 3 one
]
;show one
set postions-clusters lput one postions-clusters
;show postions-clusters
]
;; Preparation of centroids -- feedeing them with communities
create-centroids N_centroids [
set heading (who - min [who] of centroids)
set Opinion-position item heading postions-clusters ;; We set opinions, we try to do it smoothly...
;show Opinion-position
set shape "circle"
set size 1.5
set color 5 + who * 10
getPlace
]
;; Assignment of agents to groups
;let min_group min [who] of centroids
ask agents [set group [who] of min-one-of centroids [opinion-distance]]
;; Computation of centroids possitions
compute-centroids-positions
;let iter 0
; ;; Iterating cycle -- looking for good match of centroids
; while [sum [opinion-distance3 (Last-opinion) (Opinion-position)] of centroids > Centroids_change] [
;
; ;set iter iter + 1
; ;show (word "Iteration: " iter)
;
; ;; 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
; ]
;; Killing centroids without connected agents
ask centroids [
let wom who
if (not any? agents with [group = wom]) [
set N_centroids N_centroids - 1
die
]
]
;; Final coloring and killing of centroids
if centroid_color? [ask agents [set color [color] of centroid group]]
if killing_centroids? [ask centroids [die]]
;set N_centroids original_centroids_value
end
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;; G O ! ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Main routine
to go
;; Just checking and avoiding runtime errors part of code
avoiding-run-time-errors
;; Before a round erasing indicator of change
set network-changes 0
;; Prepare group identities via Louvain
set-group-identities
;; True part of GO procedure!
ask agents [
;; speaking, coloring, updating and SATISFACTION!!!
preparing-myself
;; Mechanism of own opinion or network change -- decision and rossolution
;; In case of dissatisfaction agents leave, otherwise updates opinion
ifelse not satisfied? [
change-of-network
set network-changes network-changes + 1 ;; We advance the counter of network changes -- now, one just happened.
] [
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!
]
]
;; The main algorithm might produce lonely agents, now we connect them to one other speaking agent
connect-loners
;; Recoloring patches, 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
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]
if (mean main-Record = 1 and network-changes <= 5) or ticks = max-ticks [stop]
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
end
;; sub-routine computing whether the agent is satisfied with the neighborhood
to-report get-satisfaction
;; initialization of agent set 'supporters' containing agents whose opinion positions are key for agent's satisfaction
let supporters nobody
;; 1) updating agent uses only visible link neighbors in small-world network
let visibles comm-neighbors with [speak?]
;; 2) we have different modes for finding supporters:
;; 2.1) in mode "I got them!" agent looks inside her 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 supporters visibles with [opinion-distance <= lim-dist]
]
;; 2.1) in mode "They got me!" 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 supporters visibles with [opinion-distance <= (Uncertainty * sqrt(opinions * 4))]
]
;print ((1 - (count supporters / count visibles)) < Tolerance)
;; Now we can return the True/False value, whether the agent is satisfied and among visible neighbors are enough supporters
report ifelse-value (count visibles > 0) [((1 - (count supporters / count visibles)) < 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-the-most-annoying-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
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 [(end1 != myself and [speak?] of end1) or (end2 != myself and [speak?] of end2)]
let nei-size count to-visibles
;; Secondly, we cut off all the links
;show (word "I'm killing " nei-size " visible neighbors!")
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 ;show "Not enough visibles!"
]
;; Thirdly, random VS intentional construction of new neighborhood.
ifelse random-network-change? [
;; We set new neighborhood randomly or...
create-comms-with n-of nei-size speaking-others
;show (word "I'm creating " nei-size " links with random visible neighbors!")
][
;; ...creates it out of the closest neighbors.
create-comms-with min-n-of nei-size speaking-others [opinion-distance]
;show (word "I'm creating " nei-size " links with closest visible neighbors!")
]
;; 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 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.
;; DONE!
;;
;; subroutine for changing one link
to rewire-the-most-annoying-link
;; Firstly, we cut the link with speaking agent with the most different opinion
let visibles comm-neighbors with [speak?]
;show visibles
ifelse random-network-change? [
let a-visible one-of visibles
ask one-of my-comms with [other-end = a-visible] [;show self
die]
;show (word "One random link to visible " a-visible " killed!")
][
let annoyer max-one-of comm-neighbors with [speak?] [opinion-distance]
ask one-of my-comms with [other-end = annoyer] [;show self
die]
;show (word "Link to most annoying visible " annoyer " killed!")
]
;; Secondly, we choose for the agent a new speaking partner with the most close opinion
let potentials other agents with [speak? and not comm-neighbor? myself]
;show potentials
ifelse random-network-change? [
create-comm-with one-of potentials ;[show self]
;show (word "Link to One random visible created!")
][
let partner min-one-of potentials [opinion-distance]
create-comm-with partner ;[show self]
;show (word "Link to the closest visible " partner " created!")
]
;; 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 connect-loners
;; We check whether each agent has at least one neighbor
ask agents with [(count comm-neighbors) = 0] [
;; NOTE: Potential BUG! In case the agent without neis is the only speaking agent then 'potentials' = NOBODY and
;; it produces BUG during link creation.
;; That's why I catch it via 'if' structure -- if there is noone speaking, then the lone agent has to wait until the next round.
ifelse (count other agents with [speak?] > 0) [
let potentials other agents with [speak?] ; We set 'potentials' to all other speaking agents and then...
;show "Creating new link!"
create-comm-with ifelse-value (random-network-change?) [one-of potentials][min-one-of potentials [opinion-distance]] ;[show myself] ;... it depends on scenario: we choose randomly or with the closest opinion
;print "Link just has been added!"
][;show "Not any speaking agents!"
]
]
;; 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 nobody
;; 1) updating agent uses only visible link neighbors in small-world network
let visibles other comm-neighbors with [speak?]
;; 2) we have different modes for finding influentials:
;; 2.1) in mode "I got them!" 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 "They got me!" 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 3
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 8
end
;; Sub-routine which opens/creates *.csv file and stores there states of all turtles
to record-state-of-simulation
;; setting working directory
;set-current-directory directory
;; seting 'file-name'
let file-name (word "Sims/Nodes01_" file-name-core "_" ticks ".csv")
;;;; File creation and opening: NODES
;; If file exists at the start we delete it to start with clean file
if file-exists? file-name [file-delete file-name]
file-open file-name ;; This opens existing file (at the end) or creates file if doesn't exist (at the begining)
;; Constructing list for the first row with variable names:
let row (list "ID" "Uncertainty" "pSpeaking" "Speaks")
foreach range Opinions [i -> set row lput (word "Opinion" (i + 1)) row]
;; Writing the variable names in the first row at the start
file-print list-to-string (row)
;; For writing states itself we firstly need to create list of sorted turtles 'srt'
let srt sort agents
;; Then we iterate over the list 'srt':
foreach srt [t -> ask t [ ;; every turtle in the list...
set row (list (word "Nei" who) Uncertainty P-Speaking (ifelse-value (speak?)[1][0])) ;; stores in list ROW its ID, Uncertainty, P-Speaking and whether speaks...
foreach Opinion-position [op -> set row lput (precision(op) 3) row] ;; Opinions ...
file-print list-to-string (row)
file-flush ;; for larger simulations with many agents it will be safer flush the file after each row
]]
;; Finally, we close the file
file-close
file-close
;;;; File creation and opening: LINKS
;; seting 'file-name' for links.
set file-name (word "Sims/Links01_" file-name-core "_" ticks ".csv")
;;;; File creation and opening
;; If file exists at the start we delete it to start with clean file
if file-exists? file-name [file-delete file-name]
file-open file-name ;; This opens existing file (at the end) or creates file if doesn't exist (at the begining)
;; Constructing list for the first row with variable names:
set row (list "ID1" "ID2" "Communication" "Distance")
;; Writing the variable names in the first row at the start
file-print list-to-string (row)
;; We need to prepare counters and other auxilliary varibles for doubled cycle:
let i 0
let j 1
let iMax (count agents - 2)
let jMax (count agents - 1)
let mine []