-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRX-GMV.py
More file actions
2144 lines (1964 loc) · 142 KB
/
RX-GMV.py
File metadata and controls
2144 lines (1964 loc) · 142 KB
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
import dash
from dash import dcc, html, Input, Output, State, callback_context, no_update, ALL
from dash.exceptions import PreventUpdate
import plotly.graph_objects as go
import numpy as np
import random
import json
import time
from collections import defaultdict, deque
import traceback
import uuid
# --- 1. 全局常量和辅助函数 ---
DIM_KEYS = ['b1_resource', 'b2_limitation', 'y1_clarity', 'y2_drive', 'y3_aspiration',
'h1_possibilities', 'h2_innovation', 'h3_risk_appetite',
's1_trustworthiness', 's2_reputation']
DIMENSION_LABELS_MAP_ZH = {
'b1_resource': "本然 B1: 资源/条件", 'b2_limitation': "本然 B2: 限制/障碍",
'y1_clarity': "应然 Y1: 价值清晰度", 'y2_drive': "应然 Y2: 驱动力", 'y3_aspiration': "应然 Y3: 理想高度",
'h1_possibilities': "或然 H1: 可能性广度", 'h2_innovation': "或然 H2: 创新能力",
'h3_risk_appetite': "或然 H3: 风险承受",
's1_trustworthiness': "社交 S1: 可信度", 's2_reputation': "社交 S2: 声望"
}
AXIS_LABELS_ZH = {
'simplified': {'x': '本然 B1 (资源)', 'y': '应然 Y2 (驱动)', 'z': '或然 H1 (可能)'},
'composite': {'x': '本然 (综合)', 'y': '应然 (综合)', 'z': '或然 (综合)'}
}
MAX_LOG_LINES = 250
def sigmoid(x, k=1, x0=5):
if isinstance(x, (np.ndarray, list)): x = np.array(x, dtype=float)
x_clipped = np.clip(x, -500, 500)
return 1 / (1 + np.exp(-k * (x_clipped - x0)))
def scale_value(value, old_min=0, old_max=10, new_min=0, new_max=1):
if old_max == old_min: return new_min
return new_min + (value - old_min) * (new_max - new_min) / (old_max - old_min)
SIMULATION_LOG = deque(maxlen=MAX_LOG_LINES * 2)
def log_message(level, message, source="System"):
global SIMULATION_LOG
timestamp = time.strftime('%H:%M:%S')
log_entry = f"[{timestamp}][{level.upper()}][{source}] {message}"
SIMULATION_LOG.append(log_entry)
if level.upper() in ["ERROR", "CRITICAL"]: print(log_entry)
# --- Community Project Class ---
class CommunityProject:
def __init__(self, project_id, name, required_b1, required_h2, duration,
creator_en, target_participants=2, reward_type='b2_reduction', reward_value=0.5):
self.project_id = project_id;
self.name = name
self.required_b1_total = required_b1;
self.required_h2_avg = required_h2
self.duration_total = duration;
self.creator_en = creator_en
self.target_participants = target_participants
self.reward_type = reward_type;
self.reward_value = reward_value
self.participants = {creator_en};
self.contributed_b1 = 0
self.current_duration = 0;
self.status = "pending"
def add_participant(self, state_en, contribution_b1):
if len(self.participants) < self.target_participants and self.status == "pending":
self.participants.add(state_en);
self.contributed_b1 += contribution_b1
log_message("INFO", f"{state_en} 加入项目 '{self.name}', 贡献B1: {contribution_b1:.2f}", "CommunityProject")
avg_h2_of_participants = 5.0 # Placeholder - this needs real calculation if used
# Real H2 check would require passing all_states_objects_dict here to get H2 of participants
if len(self.participants) == self.target_participants and \
self.contributed_b1 >= self.required_b1_total: # and avg_h2_of_participants >= self.required_h2_avg:
self.status = "active"
log_message("INFO", f"项目 '{self.name}' 已激活!", "CommunityProject")
return True
return False
def progress_project(self, all_states_objects_dict):
if self.status != "active": return
self.current_duration += 1
if self.current_duration >= self.duration_total:
self.status = "completed"
log_message("INFO", f"项目 '{self.name}' 已完成!", "CommunityProject")
self.distribute_rewards(all_states_objects_dict)
def distribute_rewards(self, all_states_objects_dict):
if self.status != "completed": return
for p_name in self.participants:
if p_name in all_states_objects_dict and all_states_objects_dict[p_name]:
p_obj = all_states_objects_dict[p_name]
reward_applied = False
if self.reward_type == 'b1_gain':
p_obj.b1_resource = np.clip(p_obj.b1_resource + self.reward_value, 0, 10);
reward_applied = True
elif self.reward_type == 'b2_reduction':
p_obj.b2_limitation = np.clip(p_obj.b2_limitation - self.reward_value, 0, 10);
reward_applied = True
elif self.reward_type == 'h1_boost':
p_obj.h1_possibilities = np.clip(p_obj.h1_possibilities + self.reward_value, 0, 10);
reward_applied = True
if reward_applied:
p_obj.active_effects_log.append(
f"项目'{self.name}'奖励: {self.reward_type} {self.reward_value:.2f}")
log_message("INFO", f"项目'{self.name}'奖励已分配给 {p_name}", "CommunityProject")
def to_dict(self):
return {'project_id': self.project_id, 'name': self.name, 'required_b1_total': self.required_b1_total,
'required_h2_avg': self.required_h2_avg, 'duration_total': self.duration_total,
'creator_en': self.creator_en, 'target_participants': self.target_participants,
'reward_type': self.reward_type, 'reward_value': self.reward_value,
'participants': list(self.participants), 'contributed_b1': self.contributed_b1,
'current_duration': self.current_duration, 'status': self.status}
@classmethod
def from_dict(cls, data):
proj = cls(data['project_id'], data['name'], data['required_b1_total'], data['required_h2_avg'],
data['duration_total'], data['creator_en'], data.get('target_participants', 2),
data['reward_type'], data['reward_value'])
proj.participants = set(data.get('participants', []));
proj.contributed_b1 = data.get('contributed_b1', 0)
proj.current_duration = data.get('current_duration', 0);
proj.status = data.get('status', "pending")
return proj
# --- WorldState Class ---
class WorldState:
def __init__(self, name_zh, name_en, b1_res, b2_lim, y1_cla, y2_dri, y3_asp,
h1_pos, h2_inn, h3_ris, s1_tru=5.0, s2_rep=3.0):
self.name_zh = name_zh;
self.name_en = name_en
dim_values = {'b1_resource': b1_res, 'b2_limitation': b2_lim, 'y1_clarity': y1_cla, 'y2_drive': y2_dri,
'y3_aspiration': y3_asp, 'h1_possibilities': h1_pos, 'h2_innovation': h2_inn,
'h3_risk_appetite': h3_ris, 's1_trustworthiness': s1_tru, 's2_reputation': s2_rep}
for key in DIM_KEYS: setattr(self, key, np.clip(float(dim_values.get(key, 0)), 0, 10))
self.history = [];
self.neighbors = [];
self.trust_levels = defaultdict(lambda: 5.0)
self.active_effects_log = [];
self.last_risk_outcome_factor = 0.0
self.alliance_partners = set();
self.rivals = set();
self.social_interaction_cooldowns = defaultdict(int)
self.perceived_b1_resource = self.b1_resource;
self.perceived_h1_possibilities = self.h1_possibilities
self.perception_accuracy = scale_value(self.y1_clarity, 0, 10, 0.5, 1.0);
self.mood = 0
self.community_norm_conformity = random.uniform(0.3, 0.7);
self.contributed_projects = {}
def get_display_name(self):
return f"{self.name_zh} ({self.name_en})"
def get_coords_for_plot(self, coord_type='simplified', wb=(0.6, 0.4), wy=(0.4, 0.4, 0.2), wh=(0.4, 0.4, 0.2)):
if coord_type == 'simplified':
return (self.b1_resource, self.y2_drive, self.h1_possibilities)
elif coord_type == 'composite':
b_comp = wb[0] * self.b1_resource - wb[1] * self.b2_limitation
y_comp = wy[0] * self.y1_clarity + wy[1] * self.y2_drive + wy[2] * self.y3_aspiration
h_comp = wh[0] * self.h1_possibilities + wh[1] * self.h2_innovation + wh[2] * self.h3_risk_appetite
return (np.clip(b_comp, 0, 10), np.clip(y_comp, 0, 10), np.clip(h_comp, 0, 10))
return (self.b1_resource, self.y1_clarity, self.h1_possibilities)
def _apply_boundary_effect(self, current_value, delta_value, min_val=0, max_val=10, boundary_threshold=0.5):
if current_value <= min_val + boundary_threshold and delta_value < 0:
return delta_value * scale_value(current_value, min_val, min_val + boundary_threshold, 0.1, 1)
elif current_value >= max_val - boundary_threshold and delta_value > 0:
return delta_value * scale_value(current_value, max_val - boundary_threshold, max_val, 1, 0.1)
return delta_value
def update_perception(self, params):
k_cog = params.get('coefficients', {}).get('cognitive_model', {})
base_acc = scale_value(self.y1_clarity, 0, 10, k_cog.get('y1_to_acc_min', 0.4), k_cog.get('y1_to_acc_max', 1.0))
h2_bonus = scale_value(self.h2_innovation, 0, 10, 0, k_cog.get('h2_to_acc_bonus', 0.1))
self.perception_accuracy = np.clip(base_acc + h2_bonus, 0.1, 1.0)
mood_bias = 0
if self.mood > 0:
mood_bias = k_cog.get('mood_pos_bias_factor', 0.1) * self.mood
elif self.mood < 0:
mood_bias = k_cog.get('mood_neg_bias_factor', -0.1) * abs(self.mood)
err_scale = params.get('perception_error_scale', 5.0)
b1_err = (1 - self.perception_accuracy) * err_scale;
self.perceived_b1_resource = np.clip(
self.b1_resource + random.uniform(-b1_err, b1_err) + (self.b1_resource * mood_bias), 0, 10)
h1_err = (1 - self.perception_accuracy) * params.get('perception_error_scale_h1', 4.0);
self.perceived_h1_possibilities = np.clip(
self.h1_possibilities + random.uniform(-h1_err, h1_err) + (self.h1_possibilities * mood_bias), 0, 10)
def update_mood(self, params, risk_outcome_this_step):
k_cog = params.get('coefficients', {}).get('cognitive_model', {})
change = 0
if risk_outcome_this_step > params.get('mood_risk_success_thresh', 0.1):
change += k_cog.get('mood_from_risk_success', 0.5) * scale_value(risk_outcome_this_step, 0.1, 1, 0, 1)
elif risk_outcome_this_step < params.get('mood_risk_failure_thresh', -0.1):
change += k_cog.get('mood_from_risk_failure', -0.5) * scale_value(abs(risk_outcome_this_step), 0.1, 1, 0, 1)
if self.b1_resource < params.get('mood_b1_low_thresh', 2.0):
change -= k_cog.get('mood_from_low_b1', 0.1)
elif self.b1_resource > params.get('mood_b1_high_thresh', 7.0):
change += k_cog.get('mood_from_high_b1', 0.05)
if len(self.alliance_partners) > len(self.rivals) and len(self.alliance_partners) > 0:
change += k_cog.get('mood_from_alliances', 0.05)
elif len(self.rivals) > len(self.alliance_partners) and len(self.rivals) > 0:
change -= k_cog.get('mood_from_rivals', 0.05)
self.mood += change * k_cog.get('mood_change_rate', 0.3)
self.mood = np.clip(self.mood, k_cog.get('mood_min', -1.0), k_cog.get('mood_max', 1.0))
self.mood *= k_cog.get('mood_decay_factor', 0.95)
# --- Delta Calculation Methods (GM4.5.6 - includes Stage 2, 5 modifications) ---
# (Copied from GM4.5.6 provided previously, assuming they are correct for this consolidation)
def _calculate_delta_b1(self, k_dim, params, avg_b1_others, neighbor_effect_b1, risk_project_b1_change_this_step):
effect_h2 = k_dim.get('from_h2', 0) * sigmoid(self.h2_innovation, k=0.7, x0=5);
effect_y2 = k_dim.get('from_y2', 0) * scale_value(self.y2_drive, 0, 10, 0.3, 1)
loss_b2 = k_dim.get('loss_b2', 0) * (self.b2_limitation / 10) ** 1.8;
cost_h2_activity = k_dim.get('cost_h2_activity', 0) * self.h2_innovation * (1 + self.h2_innovation / 20)
cost_y2_sustain = k_dim.get('cost_y2_sustain', 0) * self.y2_drive * (1 + self.y2_drive / 20);
reputation_bonus_b1 = k_dim.get('from_s2_reputation', 0) * self.s2_reputation
social_pressure_b1 = 0;
if avg_b1_others is not None: social_pressure_b1 = k_dim.get('social_pressure', 0) * np.clip(
avg_b1_others - self.b1_resource, -3, 3)
base_consumption = params.get('b1_maintenance_base', 0.03);
non_linear_maintenance = params.get('b1_maintenance_factor', 0.005) * (
self.b1_resource / params.get('b1_maintenance_scale_ref', 10.0)) ** params.get(
'b1_maintenance_exponent', 2.0)
total_consumption = base_consumption + non_linear_maintenance;
h2_to_b1_direct_gain = 0
if self.h2_innovation > params.get('h2_to_b1_direct_thresh', 7.0) and self.y2_drive > params.get(
'y2_for_h2_to_b1_direct_thresh', 6.0) and random.random() < k_dim.get('h2_to_b1_direct_prob', 0.01):
h2_to_b1_direct_gain = k_dim.get('h2_to_b1_direct_factor', 0.05) * self.h2_innovation;
self.active_effects_log.append(f"H2成果B1: +{h2_to_b1_direct_gain:.2f}")
delta = (
effect_h2 + effect_y2 - loss_b2 - total_consumption - cost_h2_activity - cost_y2_sustain + risk_project_b1_change_this_step + social_pressure_b1 + neighbor_effect_b1 + reputation_bonus_b1 + h2_to_b1_direct_gain)
return self._apply_boundary_effect(self.b1_resource, delta)
def _calculate_delta_b2(self, k_dim, params, neighbor_effect_b2, risk_project_b2_change_this_step):
reduction_y2 = k_dim.get('reduce_y2', 0) * sigmoid(self.y2_drive, k=0.8, x0=3);
reduction_h2 = k_dim.get('reduce_h2', 0) * sigmoid(self.h2_innovation, k=0.8, x0=3);
random_event_b2 = 0
if random.random() < params.get('b2_random_event_chance', 0.04): random_event_b2 = random.uniform(0,
0.8) * k_dim.get(
'random_factor', 0.15)
over_extension_factor = 0
if self.y2_drive > params.get('b2_y2_overextension_thresh', 9.0): over_extension_factor += (
self.y2_drive - params.get(
'b2_y2_overextension_thresh',
9.0)) * k_dim.get(
'from_y2_overextension', 0.015)
if self.h2_innovation > params.get('b2_h2_overextension_thresh', 9.0): over_extension_factor += (
self.h2_innovation - params.get(
'b2_h2_overextension_thresh',
9.0)) * k_dim.get(
'from_h2_overextension', 0.01)
h2_to_b2_reduction = 0
if self.h2_innovation > params.get('h2_to_b2_reduction_thresh', 7.5) and self.y1_clarity > params.get(
'y1_for_h2_to_b2_reduction_thresh', 6.5) and random.random() < k_dim.get('h2_to_b2_reduction_prob',
0.008):
h2_to_b2_reduction = k_dim.get('h2_to_b2_reduction_factor', 0.06) * self.h2_innovation;
self.active_effects_log.append(f"H2成果降低B2: -{h2_to_b2_reduction:.2f}")
delta = -(
reduction_y2 + reduction_h2) - h2_to_b2_reduction + random_event_b2 + over_extension_factor + risk_project_b2_change_this_step + neighbor_effect_b2
return self._apply_boundary_effect(self.b2_limitation, delta)
def _calculate_delta_y1(self, k_dim, params, neighbor_effect_y1, current_risk_outcome_this_step):
effect_experience_validation = 0
if current_risk_outcome_this_step > params.get('risk_success_return_threshold_for_y1', 0.03):
effect_experience_validation = k_dim.get('from_success_validation', 0) * sigmoid(
current_risk_outcome_this_step, k=5, x0=0.1)
elif current_risk_outcome_this_step < -params.get('risk_failure_loss_threshold_for_y1', 0.03):
effect_experience_validation = k_dim.get('from_failure_doubt', 0) * sigmoid(current_risk_outcome_this_step,
k=-5, x0=-0.1)
loss_b2 = k_dim.get('loss_b2', 0) * (self.b2_limitation / 7) ** 2.0;
perceived_reality_measure = (self.perceived_b1_resource + self.perceived_h1_possibilities) / 2
aspiration_reality_gap = self.y3_aspiration - perceived_reality_measure;
loss_from_gap = 0
if aspiration_reality_gap > params.get('y1_gap_threshold_for_loss', 3.0): loss_from_gap = k_dim.get(
'loss_aspiration_gap', 0) * (aspiration_reality_gap - params.get('y1_gap_threshold_for_loss', 3.0))
y1_maintenance_cost = 0
if self.y1_clarity > params.get('y1_high_maintenance_thresh', 8.0):
grounding_factor = (scale_value(self.b1_resource, 0, 5, 0.1, 1) + scale_value(self.h1_possibilities, 0, 5,
0.1, 1)) / 2
y1_maintenance_cost = k_dim.get('high_y1_decay_factor', 0.005) * (
self.y1_clarity - params.get('y1_high_maintenance_thresh', 8.0)) / (grounding_factor + 0.1)
b_state_y1_adjustment = 0
if self.b1_resource < params.get('b1_for_y1_erosion_thresh', 2.0) and self.b2_limitation > params.get(
'b2_for_y1_erosion_thresh', 7.0):
b_state_y1_adjustment -= k_dim.get('b_state_y1_erosion_factor', 0.01) * (
1 - scale_value(self.y1_clarity, 0, 5, 0, 1))
elif self.b1_resource > params.get('b1_for_y1_affirm_thresh', 7.0) and self.b2_limitation < params.get(
'b2_for_y1_affirm_thresh', 3.0) and self.y2_drive > params.get('y2_for_y1_affirm_thresh', 5.0):
b_state_y1_adjustment += k_dim.get('b_state_y1_affirm_factor', 0.005) * (
1 - scale_value(self.y1_clarity, 5, 10, 0, 1))
delta = effect_experience_validation - loss_b2 - loss_from_gap - y1_maintenance_cost + b_state_y1_adjustment + neighbor_effect_y1
return self._apply_boundary_effect(self.y1_clarity, delta)
def _calculate_delta_y2(self, k_dim, params, neighbor_effect_y2, current_risk_outcome_this_step):
effect_y1 = k_dim.get('from_y1', 0) * sigmoid(self.y1_clarity, k=0.8, x0=3.5);
aspiration_gap_y2 = self.y3_aspiration - self.y2_drive
effect_y3 = k_dim.get('from_y3', 0) * sigmoid(aspiration_gap_y2, k=0.4, x0=0.5) * (
1 - sigmoid(self.y2_drive, k=params.get('y2_saturation_k', 1.0),
x0=params.get('y2_saturation_x0', 8.0)))
effect_risk_outcome = 0
if current_risk_outcome_this_step > params.get('risk_success_return_threshold_for_y2', 0.02):
effect_risk_outcome = k_dim.get('from_risk_success_激励', 0) * sigmoid(current_risk_outcome_this_step, k=6,
x0=0.05)
elif current_risk_outcome_this_step < -params.get('risk_failure_loss_threshold_for_y2', 0.02):
effect_risk_outcome = k_dim.get('from_risk_failure_打击', 0) * sigmoid(current_risk_outcome_this_step, k=-6,
x0=-0.05)
loss_b2 = k_dim.get('loss_b2', 0) * (self.b2_limitation / 9) ** 1.5;
loss_low_y1 = k_dim.get('loss_low_y1', 0) * (1 - sigmoid(self.y1_clarity, k=1, x0=1.5));
sustain_cost_low_b1 = 0
if self.b1_resource < params.get('y2_b1_sustain_threshold', 2.0): sustain_cost_low_b1 = k_dim.get(
'sustain_cost_low_b1', 0) * (params.get('y2_b1_sustain_threshold', 2.0) - self.b1_resource)
y2_burnout_factor = 0
if self.y2_drive > params.get('y2_burnout_thresh', 7.5):
y2_burnout_factor = k_dim.get('burnout_factor_base', 0.012) * (
self.y2_drive - params.get('y2_burnout_thresh', 7.5)) * (
1.5 - scale_value(self.b1_resource, 0, 7, 0.3, 1.0)) * (
1.5 - scale_value(self.y1_clarity, 0, 7, 0.3, 1.0))
y2_burnout_factor = max(0, y2_burnout_factor)
b_state_y2_adjustment = 0
if self.b1_resource < params.get('b1_for_y2_sap_thresh', 1.5) or self.b2_limitation > params.get(
'b2_for_y2_sap_thresh', 7.5):
b_state_y2_adjustment -= k_dim.get('b_state_y2_sap_factor', 0.012) * (
1 - scale_value(self.y2_drive, 0, 4, 0, 1))
elif self.b1_resource > params.get('b1_for_y2_boost_thresh', 6.5) and self.y1_clarity > params.get(
'y1_for_y2_boost_thresh', 6.0):
b_state_y2_adjustment += k_dim.get('b_state_y2_boost_factor', 0.006) * (
1 - scale_value(self.y2_drive, 6, 10, 0, 1))
delta = effect_y1 + effect_y3 + effect_risk_outcome - loss_b2 - loss_low_y1 - sustain_cost_low_b1 - y2_burnout_factor + b_state_y2_adjustment + neighbor_effect_y2
return self._apply_boundary_effect(self.y2_drive, delta)
def _calculate_delta_y3(self, k_dim, params, neighbor_effect_y3, avg_b1_others, avg_h1_others):
adjustment_from_y2 = k_dim.get('adjust_y2', 0) * (self.y2_drive - self.y3_aspiration) * 0.025;
boost_y1 = k_dim.get('boost_y1', 0) * sigmoid(self.y1_clarity - 6.0, k=0.9, x0=0)
social_norm_b1_factor = 0;
if avg_b1_others is not None: social_norm_b1_factor = k_dim.get('social_norm_b1', 0) * (
avg_b1_others + params.get('y3_social_b1_offset', 1.0) - self.y3_aspiration)
social_norm_h1_factor = 0;
if avg_h1_others is not None: social_norm_h1_factor = k_dim.get('social_norm_h1', 0) * (
avg_h1_others + params.get('y3_social_h1_offset', 0.5) - self.y3_aspiration)
self_h1_factor = k_dim.get('self_h1_factor', 0) * (self.perceived_h1_possibilities - self.y3_aspiration) * (
1 - sigmoid(self.y3_aspiration, k=params.get('y3_aspiration_h1_influence_damp_k', 1.5),
x0=params.get('y3_aspiration_h1_influence_damp_x0', 8.5)))
reality_crush = 0
if self.perceived_b1_resource < self.y3_aspiration - params.get('y3_reality_gap_threshold',
4.0): reality_crush = k_dim.get(
'loss_reality_gap', 0) * (self.y3_aspiration - self.perceived_b1_resource - params.get(
'y3_reality_gap_threshold', 4.0))
y3_complacency_drag = 0
if self.y3_aspiration > params.get('y3_complacency_thresh', 8.5):
if (self.y3_aspiration - self.perceived_b1_resource > params.get('y3_complacency_b1_gap', 4.0)) or (
self.y3_aspiration - self.perceived_h1_possibilities > params.get('y3_complacency_h1_gap', 4.0)):
y3_complacency_drag = k_dim.get('complacency_drag_factor', 0.006) * (
self.y3_aspiration - params.get('y3_complacency_thresh', 8.5))
b_success_y3_lift = 0
if self.b1_resource > params.get('b1_for_y3_lift_thresh', 7.5) and self.b2_limitation < params.get(
'b2_for_y3_lift_thresh', 2.5) and self.y2_drive > params.get('y2_for_y3_lift_thresh', 6.5):
b_success_y3_lift = k_dim.get('b_success_y3_lift_factor', 0.004) * (
params.get('y3_target_after_b_success', 9.0) - self.y3_aspiration)
delta = adjustment_from_y2 + boost_y1 + social_norm_b1_factor + social_norm_h1_factor + self_h1_factor - reality_crush - y3_complacency_drag + b_success_y3_lift + neighbor_effect_y3
return self._apply_boundary_effect(self.y3_aspiration, delta)
def _calculate_delta_h1(self, k_dim, params, neighbor_effect_h1):
effect_b1 = k_dim.get('from_b1', 0) * sigmoid(self.b1_resource, k=0.6, x0=3.5) * (
1.1 - sigmoid(self.h1_possibilities, k=params.get('h1_b1_influence_damp_k', 1),
x0=params.get('h1_b1_influence_damp_x0', 8)))
effect_h2 = k_dim.get('from_h2', 0) * sigmoid(self.h2_innovation, k=0.7, x0=3.0);
loss_b2 = k_dim.get('loss_b2', 0) * (self.b2_limitation / 6) ** 2.0
loss_low_y2_y1 = k_dim.get('loss_low_y_factor', 0) * ((1 - scale_value(self.y2_drive, 0, 3.5, 0, 1)) + (
1 - scale_value(self.y1_clarity, 0, 3.5, 0, 1))) / 2;
h1_focus_cost = 0
if self.h1_possibilities > params.get('h1_focus_cost_thresh', 8.5):
h1_focus_cost = k_dim.get('focus_cost_factor', 0.008) * (
self.h1_possibilities - params.get('h1_focus_cost_thresh', 8.5)) * (
1.2 - scale_value(self.y1_clarity, 0, 7, 0.2, 1.0));
h1_focus_cost = max(0, h1_focus_cost)
b2_direct_h1_suppression = 0
if self.b2_limitation > params.get('b2_h1_suppression_thresh', 6.0): b2_direct_h1_suppression = k_dim.get(
'b2_h1_suppression_factor', 0.01) * (self.b2_limitation - params.get('b2_h1_suppression_thresh',
6.0)) * scale_value(
self.h1_possibilities, 0, 10, 0.3, 1)
delta = effect_b1 + effect_h2 - loss_b2 - loss_low_y2_y1 - h1_focus_cost - b2_direct_h1_suppression + neighbor_effect_h1
return self._apply_boundary_effect(self.h1_possibilities, delta)
def _calculate_delta_h2(self, k_dim, params, neighbor_effect_h2):
synergy_y1_y2 = self.y1_clarity * self.y2_drive / 100
effect_y2_h3 = (k_dim.get('from_y2', 0) * self.y2_drive + k_dim.get('from_h3', 0) * self.h3_risk_appetite) * (
0.4 + 0.6 * sigmoid(synergy_y1_y2, k=0.1, x0=(5 * 6 / 100))) * (
1.1 - sigmoid(self.h2_innovation, k=params.get('h2_innovation_saturation_k', 1),
x0=params.get('h2_innovation_saturation_x0', 8.5)))
practice_factor = (scale_value(self.y2_drive, 0, 10, 0.1, 1) + scale_value(self.h3_risk_appetite, 0, 10, 0.1,
1)) / 2
decay = k_dim.get('decay_no_practice', 0) * (1.1 - practice_factor) * (
self.h2_innovation / params.get('h2_decay_scale_ref', 9.0));
h2_complexity_cost = 0
if self.h2_innovation > params.get('h2_complexity_thresh', 8.0):
integration_capacity = (scale_value(self.b1_resource, 0, 6, 0.2, 1.0) + scale_value(self.y1_clarity, 0, 6,
0.2, 1.0)) / 2
h2_complexity_cost = k_dim.get('complexity_cost_factor', 0.007) * (
self.h2_innovation - params.get('h2_complexity_thresh', 8.0)) / (integration_capacity + 0.1)
y3_h2_drive = 0
if self.y3_aspiration > params.get('y3_for_h2_drive_thresh', 7.0) and self.y1_clarity > params.get(
'y1_for_h2_drive_thresh', 6.0) and self.b1_resource > params.get('b1_for_h2_drive_thresh', 3.0):
y3_h2_drive = k_dim.get('y3_h2_drive_factor', 0.005) * (
self.y3_aspiration - params.get('y3_for_h2_drive_thresh', 7.0)) * (
1 - scale_value(self.h2_innovation, 7, 10, 0, 1))
delta = effect_y2_h3 + y3_h2_drive - decay - h2_complexity_cost + neighbor_effect_h2
return self._apply_boundary_effect(self.h2_innovation, delta)
def _calculate_delta_h3(self, k_dim, params, neighbor_effect_h3, current_risk_outcome_this_step):
effect_risk_outcome = 0;
risk_outcome_h3_dampening = (
1 - sigmoid(abs(self.h3_risk_appetite - 5), k=params.get('h3_risk_feedback_damp_k', 0.3),
x0=params.get('h3_risk_feedback_damp_x0', 4)))
if current_risk_outcome_this_step > params.get('risk_success_return_threshold_for_h3', 0.03):
effect_risk_outcome = k_dim.get('from_risk_success_回报', 0) * sigmoid(current_risk_outcome_this_step, k=8,
x0=0.05) * risk_outcome_h3_dampening
elif current_risk_outcome_this_step < -params.get('risk_failure_loss_threshold_for_h3', 0.03):
effect_risk_outcome = k_dim.get('from_risk_failure_惩罚', 0) * sigmoid(current_risk_outcome_this_step, k=-8,
x0=-0.05) * risk_outcome_h3_dampening
effect_y1 = k_dim.get('from_y1', 0) * sigmoid(self.y1_clarity, k=0.7, x0=6.0);
effect_y2 = k_dim.get('from_y2', 0) * sigmoid(self.y2_drive, k=0.7, x0=6.0);
loss_b2 = k_dim.get('loss_b2', 0) * (self.b2_limitation / 10) ** 1.3;
stability_caution = 0
if self.b1_resource > params.get('h3_b1_stability_thresh', 8.0) and self.b2_limitation < params.get(
'h3_b2_stability_thresh', 2.0): stability_caution = k_dim.get('stability_caution_factor', 0.006) * (
self.h3_risk_appetite - params.get('h3_stable_target_risk', 3.0))
desperation_risk_push = 0
if self.b1_resource < params.get('h3_b1_desperation_thresh', 2.0) and self.y2_drive > params.get(
'h3_y2_desperation_thresh', 6.0): desperation_risk_push = k_dim.get('desperation_risk_factor',
0.004) * (
params.get('h3_desperate_target_risk',
7.0) - self.h3_risk_appetite)
delta = effect_risk_outcome + effect_y1 + effect_y2 - loss_b2 - stability_caution + desperation_risk_push + neighbor_effect_h3
return self._apply_boundary_effect(self.h3_risk_appetite, delta)
def _calculate_delta_s1_trustworthiness(self, k_dim, params, neighbor_feedback_s1, current_risk_outcome_this_step):
delta = 0;
consistency_factor = sigmoid(self.y1_clarity - 5, k=0.8, x0=0) * sigmoid(
(self.b1_resource + self.h2_innovation) / 2 - (self.y3_aspiration - 2), k=0.6, x0=0)
delta += k_dim.get('from_consistency', 0) * consistency_factor * (
1.1 - sigmoid(self.s1_trustworthiness, k=1, x0=8.5))
if current_risk_outcome_this_step < params.get('s1_risk_failure_penalty_thresh', -0.3): delta -= k_dim.get(
'penalty_risk_failure', 0) * abs(current_risk_outcome_this_step)
delta += neighbor_feedback_s1;
delta -= k_dim.get('decay', 0) * (self.s1_trustworthiness / params.get('s_decay_scale_ref', 10.0))
return self._apply_boundary_effect(self.s1_trustworthiness, delta)
def _calculate_delta_s2_reputation(self, k_dim, params, neighbor_feedback_s2, current_risk_outcome_this_step):
delta = 0;
achievement_factor = (scale_value(self.b1_resource, 3, 10, 0, 1) + scale_value(self.h2_innovation, 4, 10, 0,
1)) / 2
delta += k_dim.get('from_achievement', 0) * achievement_factor * (
1.1 - sigmoid(self.s2_reputation, k=1, x0=8.5))
value_appeal_factor = sigmoid(self.y1_clarity - 6, k=0.7, x0=0) * sigmoid(self.y3_aspiration - 6, k=0.7, x0=0)
delta += k_dim.get('from_value_appeal', 0) * value_appeal_factor * (
1.1 - sigmoid(self.s2_reputation, k=1, x0=8.5))
if current_risk_outcome_this_step > params.get('s2_risk_success_bonus_thresh', 0.15): delta += k_dim.get(
'bonus_risk_success', 0) * current_risk_outcome_this_step
delta += neighbor_feedback_s2;
delta -= k_dim.get('decay', 0) * (self.s2_reputation / params.get('s_decay_scale_ref', 10.0))
return self._apply_boundary_effect(self.s2_reputation, delta)
def _calculate_neighbor_effects(self, params, all_states_objects_dict):
k_social = params.get('coefficients', {}).get('social_interactions', {});
effects = {key: 0.0 for key in DIM_KEYS};
num_valid_neighbors = 0
if not self.neighbors: return effects
sum_neighbor_y1, sum_neighbor_y2, sum_neighbor_y3, sum_neighbor_s1, sum_neighbor_s2 = 0, 0, 0, 0, 0
for neighbor_name in self.neighbors:
if neighbor_name in all_states_objects_dict and neighbor_name != self.name_en:
neighbor_obj = all_states_objects_dict[neighbor_name];
if neighbor_obj is None: continue
num_valid_neighbors += 1;
trust_target = neighbor_obj.s1_trustworthiness
trust_delta = k_social.get('trust_formation_rate', 0) * (
trust_target - self.trust_levels[neighbor_name]) * scale_value(self.s1_trustworthiness, 0,
10, 0.8, 1.2)
self.trust_levels[neighbor_name] = np.clip(self.trust_levels[neighbor_name] + trust_delta, 0, 10);
current_trust_in_neighbor = self.trust_levels[neighbor_name]
sum_neighbor_y1 += neighbor_obj.y1_clarity;
sum_neighbor_y2 += neighbor_obj.y2_drive;
sum_neighbor_y3 += neighbor_obj.y3_aspiration;
sum_neighbor_s1 += neighbor_obj.s1_trustworthiness;
sum_neighbor_s2 += neighbor_obj.s2_reputation
coop_factor_trust = scale_value(current_trust_in_neighbor, 0, 10,
k_social.get('trust_effect_min_coop', 0.5),
k_social.get('trust_effect_max_coop', 1.5))
b1_diff = neighbor_obj.b1_resource - self.b1_resource;
b1_comp_loss_mod = 1.0;
b1_coop_gain_mod = 1.0
if neighbor_name in self.rivals:
b1_comp_loss_mod = k_social.get('rival_comp_loss_multiplier', 1.5);
b1_coop_gain_mod = k_social.get(
'rival_coop_gain_multiplier', 0.3)
elif neighbor_name in self.alliance_partners:
b1_comp_loss_mod = k_social.get('alliance_comp_loss_multiplier',
0.5);
b1_coop_gain_mod = k_social.get(
'alliance_coop_gain_multiplier', 1.5)
if b1_diff > k_social.get('b1_comp_diff_thresh', 1.0):
effects['b1_resource'] -= k_social.get('b1_comp_loss_factor', 0) * b1_diff * (
k_social.get('base_comp_factor', 1.1) - coop_factor_trust * 0.5) * b1_comp_loss_mod
elif abs(b1_diff) < k_social.get('b1_coop_diff_thresh', 0.6) and self.b1_resource > k_social.get(
'b1_coop_min_self_res', 2.0):
effects['b1_resource'] += k_social.get('b1_coop_gain_factor', 0) * min(self.b1_resource,
neighbor_obj.b1_resource) * coop_factor_trust * b1_coop_gain_mod
h2_info_share_mod = 1.0
if neighbor_name in self.rivals:
h2_info_share_mod = k_social.get('rival_h2_share_multiplier', 0.1)
elif neighbor_name in self.alliance_partners:
h2_info_share_mod = k_social.get('alliance_h2_share_multiplier', 1.8)
if neighbor_obj.h2_innovation > self.h2_innovation + k_social.get('h2_info_share_min_diff', 0.5):
info_gain_potential = (neighbor_obj.h2_innovation - self.h2_innovation) * k_social.get(
'h2_info_share_factor', 0)
trust_in_source_factor = scale_value(current_trust_in_neighbor, 0, 10, 0.3, 1.0);
source_reputation_factor = scale_value(neighbor_obj.s2_reputation, 0, 10, 0.5, 1.2);
self_openness_factor = scale_value(self.y1_clarity, 0, 10, 0.7, 1.0)
effects['h2_innovation'] = effects.get('h2_innovation',
0) + info_gain_potential * trust_in_source_factor * source_reputation_factor * self_openness_factor * h2_info_share_mod
if neighbor_name in self.rivals and current_trust_in_neighbor < k_social.get('rival_harm_trust_thresh',
3.0):
sabotage_strength = (k_social.get('rival_harm_trust_thresh',
3.0) - current_trust_in_neighbor) * scale_value(
neighbor_obj.y2_drive, 0, 10, 0.5, 1.2)
effects['b2_limitation'] = effects.get('b2_limitation', 0) + k_social.get(
'rival_sabotage_b2_factor', 0.005) * sabotage_strength
effects['s2_reputation'] = effects.get('s2_reputation', 0) - k_social.get('rival_smear_s2_factor',
0.003) * sabotage_strength
if num_valid_neighbors > 0:
avg_neighbor_y1 = sum_neighbor_y1 / num_valid_neighbors;
avg_neighbor_y2 = sum_neighbor_y2 / num_valid_neighbors;
avg_neighbor_y3 = sum_neighbor_y3 / num_valid_neighbors;
avg_neighbor_s1 = sum_neighbor_s1 / num_valid_neighbors;
avg_neighbor_s2 = sum_neighbor_s2 / num_valid_neighbors
confidence_factor_self = scale_value(self.s2_reputation, 0, 10, 0.5, 1.0);
y_align_mod = 1.0
num_allies = len(self.alliance_partners.intersection(self.neighbors));
num_rivals = len(self.rivals.intersection(self.neighbors))
if num_allies / num_valid_neighbors > k_social.get('alliance_majority_for_y_align_boost', 0.6):
y_align_mod = k_social.get('alliance_y_align_multiplier', 1.3)
elif num_rivals / num_valid_neighbors > k_social.get('rival_majority_for_y_align_reduction', 0.4):
y_align_mod = k_social.get('rival_y_align_multiplier', 0.7)
effects['y1_clarity'] = effects.get('y1_clarity', 0) + k_social.get('y1_alignment_factor', 0) * (
avg_neighbor_y1 - self.y1_clarity) * (1 - sigmoid(self.y1_clarity, k=1.2,
x0=params.get('y_social_align_self_thresh',
7.5))) * (
1.1 - confidence_factor_self) * y_align_mod
effects['y2_drive'] = effects.get('y2_drive', 0) + k_social.get('y2_contagion_factor', 0) * (
avg_neighbor_y2 - self.y2_drive) * (1 - sigmoid(self.y2_drive, k=1.2,
x0=params.get('y_social_align_self_thresh',
7.5))) * (
1.1 - confidence_factor_self) * y_align_mod
effects['y3_aspiration'] = effects.get('y3_aspiration', 0) + k_social.get('y3_alignment_factor', 0) * (
avg_neighbor_y3 - self.y3_aspiration) * (1 - sigmoid(self.y3_aspiration, k=1, x0=params.get(
'y3_social_align_self_thresh', 8.0))) * (1.1 - confidence_factor_self) * y_align_mod
effects['s1_trustworthiness'] = effects.get('s1_trustworthiness', 0) + k_social.get('s1_social_norm_factor',
0) * (
avg_neighbor_s1 - self.s1_trustworthiness)
effects['s2_reputation'] = effects.get('s2_reputation', 0) + k_social.get('s2_social_pressure_factor',
0) * (
avg_neighbor_s2 - self.s2_reputation)
avg_neighbor_h3 = np.mean([s.h3_risk_appetite for s_name, s in all_states_objects_dict.items() if
s_name in self.neighbors and s is not None]) if num_valid_neighbors > 0 else self.h3_risk_appetite
h3_norm_pressure = (avg_neighbor_h3 - self.h3_risk_appetite) * k_social.get('h3_norm_pressure_factor',
0.002) * self.community_norm_conformity * (
1 - scale_value(self.y1_clarity, 0, 10, 0, 0.8))
effects['h3_risk_appetite'] = effects.get('h3_risk_appetite', 0) + h3_norm_pressure
return effects
### MODIFIED: manage_social_relations with stricter checks and cleanup ###
def manage_social_relations(self, params, all_states_objects_dict, current_step):
k_social = params.get('coefficients', {}).get('social_interactions', {})
social_action_interval = params.get('social_action_interval', 5)
if current_step % social_action_interval != 0:
return
# Decay cooldowns first
for key in list(self.social_interaction_cooldowns.keys()):
self.social_interaction_cooldowns[key] -= social_action_interval
if self.social_interaction_cooldowns[key] <= 0:
del self.social_interaction_cooldowns[key]
for neighbor_name in list(
self.neighbors): # Iterate over a copy if self.neighbors might change (not in this logic)
if neighbor_name not in all_states_objects_dict or neighbor_name == self.name_en:
continue
neighbor_obj = all_states_objects_dict[neighbor_name]
if not neighbor_obj: # Should not happen if dict is clean
continue
my_trust_in_neighbor = self.trust_levels.get(neighbor_name, 5.0) # My trust in them
neighbor_trust_in_me = neighbor_obj.trust_levels.get(self.name_en, 5.0) # Their trust in me
cooldown_key_alliance = f"form_alliance_{neighbor_name}"
cooldown_key_rivalry = f"form_rivalry_{neighbor_name}"
cooldown_key_break_alliance = f"break_alliance_{neighbor_name}" # Optional: cooldown for re-evaluating break
cooldown_key_end_rivalry = f"end_rivalry_{neighbor_name}" # Optional: cooldown for re-evaluating end
# --- I. Attempt to form new relations OR break existing ones ---
# A. Check for forming an ALLIANCE
# Conditions: Not already allied, not already rival, not on alliance cooldown, AND meets alliance criteria
if neighbor_name not in self.alliance_partners and \
neighbor_name not in self.rivals and \
self.social_interaction_cooldowns.get(cooldown_key_alliance, 0) <= 0:
y1_similarity = 10 - abs(self.y1_clarity - neighbor_obj.y1_clarity)
y3_similarity = 10 - abs(self.y3_aspiration - neighbor_obj.y3_aspiration)
alliance_propensity = 0
if my_trust_in_neighbor > k_social.get('alliance_form_my_trust_thresh', 7.2) and \
neighbor_trust_in_me > k_social.get('alliance_form_their_trust_thresh', 7.2):
alliance_propensity += k_social.get('alliance_trust_factor', 0.35)
if y1_similarity > k_social.get('alliance_form_y1_sim_thresh', 7.5):
alliance_propensity += k_social.get('alliance_y1_sim_factor', 0.3)
if y3_similarity > k_social.get('alliance_form_y3_sim_thresh', 7.0):
alliance_propensity += k_social.get('alliance_y3_sim_factor', 0.25)
if random.random() < alliance_propensity * k_social.get('alliance_form_base_prob', 0.12):
# --- Stricter Check: Ensure neighbor ALSO doesn't see me as a rival ---
if self.name_en not in neighbor_obj.rivals:
self.alliance_partners.add(neighbor_name)
neighbor_obj.alliance_partners.add(self.name_en) # Reciprocal
# If by some chance they were rivals before, clear that (shouldn't happen with above checks but defensive)
self.rivals.discard(neighbor_name)
neighbor_obj.rivals.discard(self.name_en)
log_msg = f"与 {neighbor_obj.name_zh} 结为联盟!"
self.active_effects_log.append(log_msg)
neighbor_obj.active_effects_log.append(f"与 {self.name_zh} 结为联盟!")
log_message("INFO", f"{self.name_zh} 与 {neighbor_obj.name_zh} 结盟", "SocialLogic")
self.social_interaction_cooldowns[cooldown_key_alliance] = params.get('alliance_cooldown',
20)
neighbor_obj.social_interaction_cooldowns[f"form_alliance_{self.name_en}"] = params.get(
'alliance_cooldown', 20)
else:
log_message("INFO",
f"{self.name_en} to {neighbor_name}: Alliance blocked, target views self as rival.",
"SocialLogic")
# B. Check for forming a RIVALRY
# Conditions: Not already allied, not already rival, not on rivalry cooldown, AND meets rivalry criteria
# Using elif to ensure this block is only considered if alliance formation didn't happen with this neighbor in this step
elif neighbor_name not in self.alliance_partners and \
neighbor_name not in self.rivals and \
self.social_interaction_cooldowns.get(cooldown_key_rivalry, 0) <= 0:
b1_competition_diff = abs(self.b1_resource - neighbor_obj.b1_resource)
is_driven_competition = (self.y2_drive > k_social.get('rival_form_self_y2_thresh', 6.5) or \
neighbor_obj.y2_drive > k_social.get('rival_form_other_y2_thresh', 6.5))
rivalry_propensity = 0
if my_trust_in_neighbor < k_social.get('rival_form_my_trust_thresh', 2.8):
rivalry_propensity += k_social.get('rival_trust_factor', 0.45)
if b1_competition_diff > k_social.get('rival_form_b1_diff_thresh', 2.5) and is_driven_competition:
rivalry_propensity += k_social.get('rival_b1_comp_factor', 0.35)
if random.random() < rivalry_propensity * k_social.get('rival_form_base_prob', 0.1):
# --- Stricter Check: Ensure neighbor ALSO doesn't see me as an ally ---
if self.name_en not in neighbor_obj.alliance_partners:
self.rivals.add(neighbor_name)
neighbor_obj.rivals.add(self.name_en) # Reciprocal
# If by some chance they were allies before, clear that
self.alliance_partners.discard(neighbor_name)
neighbor_obj.alliance_partners.discard(self.name_en)
log_msg = f"与 {neighbor_obj.name_zh} 成为对手!"
self.active_effects_log.append(log_msg)
neighbor_obj.active_effects_log.append(f"与 {self.name_zh} 成为对手!")
log_message("INFO", f"{self.name_zh} 与 {neighbor_obj.name_zh} 成为对手", "SocialLogic")
self.social_interaction_cooldowns[cooldown_key_rivalry] = params.get('rivalry_cooldown', 25)
neighbor_obj.social_interaction_cooldowns[f"form_rivalry_{self.name_en}"] = params.get(
'rivalry_cooldown', 25)
else:
log_message("INFO",
f"{self.name_en} to {neighbor_name}: Rivalry blocked, target views self as ally.",
"SocialLogic")
# C. Check for BREAKING an existing ALLIANCE
# Conditions: Currently allied, not on break alliance cooldown (optional), AND meets break conditions
elif neighbor_name in self.alliance_partners and \
self.social_interaction_cooldowns.get(cooldown_key_break_alliance, 0) <= 0: # Optional cooldown
y1_divergence = abs(self.y1_clarity - neighbor_obj.y1_clarity)
break_alliance = False
if my_trust_in_neighbor < k_social.get('alliance_break_trust_thresh', 3.5):
break_alliance = True
reason = "low trust"
elif y1_divergence > k_social.get('alliance_break_y1_diff_thresh', 6.0) and \
random.random() < k_social.get('alliance_break_prob_y_diverge', 0.04):
break_alliance = True
reason = "value divergence"
if break_alliance:
self.alliance_partners.discard(neighbor_name)
neighbor_obj.alliance_partners.discard(self.name_en) # 双向解除
# Explicitly ensure they are not rivals either after breaking alliance,
# unless conditions for rivalry are met *in a subsequent step*.
self.rivals.discard(neighbor_name) # Safety cleanup
neighbor_obj.rivals.discard(self.name_en) # Safety cleanup
log_msg = f"与 {neighbor_obj.name_zh} 解除联盟 (原因: {reason})."
self.active_effects_log.append(log_msg)
# neighbor_obj.active_effects_log.append(f"与 {self.name_zh} 的联盟已解除 (原因: {reason}).") # Avoid duplicate logs if B also processes A
log_message("INFO", f"{self.name_zh} 与 {neighbor_obj.name_zh} 解除联盟 (原因: {reason})",
"SocialLogic")
# self.social_interaction_cooldowns[cooldown_key_break_alliance] = params.get('alliance_break_cooldown', 10) # Optional
# No immediate attempt to form rivalry here; let next step's logic handle it if conditions are met.
# D. Check for ENDING an existing RIVALRY
# Conditions: Currently rivals, not on end rivalry cooldown (optional), AND meets end conditions
elif neighbor_name in self.rivals and \
self.social_interaction_cooldowns.get(cooldown_key_end_rivalry, 0) <= 0: # Optional cooldown
end_rivalry = False
if my_trust_in_neighbor > k_social.get('rival_end_trust_thresh', 6.5) and \
random.random() < k_social.get('rival_end_prob_trust_improve', 0.1):
end_rivalry = True
reason = "improved trust"
# Could add other conditions, e.g., common powerful enemy, mutual benefit opportunity
if end_rivalry:
self.rivals.discard(neighbor_name)
neighbor_obj.rivals.discard(self.name_en) # 双向解除
# Explicitly ensure they are not allies either after ending rivalry,
# unless conditions for alliance are met *in a subsequent step*.
self.alliance_partners.discard(neighbor_name) # Safety cleanup
neighbor_obj.alliance_partners.discard(self.name_en) # Safety cleanup
log_msg = f"与 {neighbor_obj.name_zh} 结束敌对 (原因: {reason})."
self.active_effects_log.append(log_msg)
# neighbor_obj.active_effects_log.append(f"与 {self.name_zh} 的敌对已结束 (原因: {reason}).")
log_message("INFO", f"{self.name_zh} 与 {neighbor_obj.name_zh} 结束敌对 (原因: {reason})",
"SocialLogic")
# self.social_interaction_cooldowns[cooldown_key_end_rivalry] = params.get('rivalry_end_cooldown', 15) # Optional
# No immediate attempt to form alliance here.
# End of loop through neighbors
### END MODIFIED ###
def decide_community_actions(self, params, all_states_objects_dict, community_projects):
k_comm = params.get('coefficients', {}).get('community_actions', {})
if self.y2_drive > k_comm.get('initiate_project_y2_thresh', 7.0) and self.s2_reputation > k_comm.get(
'initiate_project_s2_thresh', 5.0) and random.random() < k_comm.get('initiate_project_prob', 0.01):
project_id = str(uuid.uuid4())[:8];
proj_name = f"公共设施改善-{project_id}"
req_b1 = self.b1_resource * k_comm.get('project_b1_cost_ratio_self', 0.3);
req_b1_total = req_b1 * 3
new_project = CommunityProject(project_id, proj_name, req_b1_total,
required_h2=k_comm.get('project_req_h2', 4.0),
duration=k_comm.get('project_duration', 10), creator_en=self.name_en,
target_participants=k_comm.get('project_target_participants', 3),
reward_type='b2_reduction',
reward_value=k_comm.get('project_b2_reward_val', 0.8))
if self.b1_resource >= req_b1:
self.b1_resource -= req_b1;
new_project.contributed_b1 += req_b1;
new_project.participants = {self.name_en}
community_projects[project_id] = new_project;
self.active_effects_log.append(f"发起社区项目'{proj_name}', 贡献B1: {req_b1:.2f}")
log_message("INFO", f"{self.name_zh} 发起社区项目'{proj_name}'", "CommunityAction")
else:
self.active_effects_log.append(f"想发起项目'{proj_name}'但B1不足")
for proj_id, project in community_projects.items():
if project.status == "pending" and self.name_en not in project.participants and len(
project.participants) < project.target_participants:
trust_in_creator = self.trust_levels.get(project.creator_en, 3.0)
perceived_value_vs_cost_ratio = (project.reward_value / (
project.required_b1_total / project.target_participants + 0.1)) * scale_value(
self.y1_clarity, 0, 10, 0.5, 1.2)
can_afford_contribution = self.b1_resource > (
project.required_b1_total / project.target_participants) * 1.2;
join_propensity = 0
if trust_in_creator > k_comm.get('join_project_trust_thresh', 5.0): join_propensity += k_comm.get(
'join_trust_factor', 0.3)
if perceived_value_vs_cost_ratio > k_comm.get('join_project_value_ratio_thresh',
1.5): join_propensity += k_comm.get('join_value_factor',
0.4)
if can_afford_contribution: join_propensity += k_comm.get('join_afford_factor', 0.2)
if random.random() < join_propensity * k_comm.get('join_project_base_prob', 0.1):
my_contribution = project.required_b1_total / project.target_participants
if self.b1_resource >= my_contribution:
self.b1_resource -= my_contribution
if project.add_participant(self.name_en, my_contribution):
self.contributed_projects[proj_id] = my_contribution
else:
self.b1_resource += my_contribution
break
def evolve(self, params, all_states_objects_dict, active_event_effects_on_self, global_env_factors, current_step,
community_projects):
self.update_perception(params)
coeffs = params.get('coefficients', {});
noise_level = params.get('noise_level', 0.05);
lr = params.get('learning_rate', 0.1)
b1_acq_mod = global_env_factors.get('b1_acq_mod', 1.0);
b2_base_inc = global_env_factors.get('b2_base_inc', 0.0) # Ensure 'b2_base_inc' is correct key
current_risk_outcome_this_step = 0.0;
risk_project_b1_change = 0.0;
risk_project_b2_change = 0.0
self.manage_social_relations(params, all_states_objects_dict, current_step)
self.decide_community_actions(params, all_states_objects_dict, community_projects)
h3_risk_attempt_thresh = params.get('h3_risk_attempt_threshold', 4.0);
y2_risk_attempt_thresh = params.get('y2_risk_attempt_threshold', 3.0)
perceived_can_invest = self.perceived_b1_resource > params.get('risk_min_perceived_b1_to_attempt', 1.0)
risk_attempt_probability = sigmoid(self.h3_risk_appetite - h3_risk_attempt_thresh, k=0.8, x0=0) * sigmoid(
self.y2_drive - y2_risk_attempt_thresh, k=0.7, x0=0) * scale_value(self.s2_reputation, 0, 10, 1.1, 0.8) * (
0.5 + 0.5 * scale_value(self.mood, -1, 1, 0.8, 1.2))
if random.random() < risk_attempt_probability and perceived_can_invest:
b1_invest_ratio_base = scale_value(self.h3_risk_appetite, 0, 10, params.get('risk_invest_ratio_min', 0.03),
params.get('risk_invest_ratio_max', 0.12))
b1_invest_ratio_modifier = (
0.6 + 0.2 * sigmoid(self.y1_clarity, k=1, x0=5) + 0.2 * sigmoid(self.s1_trustworthiness, k=1,
x0=6))
potential_investment_amount = self.perceived_b1_resource * np.clip(
b1_invest_ratio_base * b1_invest_ratio_modifier, 0, params.get('risk_max_invest_cap_ratio', 0.30))
b1_invested = min(potential_investment_amount, self.b1_resource)
if b1_invested > 0.01:
k_risk = coeffs.get('risk_project', {});
potential_R_factor = k_risk.get('potential_R_base', 0) + k_risk.get('potential_R_h2',
0) * self.h2_innovation + k_risk.get(
'potential_R_y1', 0) * self.y1_clarity + k_risk.get('potential_R_s2', 0) * self.s2_reputation
inherent_risk_L_factor = k_risk.get('inherent_L_base', 0) + k_risk.get('inherent_L_h3',
0) * self.h3_risk_appetite + k_risk.get(
'inherent_L_b2', 0) * self.b2_limitation - k_risk.get('reduction_s1', 0) * self.s1_trustworthiness
mean_outcome = potential_R_factor - inherent_risk_L_factor * k_risk.get('L_to_mean_factor', 0.6);
std_dev_outcome = max(k_risk.get('min_std_dev', 0.01),
inherent_risk_L_factor * k_risk.get('L_to_std_factor', 0.7))
actual_return_factor_on_investment = random.normalvariate(mean_outcome, std_dev_outcome);
current_risk_outcome_this_step = actual_return_factor_on_investment
b1_investment_scale_factor = sigmoid(
self.b1_resource * params.get('risk_invest_diminishing_threshold_factor', 0.1) - b1_invested,
k=-params.get('risk_invest_diminishing_k', 0.1), x0=0)
effective_return_factor = actual_return_factor_on_investment * (0.5 + 0.5 * b1_investment_scale_factor);
risk_project_b1_change = b1_invested * effective_return_factor * b1_acq_mod
if current_risk_outcome_this_step < params.get('risk_failure_threshold_for_b2',
-0.1): risk_project_b2_change = k_risk.get(
'b2_from_major_failure', 0) * abs(current_risk_outcome_this_step) * (b1_invested / max(0.1,
self.b1_resource if self.b1_resource > 0 else 0.1))
self.active_effects_log.append(
f"风险项目: 计划投(基于感知) {potential_investment_amount:.2f}, 实际投 {b1_invested:.2f}, 回报因子 {current_risk_outcome_this_step:.2f} (有效 {effective_return_factor:.2f}), B1变 {risk_project_b1_change:.2f}, B2变 {risk_project_b2_change:.2f}")
else:
self.active_effects_log.append(f"风险项目: 感知B1不足或实际B1不足以支持投资。")
else:
if not perceived_can_invest: self.active_effects_log.append(
f"风险项目: 因感知B1({self.perceived_b1_resource:.2f})不足而未尝试。")
self.update_mood(params, current_risk_outcome_this_step)
avg_b1_others, avg_h1_others = None, None
all_b1s = [obj.b1_resource for name_other, obj in all_states_objects_dict.items() if
name_other != self.name_en and obj is not None]
if all_b1s: avg_b1_others = np.mean(all_b1s);
all_h1s = [obj.h1_possibilities for name_other, obj in all_states_objects_dict.items() if
name_other != self.name_en and obj is not None]
if all_h1s: avg_h1_others = np.mean(all_h1s)
neighbor_effects = self._calculate_neighbor_effects(params, all_states_objects_dict)
deltas = {'b1_resource': self._calculate_delta_b1(coeffs.get('b1_resource', {}), params, avg_b1_others,
neighbor_effects.get('b1_resource', 0),
risk_project_b1_change),
'b2_limitation': self._calculate_delta_b2(coeffs.get('b2_limitation', {}), params,
neighbor_effects.get('b2_limitation', 0),
risk_project_b2_change) + b2_base_inc, # Use b2_base_inc
'y1_clarity': self._calculate_delta_y1(coeffs.get('y1_clarity', {}), params,
neighbor_effects.get('y1_clarity', 0),
current_risk_outcome_this_step),
'y2_drive': self._calculate_delta_y2(coeffs.get('y2_drive', {}), params,
neighbor_effects.get('y2_drive', 0),
current_risk_outcome_this_step),
'y3_aspiration': self._calculate_delta_y3(coeffs.get('y3_aspiration', {}), params,
neighbor_effects.get('y3_aspiration', 0), avg_b1_others,
avg_h1_others),
'h1_possibilities': self._calculate_delta_h1(coeffs.get('h1_possibilities', {}), params,
neighbor_effects.get('h1_possibilities', 0)),
'h2_innovation': self._calculate_delta_h2(coeffs.get('h2_innovation', {}), params,
neighbor_effects.get('h2_innovation', 0)),
'h3_risk_appetite': self._calculate_delta_h3(coeffs.get('h3_risk_appetite', {}), params,
neighbor_effects.get('h3_risk_appetite', 0),
current_risk_outcome_this_step),
's1_trustworthiness': self._calculate_delta_s1_trustworthiness(coeffs.get('s1_trustworthiness', {}),
params, neighbor_effects.get(
's1_trustworthiness', 0), current_risk_outcome_this_step),
's2_reputation': self._calculate_delta_s2_reputation(coeffs.get('s2_reputation', {}), params,
neighbor_effects.get('s2_reputation', 0),
current_risk_outcome_this_step), }
internal_logs_this_step = self.active_effects_log[:]
self.active_effects_log.clear()
for key in DIM_KEYS:
current_val = getattr(self, key);
total_delta_from_sources = deltas.get(key, 0);
noise_val = random.uniform(-noise_level, noise_level)
effective_delta = total_delta_from_sources
if key == 'b1_resource' and effective_delta > 0: effective_delta *= b1_acq_mod
effective_delta += noise_val;
new_val_before_event = current_val + effective_delta * lr;
final_val_after_event = new_val_before_event
if key in active_event_effects_on_self:
for event_eff in active_event_effects_on_self.get(key, []):
eff_val = event_eff.get('val', 0);
eff_type = event_eff.get('type')
resilience_score = (self.y1_clarity / 10) * params.get('event_resilience_y1_factor', 0.6) + (
self.b1_resource / 10) * params.get('event_resilience_b1_factor', 0.4)
resilience_score = np.clip(resilience_score, 0.1, 1.0);
actual_eff_val = eff_val
if eff_val < 0:
actual_eff_val = eff_val / (
resilience_score * params.get('event_neg_resilience_mult', 1.5) + 0.5)
else:
actual_eff_val = eff_val * (
resilience_score * params.get('event_pos_resilience_mult', 0.8) + 0.6)
if eff_type == 'add_abs':
final_val_after_event += actual_eff_val
elif eff_type == 'set_abs':
final_val_after_event = actual_eff_val
elif eff_type == 'multiply_abs':
if actual_eff_val < 1.0 and eff_val < 1.0:
actual_eff_val = 1.0 - (1.0 - actual_eff_val) / (resilience_score + 0.1)
elif actual_eff_val > 1.0 and eff_val > 1.0:
actual_eff_val = 1.0 + (actual_eff_val - 1.0) * (resilience_score + 0.1)
final_val_after_event *= actual_eff_val
final_val_after_event = np.clip(final_val_after_event, 0, 10)
if key == 'b1_resource' and final_val_after_event > params.get('b1_practical_max', 9.7):
overflow = final_val_after_event - params.get('b1_practical_max', 9.7);
final_val_after_event = params.get('b1_practical_max', 9.7)
s2_coeffs_for_overflow = coeffs.get('s2_reputation', {})
self.s2_reputation += overflow * s2_coeffs_for_overflow.get('from_b1_overflow', 0.05);
self.s2_reputation = np.clip(self.s2_reputation, 0, 10)
if overflow > 1e-3: self.active_effects_log.append(f"B1溢出 {overflow:.2f} -> S2增加")
setattr(self, key, final_val_after_event)
self.last_risk_outcome_factor = current_risk_outcome_this_step
self.active_effects_log.extend(internal_logs_this_step)
def record_history(self, coord_type, wb, wy, wh, max_history=50):
coords = self.get_coords_for_plot(coord_type, wb, wy, wh);
if len(self.history) >= max_history: self.history.pop(0)
self.history.append(coords)
def clear_history(self):
self.history = []
def to_dict(self):
data = {key: getattr(self, key) for key in DIM_KEYS}
data.update(
{'name_zh': self.name_zh, 'name_en': self.name_en, 'history': self.history, 'neighbors': self.neighbors,
'trust_levels': dict(self.trust_levels), 'last_risk_outcome_factor': self.last_risk_outcome_factor,
'alliance_partners': list(self.alliance_partners), 'rivals': list(self.rivals),
'perceived_b1_resource': self.perceived_b1_resource,
'perceived_h1_possibilities': self.perceived_h1_possibilities,
'perception_accuracy': self.perception_accuracy, 'mood': self.mood,
'community_norm_conformity': self.community_norm_conformity,
'contributed_projects': self.contributed_projects, })
return data
@classmethod
def from_dict(cls, data):
dim_data = {key: data.get(key, 0 if 'limitation' not in key else 5) for key in DIM_KEYS}
obj = cls(data.get('name_zh', '未知状态'), data.get('name_en', f'Unknown_{random.randint(1000, 9999)}'),
dim_data['b1_resource'], dim_data['b2_limitation'], dim_data['y1_clarity'], dim_data['y2_drive'],
dim_data['y3_aspiration'], dim_data['h1_possibilities'], dim_data['h2_innovation'],
dim_data['h3_risk_appetite'],
dim_data.get('s1_trustworthiness', 5.0), dim_data.get('s2_reputation', 3.0))
obj.history = data.get('history', []);
obj.neighbors = data.get('neighbors', [])
obj.trust_levels = defaultdict(lambda: 5.0, data.get('trust_levels', {}))
obj.last_risk_outcome_factor = data.get('last_risk_outcome_factor', 0)
obj.alliance_partners = set(data.get('alliance_partners', []));
obj.rivals = set(data.get('rivals', []))
obj.perceived_b1_resource = data.get('perceived_b1_resource', obj.b1_resource)
obj.perceived_h1_possibilities = data.get('perceived_h1_possibilities', obj.h1_possibilities)
obj.perception_accuracy = data.get('perception_accuracy', scale_value(obj.y1_clarity, 0, 10, 0.5, 1.0))
obj.mood = data.get('mood', 0)
obj.community_norm_conformity = data.get('community_norm_conformity', random.uniform(0.3, 0.7))
obj.contributed_projects = data.get('contributed_projects', {})
return obj
def __repr__(self):
return f"<WorldState: {self.get_display_name()}>"
# --- EventManager and Event classes (GM4.5.6) ---
class Event: