-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1478 lines (1237 loc) · 54.7 KB
/
app.py
File metadata and controls
1478 lines (1237 loc) · 54.7 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
"""
Streamlit 主入口 - 多灾难点 + 单/多路径 + GA + AI Allocation Predictor + LLM智能体模拟
- 全局容量共享(多灾难点)
- 所有方法都执行:可达性 + 容量 + 守恒 repair
- 正确重叠率 overlap_rate(edge 计数法)
运行:
streamlit run app.py --server.port 8502
"""
import time
import random
from dataclasses import dataclass
from typing import Dict, List, Any, Tuple, Optional, Any as AnyType
import numpy as np
import pandas as pd
import networkx as nx
import streamlit as st
import folium
from streamlit_folium import st_folium
# ---------------------------------------------------------
# 导入项目模块(缺失则兜底)
# ---------------------------------------------------------
try:
from web.layout import setup_page_config, apply_custom_styles, create_header, create_footer
from web.layout import create_sidebar_header, create_sidebar_footer
except Exception:
def setup_page_config():
st.set_page_config(page_title="智能应急疏散模拟系统", layout="wide", initial_sidebar_state="expanded")
def apply_custom_styles():
pass
def create_header():
st.title("🏃♂️ 智能应急疏散模拟系统")
def create_footer():
st.markdown("---")
st.caption("Demo")
def create_sidebar_header():
st.sidebar.markdown("### 🎯 疏散策略配置")
def create_sidebar_footer():
st.sidebar.markdown("---")
st.sidebar.info("操作指南:选灾难点/避难点 → 运行 → 看指标")
try:
from utils.data_loader import load_graph
except Exception:
load_graph = None
try:
from utils.geo_utils import snap_to_graph, get_node_latlon
except Exception:
def snap_to_graph(G, lat: float, lon: float) -> int:
best = None
bestd = 1e18
for n, data in G.nodes(data=True):
y = data.get("y", 0.0)
x = data.get("x", 0.0)
d = (y - lat) ** 2 + (x - lon) ** 2
if d < bestd:
bestd, best = d, n
return int(best)
def get_node_latlon(G, node_id: int) -> Tuple[float, float]:
data = G.nodes[node_id]
return float(data.get("y", 0.0)), float(data.get("x", 0.0))
try:
from utils.visualization import build_base_map, add_node_marker, add_path_to_map, add_agents_to_map
except Exception:
def build_base_map(G):
nodes = list(G.nodes())
if nodes:
lat, lon = get_node_latlon(G, nodes[0])
else:
lat, lon = 39.968056, 116.305833
return folium.Map(location=(lat, lon), zoom_start=16, tiles="openstreetmap")
def add_node_marker(G, fmap, node_id: int, color: str, text: str, icon: str = "info-sign"):
lat, lon = get_node_latlon(G, node_id)
folium.Marker(location=(lat, lon), popup=text, icon=folium.Icon(color=color, icon=icon)).add_to(fmap)
def add_path_to_map(G, fmap, path: List[int], color="blue", weight=5, popup_text=None, opacity=0.8):
coords = [get_node_latlon(G, n) for n in path]
folium.PolyLine(locations=coords, color=color, weight=weight, opacity=opacity, popup=popup_text).add_to(fmap)
def add_agents_to_map(G, fmap, agents: List[Dict[str, Any]]):
pass
try:
from planning.multi_objective import ga_optimize_allocation, precompute_paths
except Exception:
ga_optimize_allocation = None
precompute_paths = None
# 导入智能体模拟模块
try:
from simulation.llm_agent import LLMAgentSimulator
LLM_AVAILABLE = True
except Exception:
LLMAgentSimulator = None
LLM_AVAILABLE = False
print("警告:LLM智能体模拟模块导入失败")
try:
from config import (
DEFAULT_TOTAL_PEOPLE,
DEFAULT_SHELTER_CAPACITY,
COLOR_SCHEME,
LAYOUT_CONFIG,
FOLIUM_COLORS,
LLM_CONFIG,
AGENT_GENERATION_CONFIG
)
except Exception:
DEFAULT_TOTAL_PEOPLE = 1000
DEFAULT_SHELTER_CAPACITY = 200
COLOR_SCHEME = {
"disaster": "red",
"shelter": "green",
"agent": "blue",
"agent_child": "#339AF0",
"agent_adult": "#FF922B",
"agent_elderly": "#845EF7",
"agent_panicked": "#FF6B6B",
"agent_nervous": "#FFD93D",
"agent_calm": "#6BCF7F",
"path_single": "blue",
"path_multi_1": "purple",
"path_multi_2": "orange",
"path_multi_3": "darkred",
"risk_edge": "red",
"risk_edge_mid": "orange",
"simulation_bg": "#F8F9FA",
"panel_bg": "#FFFFFF",
}
FOLIUM_COLORS = [
"red", "blue", "green", "purple", "orange", "darkred",
"lightred", "beige", "darkblue", "darkgreen", "cadetblue",
"darkpurple", "white", "pink", "lightblue", "lightgreen",
"gray", "black", "lightgray"
]
LAYOUT_CONFIG = {"map_height": 600}
LLM_CONFIG = {}
AGENT_GENERATION_CONFIG = {}
# ---------------------------------------------------------
# ✅ 兼容 GA 返回值
# ---------------------------------------------------------
def safe_unpack_ga_result(res: AnyType) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]:
if res is None:
return [], {}
if isinstance(res, tuple):
best_paths = res[0] if len(res) >= 1 else []
best_metrics = res[1] if len(res) >= 2 and isinstance(res[1], dict) else {}
return best_paths or [], best_metrics or {}
if isinstance(res, dict):
bp = res.get("best_paths", res.get("paths", []))
bm = res.get("best_metrics", res.get("metrics", {}))
return bp or [], bm or {}
return [], {}
# ---------------------------------------------------------
# ✅ 正确重叠率:edge 计数法(修复你一直 0 的 bug)
# ---------------------------------------------------------
from collections import Counter
def _path_edge_set_undirected(path: List[int]) -> set:
s = set()
if not path or len(path) < 2:
return s
for u, v in zip(path[:-1], path[1:]):
s.add((min(u, v), max(u, v)))
return s
def enrich_path_infos_with_overlap(path_infos: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
edge_sets = [_path_edge_set_undirected(info.get("path", [])) for info in path_infos]
cnt = Counter()
for es in edge_sets:
for e in es:
cnt[e] += 1
for info, es in zip(path_infos, edge_sets):
info["edge_count"] = int(len(es))
if len(es) == 0:
info["shared_edge_count"] = 0
info["overlap_rate"] = 0.0
else:
shared = sum(1 for e in es if cnt[e] > 1)
info["shared_edge_count"] = int(shared)
info["overlap_rate"] = float(shared / max(1, len(es)))
return path_infos
# ---------------------------------------------------------
# 可达性判断
# ---------------------------------------------------------
def is_reachable_path(info: Dict[str, Any]) -> bool:
path = info.get("path", [])
L = info.get("length", None)
if path is None or len(path) < 2:
return False
if L is None:
return False
try:
return np.isfinite(float(L)) and float(L) > 0 and bool(info.get("reachable", True))
except Exception:
return False
# ---------------------------------------------------------
# ✅ 统一 repair:可达性 + 容量 + 守恒(支持容量不足 leftover)
# (所有策略都必须走它)
# ---------------------------------------------------------
def repair_allocation_with_capacity_and_reachability(
path_infos: List[Dict[str, Any]],
alloc: List[int],
total_people: int,
shelter_caps: Dict[int, int],
redistribute: str = "heuristic", # "heuristic" or "remaining_capacity"
p: float = 1.3,
overlap_penalty: float = 0.6,
) -> Tuple[List[int], int]:
k = len(path_infos)
if k == 0:
return [], int(total_people)
a = np.array([max(0, int(x)) for x in alloc], dtype=np.int64)
if a.shape[0] != k:
a = np.resize(a, k)
a = np.maximum(a, 0)
reachable = np.array([is_reachable_path(info) for info in path_infos], dtype=bool)
caps = np.array([int(shelter_caps.get(int(info["target"]), DEFAULT_SHELTER_CAPACITY)) for info in path_infos],
dtype=np.int64)
caps[~reachable] = 0
# clamp
a[~reachable] = 0
a = np.minimum(a, caps)
assigned = int(a.sum())
leftover = int(total_people - assigned)
# 若超配(理论上少见,但防御)
if leftover < 0:
need = -leftover
while need > 0 and int(a.sum()) > total_people:
j = int(np.argmax(a))
if a[j] <= 0:
break
a[j] -= 1
need -= 1
assigned = int(a.sum())
leftover = int(total_people - assigned)
# redistribute
if leftover > 0:
space = caps - a
if int(space.sum()) > 0:
if redistribute == "remaining_capacity":
w = space.astype(np.float64)
else:
# cap/(length^p) * (1 - overlap_penalty*overlap)
w = []
for i, info in enumerate(path_infos):
if space[i] <= 0:
w.append(0.0)
continue
L = float(info.get("length", 1e9))
L = max(1.0, L) if np.isfinite(L) else 1e9
cap = float(caps[i])
ov = float(info.get("overlap_rate", 0.0))
ov_factor = max(0.05, 1.0 - overlap_penalty * ov)
w.append((cap / (L ** p)) * ov_factor)
w = np.array(w, dtype=np.float64)
if w.sum() <= 1e-12:
w = space.astype(np.float64)
w = w / max(1e-12, w.sum())
add = np.floor(w * leftover).astype(np.int64)
add = np.minimum(add, space)
a += add
leftover -= int(add.sum())
while leftover > 0 and int((caps - a).sum()) > 0:
j = int(np.argmax(caps - a))
if caps[j] - a[j] <= 0:
break
a[j] += 1
leftover -= 1
return a.astype(int).tolist(), int(max(0, leftover))
# ---------------------------------------------------------
# 生成 path_infos(含不可达)
# ---------------------------------------------------------
def make_path_infos(G: nx.Graph, source: int, shelters: List[int]) -> List[Dict[str, Any]]:
infos: List[Dict[str, Any]] = []
if precompute_paths is not None:
infos = precompute_paths(G, source, shelters) # 模块版包含 reachable/overlap
# 保险:再 enrich 一次(不破坏)
return enrich_path_infos_with_overlap(infos)
for t in shelters:
try:
path = nx.shortest_path(G, source, t, weight="length")
length = nx.shortest_path_length(G, source, t, weight="length")
reachable = bool(path) and len(path) >= 2 and np.isfinite(float(length))
except Exception:
path = []
length = float("inf")
reachable = False
infos.append({"target": int(t), "path": path, "length": float(length), "reachable": bool(reachable)})
return enrich_path_infos_with_overlap(infos)
# ---------------------------------------------------------
# 启发式 allocation(带 overlap 惩罚)
# ---------------------------------------------------------
def heuristic_allocation(
path_infos: List[Dict[str, Any]],
total_people: int,
shelter_caps: Dict[int, int],
p: float = 1.3,
overlap_penalty: float = 0.6,
) -> Tuple[List[int], int]:
w = []
for info in path_infos:
if not is_reachable_path(info):
w.append(0.0)
continue
L = max(1.0, float(info.get("length", 1e9)))
cap = float(shelter_caps.get(int(info["target"]), DEFAULT_SHELTER_CAPACITY))
ov = float(info.get("overlap_rate", 0.0))
ov_factor = max(0.05, 1.0 - overlap_penalty * ov)
w.append((cap / (L ** p)) * ov_factor)
w = np.array(w, dtype=np.float64)
if w.sum() <= 1e-12:
alloc0 = [0] * len(path_infos)
return alloc0, int(total_people)
w = w / w.sum()
alloc = np.floor(w * total_people).astype(int).tolist()
diff = int(total_people - sum(alloc))
while diff > 0:
alloc[int(np.argmax(w))] += 1
diff -= 1
return repair_allocation_with_capacity_and_reachability(
path_infos, alloc, total_people, shelter_caps, redistribute="heuristic", p=p, overlap_penalty=overlap_penalty
)
# ---------------------------------------------------------
# AI Predictor(GA 当老师)
# ---------------------------------------------------------
FEATURE_NAMES = [
"bias",
"log1p(length)",
"overlap_rate",
"log1p(edge_count)",
"log1p(capacity)",
"overlap*log1p(length)",
"reachable_flag"
]
def build_path_feature_matrix(path_infos: List[Dict[str, Any]], capacities: Dict[int, int]) -> np.ndarray:
feats = []
for info in path_infos:
L = float(info.get("length", 0.0))
ov = float(info.get("overlap_rate", 0.0))
ec = float(info.get("edge_count", max(0, len(info.get("path", [])) - 1)))
cap = float(capacities.get(int(info["target"]), DEFAULT_SHELTER_CAPACITY))
reachable = 1.0 if is_reachable_path(info) else 0.0
feats.append([
1.0,
np.log1p(max(0.0, L if np.isfinite(L) else 1e9)),
ov,
np.log1p(max(0.0, ec)),
np.log1p(max(0.0, cap)),
ov * np.log1p(max(0.0, L if np.isfinite(L) else 1e9)),
reachable,
])
return np.asarray(feats, dtype=np.float32)
def softmax(x: np.ndarray) -> np.ndarray:
x = x - np.max(x)
e = np.exp(x)
s = np.sum(e)
return e / max(1e-12, s)
@dataclass
class AllocationPredictorModel:
w: np.ndarray
loss_history: List[float]
def predict_allocation_from_model(
path_infos: List[Dict[str, Any]],
total_people: int,
shelter_caps: Dict[int, int],
model: AllocationPredictorModel
) -> Tuple[List[int], int]:
X = build_path_feature_matrix(path_infos, shelter_caps)
scores = X @ model.w
shares = softmax(scores)
alloc = np.round(shares * total_people).astype(int).tolist()
# 统一 repair(保证:不可达/容量/守恒)
return repair_allocation_with_capacity_and_reachability(
path_infos, alloc, total_people, shelter_caps, redistribute="heuristic"
)
def train_allocation_predictor(
teacher_samples: List[Tuple[np.ndarray, np.ndarray]],
lr: float = 0.2,
epochs: int = 120,
l2: float = 1e-3
) -> AllocationPredictorModel:
if not teacher_samples:
w = np.zeros((len(FEATURE_NAMES),), dtype=np.float32)
return AllocationPredictorModel(w=w, loss_history=[0.0])
d = teacher_samples[0][0].shape[1]
w = np.zeros((d,), dtype=np.float32)
loss_hist = []
for _ in range(epochs):
total_loss = 0.0
grad = np.zeros_like(w)
for X, y_share in teacher_samples:
scores = X @ w
p = softmax(scores)
diff = (p - y_share)
loss = float(np.mean(diff ** 2))
total_loss += loss
# softmax Jacobian * MSE grad(轻量够用)
J = np.diag(p) - np.outer(p, p)
dp = (2.0 / len(p)) * diff
ds = J @ dp
grad += X.T @ ds
total_loss /= max(1, len(teacher_samples))
grad = grad / max(1, len(teacher_samples)) + l2 * w
w -= lr * grad.astype(np.float32)
loss_hist.append(total_loss)
if len(loss_hist) > 20 and abs(loss_hist[-1] - loss_hist[-20]) < 1e-6:
break
return AllocationPredictorModel(w=w, loss_history=loss_hist)
# ---------------------------------------------------------
# 多灾难点评估(全局拥堵/距离)
# ---------------------------------------------------------
def evaluate_multi_disaster(per_plans: List[Dict[str, Any]]) -> Dict[str, float]:
edge_loads = {}
total_distance = 0.0
makespan = 0.0
for plan in per_plans:
path_infos = plan["path_infos"]
allocation = plan["allocation"]
for alloc_n, info in zip(allocation, path_infos):
n = int(alloc_n)
if n <= 0:
continue
if not is_reachable_path(info):
continue
L = float(info["length"])
if not np.isfinite(L):
continue
total_distance += n * L
makespan = max(makespan, L)
for u, v in zip(info["path"][:-1], info["path"][1:]):
key = (min(u, v), max(u, v))
edge_loads[key] = edge_loads.get(key, 0) + n
max_cong = float(max(edge_loads.values())) if edge_loads else 0.0
return {
"makespan": float(makespan),
"total_distance": float(total_distance),
"max_congestion": float(max_cong),
}
# ---------------------------------------------------------
# 输出表格:每个灾难点(所有策略都用)
# ---------------------------------------------------------
def build_detail_table(
G: nx.Graph,
source: int,
N: int,
shelters: List[int],
path_infos: List[Dict[str, Any]],
alloc: List[int],
caps_used: Dict[int, int],
leftover: int,
method: str,
) -> pd.DataFrame:
rows = []
for idx, (info, n) in enumerate(zip(path_infos, alloc), start=1):
t = int(info["target"])
L = float(info.get("length", float("inf")))
ov = float(info.get("overlap_rate", 0.0))
ec = int(info.get("edge_count", 0))
shared = int(info.get("shared_edge_count", 0))
cap = int(caps_used.get(t, DEFAULT_SHELTER_CAPACITY))
reachable = bool(is_reachable_path(info))
try:
lat, lon = get_node_latlon(G, t)
coord = f"{lat:.6f},{lon:.6f}"
except Exception:
coord = ""
rows.append({
"方法": method,
"灾难点": int(source),
"总人数N": int(N),
"未安置人数": int(leftover),
"路径编号": int(idx),
"避难点节点": int(t),
"可达": "✅" if reachable else "❌",
"避难点容量(本轮可用)": int(cap),
"分配人数": int(n),
"占比": float(n) / max(1, int(N)),
"路径长度(m)": float(L) if np.isfinite(L) else np.nan,
"边数": int(ec),
"共享边数": int(shared),
"重叠率": float(ov),
"人公里(people-km)": (float(n) * float(L) / 1000.0) if (reachable and np.isfinite(L)) else 0.0,
"避难点坐标": coord,
})
df = pd.DataFrame(rows)
df = df.sort_values(["分配人数", "路径长度(m)"], ascending=[False, True], na_position="last").reset_index(drop=True)
return df
# ---------------------------------------------------------
# 智能体模拟函数
# ---------------------------------------------------------
def run_llm_agent_simulation():
"""运行LLM智能体模拟"""
if not LLM_AVAILABLE or LLMAgentSimulator is None:
st.error("LLM智能体模块不可用,请检查依赖安装和配置")
return
shelters = [int(x) for x in st.session_state.shelter_nodes]
disasters = [int(x) for x in st.session_state.disaster_nodes]
if not disasters or not shelters:
st.error("请先设置灾难点和避难点")
return
# 初始化模拟器
simulator = LLMAgentSimulator(G, LLM_CONFIG)
# 生成智能体
total_people = sum(int(v) for v in st.session_state.disaster_people.values())
agent_count = min(st.session_state.agent_count, total_people) if total_people > 0 else st.session_state.agent_count
agents = simulator.generate_random_agents(
num_agents=agent_count,
start_nodes=disasters,
shelter_nodes=shelters,
config=AGENT_GENERATION_CONFIG
)
st.session_state.llm_simulator = simulator
st.session_state.simulation_agents = agents
st.session_state.simulation_steps = []
st.session_state.current_simulation_step = 0
st.session_state.simulation_edge_congestion = {}
# 运行模拟
progress_bar = st.progress(0)
status_text = st.empty()
results_container = st.container()
try:
for step in range(st.session_state.max_simulation_steps):
status_text.text(f"模拟步骤: {step + 1}/{st.session_state.max_simulation_steps}")
progress_bar.progress((step + 1) / st.session_state.max_simulation_steps)
# 运行一步模拟
step_result = simulator.run_simulation_step(
current_step=step,
edge_congestion=st.session_state.simulation_edge_congestion
)
st.session_state.simulation_steps.append(step_result)
st.session_state.current_simulation_step = step
# 检查是否所有智能体都已到达
if step_result.get("active_agents", 0) == 0:
status_text.text(f"模拟完成!所有智能体已到达避难所。")
break
time.sleep(0.1) # 稍微延迟以便观察
# 计算统计信息
st.session_state.agent_statistics = simulator.get_agent_statistics()
# 准备结果
st.session_state.simulation_results = {
"total_steps": len(st.session_state.simulation_steps),
"statistics": st.session_state.agent_statistics,
"steps": st.session_state.simulation_steps
}
with results_container:
display_simulation_results()
except Exception as e:
st.error(f"模拟运行失败: {str(e)}")
finally:
st.session_state.is_simulation_running = False
def display_simulation_results():
"""显示智能体模拟结果"""
if not st.session_state.simulation_results:
return
stats = st.session_state.agent_statistics or {}
st.markdown("### 📊 智能体模拟结果")
# 总体统计
cols = st.columns(4)
with cols[0]:
st.metric("总智能体数", stats.get("total_agents", 0))
with cols[1]:
st.metric("已到达数", stats.get("arrived_agents", 0))
with cols[2]:
st.metric("到达率", f"{stats.get('arrival_rate', 0) * 100:.1f}%")
with cols[3]:
st.metric("平均步数", f"{stats.get('avg_steps', 0):.1f}")
# 详细统计
if stats.get("age_statistics"):
st.markdown("#### 按年龄组统计")
age_stats = stats.get("age_statistics", {})
age_df = pd.DataFrame.from_dict(age_stats, orient='index')
st.dataframe(age_df, use_container_width=True)
if stats.get("panic_statistics"):
st.markdown("#### 按恐慌程度统计")
panic_stats = stats.get("panic_statistics", {})
panic_df = pd.DataFrame.from_dict(panic_stats, orient='index')
st.dataframe(panic_df, use_container_width=True)
# 模拟步骤可视化
if st.session_state.simulation_steps:
import plotly.graph_objects as go
steps_df = pd.DataFrame(st.session_state.simulation_steps)
fig = go.Figure()
fig.add_trace(go.Scatter(
x=steps_df["step"],
y=steps_df["active_agents"],
mode='lines+markers',
name='活跃智能体数'
))
fig.add_trace(go.Scatter(
x=steps_df["step"],
y=steps_df["arrived_agents"],
mode='lines+markers',
name='已到达智能体数'
))
fig.update_layout(
title="模拟进度",
xaxis_title="步骤",
yaxis_title="智能体数",
height=300,
template="plotly_white"
)
st.plotly_chart(fig, use_container_width=True)
# ---------------------------------------------------------
# 页面初始化
# ---------------------------------------------------------
setup_page_config()
apply_custom_styles()
@st.cache_data(show_spinner=True)
def get_graph_cached():
if load_graph is None:
raise RuntimeError("utils.data_loader.load_graph 不可用,请确认你的项目结构。")
return load_graph()
G = get_graph_cached()
create_header()
# ---------------------------------------------------------
# Session State
# ---------------------------------------------------------
def ss_init():
defaults = {
"disaster_nodes": [],
"disaster_people": {},
"shelter_nodes": [],
"shelter_capacities": {},
"current_mode": "选择灾难点(可多个)",
"strategy_type": "多目标优化(GA)",
"result_info": "",
"result_paths": [],
"simulation_completed": False,
"simulation_running": False,
"ga_pop_size": 40,
"ga_generations": 80,
# AI训练
"auto_train_ai": True,
"teacher_samples": 12,
"teacher_ga_pop": 20,
"teacher_ga_gen": 35,
"ai_lr": 0.2,
"ai_epochs": 120,
"teacher_time": None,
"train_time": None,
"ai_model": None,
"ai_loss_history": None,
"ai_weights": None,
# 对比
"compare_table": None,
"ga_time": None,
"ai_time": None,
# ✅ 所有策略都输出详细表
"detail_tables": [],
"detail_summary": None,
# leftover
"unassigned_total": 0,
# 智能体模拟状态
"llm_simulator": None,
"simulation_agents": [],
"simulation_steps": [],
"current_simulation_step": 0,
"is_simulation_running": False,
"simulation_edge_congestion": {},
"agent_statistics": None,
"simulation_results": None,
# 智能体生成参数
"agent_count": 20,
"max_simulation_steps": 50,
"use_llm_decision": True,
}
for k, v in defaults.items():
if k not in st.session_state:
st.session_state[k] = v
def ss_reset_results():
st.session_state.result_info = ""
st.session_state.result_paths = []
st.session_state.simulation_completed = False
st.session_state.compare_table = None
st.session_state.ga_time = None
st.session_state.ai_time = None
st.session_state.detail_tables = []
st.session_state.detail_summary = None
st.session_state.unassigned_total = 0
# 不清除智能体模拟相关状态
ss_init()
# ---------------------------------------------------------
# AI 训练(GA 当老师)——teacher 也走 repair(避免学到非法分配)
# ---------------------------------------------------------
def train_models_if_needed():
if st.session_state.ai_model is not None:
return
shelters = [int(x) for x in st.session_state.shelter_nodes]
if not shelters:
return
base_caps = {int(k): int(v) for k, v in
st.session_state.shelter_capacities.items()} if st.session_state.shelter_capacities else {}
if not base_caps:
# 没设就给默认
base_caps = {s: DEFAULT_SHELTER_CAPACITY for s in shelters}
sources_pool = st.session_state.disaster_nodes[:] if st.session_state.disaster_nodes else list(G.nodes())
if not sources_pool:
return
teacher_samples = []
t0 = time.perf_counter()
for _ in range(int(st.session_state.teacher_samples)):
s = int(random.choice(sources_pool))
N = int(max(100, random.choice([500, 800, 1000, 1500, 2000, 3000])))
path_infos = make_path_infos(G, s, shelters)
# teacher = GA,否则启发式
if ga_optimize_allocation is None:
alloc, leftover = heuristic_allocation(path_infos, N, base_caps)
else:
try:
# 给 GA 一些 seed(启发式 + 纯随机)
seed1, _ = heuristic_allocation(path_infos, N, base_caps)
seeds = [seed1]
res = ga_optimize_allocation(
G, s, shelters, total_people=N,
pop_size=int(st.session_state.teacher_ga_pop),
generations=int(st.session_state.teacher_ga_gen),
shelter_capacities=base_caps,
init_allocations=seeds,
)
best_paths, _m = safe_unpack_ga_result(res)
if not best_paths:
alloc, leftover = heuristic_allocation(path_infos, N, base_caps)
else:
mp = {int(x.get("target", x.get("shelter", -1))): int(x.get("people", 0)) for x in best_paths}
alloc0 = [mp.get(int(tt), 0) for tt in shelters]
alloc, leftover = repair_allocation_with_capacity_and_reachability(path_infos, alloc0, N, base_caps)
except Exception:
alloc, leftover = heuristic_allocation(path_infos, N, base_caps)
# y_share:只对已分配部分学习(leftover 不参与比例)
assigned = max(1, N - leftover)
y_share = (np.array(alloc, dtype=np.float32) / float(assigned))
if float(y_share.sum()) <= 1e-9:
continue
y_share = y_share / float(y_share.sum())
X = build_path_feature_matrix(path_infos, base_caps)
teacher_samples.append((X, y_share))
st.session_state.teacher_time = float(time.perf_counter() - t0)
t1 = time.perf_counter()
model = train_allocation_predictor(
teacher_samples,
lr=float(st.session_state.ai_lr),
epochs=int(st.session_state.ai_epochs),
l2=1e-3
)
st.session_state.train_time = float(time.perf_counter() - t1)
st.session_state.ai_model = model
st.session_state.ai_loss_history = model.loss_history
st.session_state.ai_weights = model.w.copy()
# ---------------------------------------------------------
# 侧边栏
# ---------------------------------------------------------
with st.sidebar:
create_sidebar_header()
st.markdown("### 🏃♀️ 疏散策略")
options = ["单一路径", "多路径分流", "多目标优化(GA)", "AI预测(Allocation Predictor)", "LLM智能体模拟"]
st.session_state.strategy_type = st.selectbox(
"选择疏散策略类型:",
options,
index=options.index(st.session_state.strategy_type) if st.session_state.strategy_type in options else 2
)
st.markdown("---")
st.markdown("### ⚙️ 地图点击模式")
st.session_state.current_mode = st.radio(
"地图点击模式:",
["选择灾难点(可多个)", "添加/设置避难点"],
index=0 if st.session_state.current_mode.startswith("选择灾难点") else 1
)
st.markdown("---")
st.markdown("### 🔥 多灾难点人数设置")
total_people = 0
if st.session_state.disaster_nodes:
for i, s in enumerate(st.session_state.disaster_nodes):
key = str(s)
ppl = int(st.session_state.disaster_people.get(key, 100))
new_p = st.number_input(
f"灾难点{i + 1} (节点{s}) 人数",
min_value=0, max_value=100000,
value=int(ppl),
step=10,
key=f"ppl_{key}"
)
st.session_state.disaster_people[key] = int(new_p)
total_people += int(new_p)
else:
st.caption("还未设置灾难点(点击地图添加)")
st.metric("自动汇总总疏散人数", int(total_people))
st.markdown("---")
st.markdown("### 🏠 避难点容量设置")
if st.session_state.shelter_nodes:
for idx, shelter in enumerate(st.session_state.shelter_nodes):
skey = str(shelter)
cur_cap = int(st.session_state.shelter_capacities.get(skey, DEFAULT_SHELTER_CAPACITY))
new_cap = st.number_input(
f"避难点{idx + 1} (节点{shelter}) 容量",
min_value=0, max_value=200000,
value=cur_cap, step=10,
key=f"cap_{shelter}_{idx}"
)
st.session_state.shelter_capacities[skey] = int(new_cap)
else:
st.caption("还未设置避难点(点击地图添加)")
total_capacity = sum(
int(v) for v in st.session_state.shelter_capacities.values()) if st.session_state.shelter_capacities else 0
st.metric("避难点总容量", int(total_capacity))
if total_people > 0 and total_capacity > 0 and total_capacity < total_people:
st.error(f"⚠️ 容量不足:总容量 {total_capacity} < 总疏散人数 {total_people}(将产生未安置人数)")
# 根据选择的策略类型显示不同的参数
st.markdown("---")
if st.session_state.strategy_type == "多目标优化(GA)":
st.markdown("### 🧬 GA 参数")
st.session_state.ga_pop_size = st.slider("种群大小", 10, 120, int(st.session_state.ga_pop_size), 5)
st.session_state.ga_generations = st.slider("迭代代数", 10, 250, int(st.session_state.ga_generations), 10)
elif st.session_state.strategy_type == "AI预测(Allocation Predictor)":
st.markdown("### 🤖 AI 模型(GA当老师)")
st.session_state.auto_train_ai = st.checkbox("运行策略时若未训练则自动训练",
value=bool(st.session_state.auto_train_ai))
st.session_state.teacher_samples = st.slider("teacher 样本数", 4, 40, int(st.session_state.teacher_samples), 2)
st.session_state.teacher_ga_pop = st.slider("teacher GA 种群", 10, 60, int(st.session_state.teacher_ga_pop), 5)
st.session_state.teacher_ga_gen = st.slider("teacher GA 代数", 10, 120, int(st.session_state.teacher_ga_gen), 5)
st.session_state.ai_lr = st.slider("AI 学习率", 0.01, 0.8, float(st.session_state.ai_lr), 0.01)
st.session_state.ai_epochs = st.slider("AI 训练轮数", 30, 400, int(st.session_state.ai_epochs), 10)
elif st.session_state.strategy_type == "LLM智能体模拟":
st.markdown("### 🤖 智能体模拟参数")
if not LLM_AVAILABLE:
st.warning("LLM模块不可用,请检查dashscope库安装和API配置")
st.session_state.agent_count = st.slider(
"智能体数量",
min_value=5,
max_value=AGENT_GENERATION_CONFIG.get("max_agents_per_simulation", 100),
value=st.session_state.agent_count,
step=5
)
st.session_state.max_simulation_steps = st.slider(
"最大模拟步数",
min_value=10,
max_value=200,
value=st.session_state.max_simulation_steps,