File size: 29,170 Bytes
9b512b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
 
9b512b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
9b512b7
 
 
 
51a5ea2
9b512b7
51a5ea2
9b512b7
 
51a5ea2
 
9b512b7
51a5ea2
9b512b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
9b512b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
 
9b512b7
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
 
9b512b7
 
 
 
 
 
 
 
 
 
51a5ea2
9b512b7
51a5ea2
9b512b7
 
51a5ea2
9b512b7
51a5ea2
 
9b512b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
 
 
9b512b7
 
 
 
 
 
 
51a5ea2
9b512b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
 
9b512b7
 
 
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
 
9b512b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
 
9b512b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
9b512b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
 
 
9b512b7
 
 
 
 
 
51a5ea2
9b512b7
51a5ea2
 
9b512b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51a5ea2
 
 
9b512b7
 
51a5ea2
9b512b7
 
51a5ea2
9b512b7
 
 
 
 
 
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
# stage3_geo_analysis.py
# -*- coding: utf-8 -*-
"""
Step 3: Step 2가 만든 [r1-1] 결과 CSV를 바탕으로 국가/지역 단위 유입원 분석 표와
그림을 생성합니다.

"""

from __future__ import annotations

import os
import re
import glob

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import font_manager as fm

import settings_dengue as s
from path_config import get_path_config

TOPK = 5

# ── 엔데믹 지역 정의 ─────────────────────────────────────────────────────────
# 유입원(source) 국가가 아래 지역에 속할 때에만 city 단위 추가 분석을 수행한다.
ENDEMIC_REGIONS = {"South America", "Southeast Asia", "Africa", "South Asia", "Oceania"}

# 그림 3·4·5에서 "발견국(도착지)"으로 제외할 주요 뎅기 엔데믹 국가들.
# settings_dengue.py 의 source_countries 를 단일 소스로 사용하고,
# 원본 스크립트에만 있던 "Solomon-Islands" 만 보존해서 합쳤습니다.
MAJOR_ENDEMIC_COUNTRIES = set(s.source_countries) | {"Solomon-Islands"}

# 국가 -> 지역 매핑도 settings_dengue.py 를 단일 소스로 사용합니다.
REGION_MAP = dict(s.region_map)


# =============================================================================
# 폰트 설정 (크로스플랫폼, HF Spaces 포함)
# =============================================================================
# HF Spaces 컨테이너에는 시스템 한글 폰트(나눔고딕/Noto Sans CJK)가 기본 설치되어
# 있지 않은 경우가 많아, 이전 버전(시스템 폰트 경로만 탐색)에서는 한글이 네모(□)로
# 깨지는 문제가 있었습니다. 이를 해결하기 위해 이 스크립트와 같은 폴더의
# fonts/NanumGothic-Regular.ttf 를 저장소에 함께 포함시키고, 시스템 폰트보다
# 이 번들 폰트를 최우선으로 사용하도록 바꿨습니다. (배포 환경과 무관하게 항상 동작)
_THIS_DIR = os.path.dirname(os.path.abspath(__file__))
_BUNDLED_FONT = os.path.join(_THIS_DIR, "fonts", "NanumGothic-Regular.ttf")


def set_korean_font():
    font_candidates = [
        _BUNDLED_FONT,                                              # 1순위: 이 저장소에 포함된 폰트
        "/usr/share/fonts/truetype/nanum/NanumGothic.ttf",          # 2순위: apt fonts-nanum 로 설치된 경우
        "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",   # 3순위: apt fonts-noto-cjk 로 설치된 경우
        "C:/Windows/Fonts/malgun.ttf",                              # Windows 로컬 실행 시
        "/System/Library/Fonts/AppleSDGothicNeo.ttc",               # macOS 로컬 실행 시
    ]
    for fp in font_candidates:
        if os.path.exists(fp):
            try:
                fm.fontManager.addfont(fp)
                name = fm.FontProperties(fname=fp).get_name()
                plt.rcParams["font.family"] = name
                plt.rcParams["axes.unicode_minus"] = False
                return
            except Exception:
                continue
    # 어떤 후보도 못 찾은 경우: 조용히 넘어가지 않고 명확히 경고
    print("⚠️  No Korean font found. Korean characters in graphs may not display correctly. "
          f"Check that the font file exists at '{_BUNDLED_FONT}'.")
    plt.rcParams["axes.unicode_minus"] = False


# =============================================================================
# (원본 In[5] 셀) 진단용 체크 - top{k}_location 컬럼 존재 여부 확인
# =============================================================================
def check_location_column(paths):
    """paths['results'] 안의 r1-1*.csv 를 찾아 top1_location 컬럼이
    존재하는지, ':' 포함 비율이 얼마인지 확인합니다. (분석 실행 전 사전 점검용)

    원본에서는 이 로직이 전역 변수 s(=settings_dengue 모듈)를 덮어써서
    이후 코드에서 s.xxx 참조가 깨질 수 있는 버그가 있었습니다.
    여기서는 지역 변수(loc_series)만 사용하도록 고쳤습니다.
    """
    src_dir = paths['results']
    candidates = [f for f in src_dir.glob("*.csv")
                  if re.match(r"^[\W_]*r1-1(?![0-9])", f.name, re.I)]
    if not candidates:
        print("→ No CSV file starting with r1-1 was found.")
        return

    src = candidates[0]
    df = pd.read_csv(src)
    print("File:", src.name)
    loc_cols = [c for c in df.columns if c.endswith("_location")]
    print("Location columns:", loc_cols)
    if loc_cols:
        loc_series = df["top1_location"].astype(str)
        print("Percentage of top1_location values containing ':' = %.1f%%" % (loc_series.str.contains(":").mean() * 100))
        print("Examples:", loc_series.head(5).tolist())
    else:
        print("→ No top{k}_location columns found: rerun Step 2 with GROUP_LEVEL='city'.")


# =============================================================================
# 입력 파일 탐색 / 파싱
# =============================================================================
def find_input(input_dir):
    """input_dir 안에서 'r1' 로 시작(단 r10, r11 처럼 뒤에 숫자가 더 붙는 건 제외)
    하는 csv 를 찾아 반환. glob.escape() 로 폴더명의 [ ] 같은 특수문자를 이스케이프.

    '[r1-1]...' 파일과 '[r1]...' 파일이 둘 다 있으면 정렬 순서상('-' < ']')
    '[r1-1]...' 이 먼저 선택되어, top{k}_location 이 있는 파일이 자동으로 선택됩니다."""
    pattern = os.path.join(glob.escape(str(input_dir)), "*.csv")
    cands = [f for f in glob.glob(pattern)
             if re.match(r"^[\W_]*r1(?![0-9])", os.path.basename(f), re.IGNORECASE)]
    if not cands:
        raise FileNotFoundError(f"No CSV file starting with r1 was found in '{input_dir}'.")
    return sorted(cands)[0]


def extract_found_country(seq_id, rmap):
    """unknown_seq_id 에서 '발견국(country)'을 추출.
    헤더가 '..._country_city' 또는 '..._country_unknown' 처럼 끝에 city 가 붙을 수 있으므로,
    토큰을 뒤에서부터 훑어 REGION_MAP(rmap)에 존재하는 첫 국가명을 반환한다.
    (city/'unknown' 토큰은 rmap 에 없으므로 자연히 건너뜀)
    매칭 실패 시 마지막 토큰을 그대로 반환(기존 동작과 호환)."""
    toks = str(seq_id).split("_")
    for t in reversed(toks):
        if t in rmap:
            return t
    return toks[-1] if toks else "NA"


def load_data(path, rmap):
    df = pd.read_csv(path)
    df["found_country"] = df["unknown_seq_id"].astype(str).apply(lambda x: extract_found_country(x, rmap))
    return df


def extract_gene(path):
    """파일명에서 gene 추출. '_' 로 나눈 마지막(.csv 제외) 토큰. '-' 는 '/' 로 변환. 예: ..._C-prM.csv -> C/prM"""
    stem = re.sub(r"\.csv$", "", os.path.basename(path), flags=re.IGNORECASE)
    toks = [t for t in stem.split("_") if t]
    gene = toks[-1] if toks else "NA"
    return gene.replace("-", "/")


def extract_serotype(df):
    """첫 행 unknown_seq_id 에서 serotype 추출. '_' 토큰 중 DENV1~4 패턴. 예: ...DENV1... -> DENV1"""
    sid = str(df["unknown_seq_id"].iloc[0])
    for t in sid.split("_"):
        if re.fullmatch(r"DENV-?\d", t, flags=re.IGNORECASE):
            return t.upper().replace("-", "")
    return "NA"


def load_region_map(path=None):
    """기본은 settings_dengue.py 의 region_map. path(csv: country,region)가 있으면 그 값으로 보완/덮어쓴다."""
    rmap = dict(REGION_MAP)
    if path and os.path.exists(path):
        rm = pd.read_csv(path)
        rmap.update(dict(zip(rm["country"], rm["region"])))
    return rmap


def to_region(c, rmap):
    return rmap.get(c, "Unknown")


# =============================================================================
# 집계 로직
# =============================================================================
def melt_matches(df):
    """top1..K 매칭을 long 포맷으로 펼친다.
    top{k}_location('country:city')이 있으면 source_city 도 함께 추출한다.
    location 만 있고 country 컬럼이 없으면 country 는 location 의 콜론 앞부분으로 보완."""
    has_loc = any(f"top{k}_location" in df.columns for k in range(1, TOPK + 1))
    rows = []
    for _, r in df.iterrows():
        for k in range(1, TOPK + 1):
            sc = r.get(f"top{k}_country")
            sim = r.get(f"top{k}_similarity_percent")
            loc = r.get(f"top{k}_location") if has_loc else None
            if (pd.isna(sc) or sc is None) and isinstance(loc, str):
                sc = loc.split(":")[0]
            if pd.isna(sc) or pd.isna(sim):
                continue
            city = loc.split(":", 1)[1] if (isinstance(loc, str) and ":" in loc) else None
            rows.append(dict(unknown_seq_id=r["unknown_seq_id"],
                              found_country=r["found_country"], rank=k,
                              source_country=sc, source_location=loc,
                              source_city=city, similarity=float(sim)))
    return pd.DataFrame(rows)


def add_weight(long_df, scheme="sim"):
    sim_frac = long_df["similarity"] / 100.0
    rk = (TOPK - long_df["rank"] + 1)
    w = {"sim": sim_frac, "rank": rk.astype(float), "rank_sim": rk * sim_frac,
         "top1": np.where(long_df["rank"] == 1, 1.0, 0.0)}[scheme]
    out = long_df.copy()
    out["weight"] = w
    out["is_self"] = out["source_country"] == out["found_country"]
    return out


def _profile(sub, col, label):
    g = sub.groupby(col)["weight"].sum().sort_values(ascending=False).reset_index()
    tot = g["weight"].sum()
    g["share_%"] = np.where(tot > 0, g["weight"] / tot * 100, 0).round(2)
    g["weight"] = g["weight"].round(4)
    return g.rename(columns={col: label})


def per_country_source(long_w, rmap, exclude_self=True):
    data = long_w[~long_w["is_self"]] if exclude_self else long_w
    oc, orr = [], []
    for fc, sub in data.groupby("found_country"):
        n = sub["unknown_seq_id"].nunique()
        gc = _profile(sub, "source_country", "source_country")
        gc.insert(0, "found_country", fc); gc.insert(1, "n_unknown_seq", n); oc.append(gc)
        sub2 = sub.assign(source_region=sub["source_country"].map(lambda c: to_region(c, rmap)))
        gr = _profile(sub2, "source_region", "source_region")
        gr.insert(0, "found_country", fc); gr.insert(1, "n_unknown_seq", n); orr.append(gr)

    if not oc:
        # 그룹이 하나도 없는 경우(예: 대상 발견국이 전부 제외 대상 하나뿐이라 exclude 후
        # 데이터가 0행이 되는 경우) pd.concat([]) 은 예외를 던지므로, 빈 DataFrame을
        # 정상적으로 반환해 호출부(run())가 이 상황을 건너뛸 수 있게 합니다.
        empty_country = pd.DataFrame(columns=["found_country", "n_unknown_seq", "source_country", "weight", "share_%"])
        empty_region = pd.DataFrame(columns=["found_country", "n_unknown_seq", "source_region", "weight", "share_%"])
        return empty_country, empty_region

    return pd.concat(oc, ignore_index=True), pd.concat(orr, ignore_index=True)


def overall_source(long_w, rmap, exclude_self=True):
    data = long_w[~long_w["is_self"]] if exclude_self else long_w
    by_c = _profile(data, "source_country", "source_country")
    d = data.assign(source_region=data["source_country"].map(lambda c: to_region(c, rmap)))
    return by_c, _profile(d, "source_region", "source_region")


def region_flow_matrix(long_w, rmap, exclude_self=True):
    data = long_w[~long_w["is_self"]] if exclude_self else long_w
    d = data.assign(dest_region=data["found_country"].map(lambda c: to_region(c, rmap)),
                     source_region=data["source_country"].map(lambda c: to_region(c, rmap)))
    return d.pivot_table(index="dest_region", columns="source_region",
                          values="weight", aggfunc="sum", fill_value=0.0).round(3)


def endemic_summary(long_w):
    rows = []
    for fc, sub in long_w.groupby("found_country"):
        tot = sub["weight"].sum(); self_w = sub.loc[sub["is_self"], "weight"].sum()
        rows.append(dict(found_country=fc, n_unknown_seq=sub["unknown_seq_id"].nunique(),
                          self_weight=round(self_w, 4), imported_weight=round(tot - self_w, 4),
                          total_weight=round(tot, 4),
                          self_share_pct=round(self_w / tot * 100, 2) if tot else 0,
                          imported_share_pct=round((tot - self_w) / tot * 100, 2) if tot else 0))

    if not rows:
        # pd.DataFrame([]) 은 컬럼이 아예 없는 빈 DataFrame이 되어, 이후
        # sort_values("n_unknown_seq") 가 KeyError 로 죽습니다. 기대되는 컬럼
        # 구조를 명시한 빈 DataFrame을 대신 반환해 호출부가 안전하게 처리하게 합니다.
        return pd.DataFrame(columns=["found_country", "n_unknown_seq", "self_weight",
                                      "imported_weight", "total_weight",
                                      "self_share_pct", "imported_share_pct"])

    return pd.DataFrame(rows).sort_values("n_unknown_seq", ascending=False).reset_index(drop=True)


def city_source_for_endemic(long_w, rmap, endemic_regions=ENDEMIC_REGIONS,
                             exclude_self=True, top_city=10, drop_unknown_city=False):
    """유입원(source) 국가가 endemic_regions 에 속하는 매칭만 모아,
    'source_country x source_city' 단위로 가중합/비중을 집계한다."""
    data = long_w[~long_w["is_self"]] if exclude_self else long_w
    if "source_city" not in data.columns or data["source_city"].isna().all():
        return pd.DataFrame()

    data = data.assign(source_region=data["source_country"].map(lambda c: to_region(c, rmap)))
    data = data[data["source_region"].isin(endemic_regions) & data["source_city"].notna()]
    if drop_unknown_city:
        data = data[data["source_city"].str.lower() != "unknown"]
    if data.empty:
        return pd.DataFrame()

    out = []
    for sc, sub in data.groupby("source_country"):
        g = sub.groupby("source_city")["weight"].sum().sort_values(ascending=False).reset_index()
        tot = g["weight"].sum()
        g["share_in_country_%"] = np.where(tot > 0, g["weight"] / tot * 100, 0).round(2)
        g["weight"] = g["weight"].round(4)
        g.insert(0, "source_country", sc)
        g.insert(1, "source_region", to_region(sc, rmap))
        out.append(g.head(top_city))
    res = pd.concat(out, ignore_index=True)
    order = (res.groupby("source_country")["weight"].sum()
             .sort_values(ascending=False).index.tolist())
    res["__ord"] = res["source_country"].map({c: i for i, c in enumerate(order)})
    res = res.sort_values(["__ord", "weight"], ascending=[True, False]).drop(columns="__ord").reset_index(drop=True)
    return res


# =============================================================================
# 시각화
# =============================================================================
def fig_overall_region(ov_region, fig_dir, meta="", tag="", lang="ko"):
    en = lang == "en"
    d = ov_region.sort_values("share_%")
    fig, ax = plt.subplots(figsize=(9, 6))
    bars = ax.barh(d["source_region"], d["share_%"], color="#2E86C1")
    ax.bar_label(bars, fmt="%.1f%%", padding=3, fontsize=9)
    ax.set_xlabel("Source share (%)" if en else "Source share (%)")
    ax.set_title(f"{meta}Overall source-region share (imported only)" if en else f"{meta}Overall source-region share (imported only)", fontweight="bold")
    ax.set_xlim(0, d["share_%"].max() * 1.15); ax.margins(y=0.01)
    for spine in ("top", "right"): ax.spines[spine].set_visible(False)
    fig.tight_layout(); p = os.path.join(fig_dir, f"01_overall_source_region{('_'+tag) if tag else ''}.png")
    fig.savefig(p, dpi=150); plt.close(fig); return p


def fig_overall_country(ov_country, fig_dir, topn=15, meta="", tag="", lang="ko"):
    en = lang == "en"
    d = ov_country.head(topn).sort_values("share_%")
    fig, ax = plt.subplots(figsize=(9, 7))
    bars = ax.barh(d["source_country"], d["share_%"], color="#117A65")
    ax.bar_label(bars, fmt="%.1f%%", padding=3, fontsize=9)
    ax.set_xlabel("Source share (%)" if en else "Source share (%)")
    ax.set_title(f"{meta}Top {topn} source countries overall (imported only)" if en else f"{meta}Top {topn} source countries overall (imported only)", fontweight="bold")
    ax.set_xlim(0, d["share_%"].max() * 1.15)
    for spine in ("top", "right"): ax.spines[spine].set_visible(False)
    fig.tight_layout(); p = os.path.join(fig_dir, f"02_overall_source_country{('_'+tag) if tag else ''}.png")
    fig.savefig(p, dpi=150); plt.close(fig); return p


def fig_endemic(endemic, fig_dir, topn=15, meta="", tag="", lang="ko"):
    en = lang == "en"
    d = endemic.head(topn).iloc[::-1]
    fig, ax = plt.subplots(figsize=(9, 7))
    ax.barh(d["found_country"], d["imported_share_pct"], color="#E67E22", label="Imported" if en else "Imported")
    ax.barh(d["found_country"], d["self_share_pct"], left=d["imported_share_pct"],
            color="#85929E", label="Local circulation" if en else "Local circulation")
    for i, (_, r) in enumerate(d.iterrows()):
        ax.text(2, i, f"n={int(r['n_unknown_seq'])}", va="center", fontsize=8, color="white")
    ax.set_xlim(0, 100); ax.set_xlabel("Share (%)" if en else "Share (%)")
    ax.set_title(
        f"{meta}Imported vs. local circulation by detection country (top {topn} by sequence count)" if en else
        f"{meta}Imported vs. local circulation by detection country (top {topn} by sequence count)", fontweight="bold"
    )
    ax.legend(loc="lower right", framealpha=0.9)
    for spine in ("top", "right"): ax.spines[spine].set_visible(False)
    fig.tight_layout(); p = os.path.join(fig_dir, f"03_endemic_vs_imported{('_'+tag) if tag else ''}.png")
    fig.savefig(p, dpi=150); plt.close(fig); return p


def fig_flow_heatmap(flow, fig_dir, meta="", tag="", lang="ko"):
    en = lang == "en"
    m = flow.copy()
    m = m.loc[m.sum(axis=1).sort_values(ascending=False).index,
              m.sum(axis=0).sort_values(ascending=False).index]
    fig, ax = plt.subplots(figsize=(11, 8))
    im = ax.imshow(m.values, cmap="YlOrRd", aspect="auto")
    ax.set_xticks(range(m.shape[1])); ax.set_xticklabels(m.columns, rotation=45, ha="right", fontsize=8)
    ax.set_yticks(range(m.shape[0])); ax.set_yticklabels(m.index, fontsize=8)
    ax.set_xlabel("Source region (origin)" if en else "Source region (origin)")
    ax.set_ylabel("Destination region (detection country)" if en else "Destination region (detection country)")
    ax.set_title(f"{meta}Regional flow matrix (weighted sum)" if en else f"{meta}Regional flow matrix (weighted sum)", fontweight="bold")
    vmax = m.values.max()
    for i in range(m.shape[0]):
        for j in range(m.shape[1]):
            v = m.values[i, j]
            if v > 0:
                ax.text(j, i, f"{v:.0f}", ha="center", va="center", fontsize=7,
                        color="white" if v > vmax * 0.5 else "black")
    fig.colorbar(im, ax=ax, shrink=0.8, label="Weighted sum" if en else "Weighted sum")
    fig.tight_layout(); p = os.path.join(fig_dir, f"04_region_flow_heatmap{('_'+tag) if tag else ''}.png")
    fig.savefig(p, dpi=150); plt.close(fig); return p


def fig_per_country_facets(pc_region, endemic, fig_dir, topn=9, top_src=5, meta="", tag="", lang="ko"):
    en = lang == "en"
    order = endemic.head(topn)["found_country"].tolist()
    ncol = 3; nrow = int(np.ceil(len(order) / ncol))
    fig, axes = plt.subplots(nrow, ncol, figsize=(15, 4 * nrow))
    axes = np.array(axes).reshape(-1)
    cmap = plt.get_cmap("tab20")
    for ax, fc in zip(axes, order):
        d = pc_region[pc_region["found_country"] == fc].head(top_src).sort_values("share_%")
        ax.barh(d["source_region"], d["share_%"],
                color=[cmap(i % 20) for i in range(len(d))])
        for y, (_, r) in enumerate(d.iterrows()):
            ax.text(r["share_%"] + 1, y, f"{r['share_%']:.0f}%", va="center", fontsize=8)
        n = int(endemic.loc[endemic["found_country"] == fc, "n_unknown_seq"].iloc[0])
        ax.set_title(f"{fc}  (n={n})", fontsize=11, fontweight="bold")
        ax.set_xlim(0, max(d["share_%"].max() * 1.2, 10))
        for spine in ("top", "right"): ax.spines[spine].set_visible(False)
    for ax in axes[len(order):]: ax.axis("off")
    fig.suptitle(
        f"{meta}Source-region profiles by detection country (imported only, top detection countries)" if en else
        f"{meta}Source-region profiles by detection country (imported only, top detection countries)",
        fontsize=14, fontweight="bold", y=1.0
    )
    fig.tight_layout(); p = os.path.join(fig_dir, f"05_per_country_region_facets{('_'+tag) if tag else ''}.png")
    fig.savefig(p, dpi=150, bbox_inches="tight"); plt.close(fig); return p


def fig_city_source_endemic(city_tbl, fig_dir, topn_country=15, top_city=5, meta="", tag="", lang="ko"):
    """엔데믹 유입원 국가별로 상위 source city 비중을 facet 막대로 표시."""
    en = lang == "en"
    if city_tbl is None or city_tbl.empty:
        if en:
            print("  ℹ️  No city-level source data — skipping figure 06. "
                  "(input r1 csv must have a top{k}_location column)")
        else:
            print("  ℹ️  No city-level source data available. Skipping figure 06. "
                  "(The input r1 CSV must contain a top{k}_location column.)")
        return None
    order = (city_tbl.groupby("source_country")["weight"].sum()
             .sort_values(ascending=False).head(topn_country).index.tolist())
    ncol = 3; nrow = int(np.ceil(len(order) / ncol))
    fig, axes = plt.subplots(nrow, ncol, figsize=(15, 4 * nrow))
    axes = np.array(axes).reshape(-1)
    cmap = plt.get_cmap("tab20")
    for ax, sc in zip(axes, order):
        d = city_tbl[city_tbl["source_country"] == sc].head(top_city).sort_values("share_in_country_%")
        ax.barh(d["source_city"], d["share_in_country_%"],
                color=[cmap(i % 20) for i in range(len(d))])
        for y, (_, r) in enumerate(d.iterrows()):
            ax.text(r["share_in_country_%"] + 1, y, f"{r['share_in_country_%']:.0f}%", va="center", fontsize=8)
        region = d["source_region"].iloc[0] if not d.empty else ""
        ax.set_title(f"{sc}  ({region})", fontsize=11, fontweight="bold")
        ax.set_xlim(0, max(d["share_in_country_%"].max() * 1.2, 10))
        for spine in ("top", "right"): ax.spines[spine].set_visible(False)
    for ax in axes[len(order):]: ax.axis("off")
    fig.suptitle(
        f"{meta}Source-city distribution in endemic countries" if en else
        f"{meta}Source-city distribution in endemic countries",
        fontsize=14, fontweight="bold", y=1.0
    )
    fig.tight_layout(); p = os.path.join(fig_dir, f"06_endemic_source_city{('_'+tag) if tag else ''}.png")
    fig.savefig(p, dpi=150, bbox_inches="tight"); plt.close(fig); return p


# =============================================================================
# 실행 파이프라인
# =============================================================================
def run(input_dir, region_map_path=None, out_dir=None, fig_dir=None, scheme="sim", topn=12, lang="ko"):
    set_korean_font()
    src = find_input(input_dir); print(f"[load] {src}")
    rmap = load_region_map(region_map_path)
    df = load_data(src, rmap)
    serotype = extract_serotype(df); gene = extract_gene(src)
    meta = f"[{serotype} · {gene}] "
    file_tag = re.sub(r"[^0-9A-Za-z._-]", "-", f"{serotype}_{gene}")
    print(f"[meta] serotype={serotype}, gene={gene} | file_tag={file_tag}")
    long_w = add_weight(melt_matches(df), scheme=scheme)

    long_w_excl = long_w[~long_w["found_country"].isin(MAJOR_ENDEMIC_COUNTRIES)].copy()
    dropped = sorted(set(long_w["found_country"]) & set(MAJOR_ENDEMIC_COUNTRIES))
    print(f"[exclude] Detection countries excluded from figures 3, 4, and 5: {dropped}")

    pc_c, pc_r = per_country_source(long_w, rmap, exclude_self=True)
    ov_c, ov_r = overall_source(long_w, rmap, exclude_self=True)
    flow = region_flow_matrix(long_w, rmap, exclude_self=True)
    endemic = endemic_summary(long_w)

    _, pc_r_x = per_country_source(long_w_excl, rmap, exclude_self=True)
    flow_x = region_flow_matrix(long_w_excl, rmap, exclude_self=True)
    endemic_x = endemic_summary(long_w_excl)

    # 발견국이 전부 주요 엔데믹 국가라서(위 exclude 로 전부 빠지는 경우) long_w_excl 이
    # 0행이 될 수 있습니다. 이 경우 그림 3·4·5는 그릴 데이터 자체가 없는 것이 정상이므로,
    # 에러 없이 건너뛰고 이유를 안내합니다.
    excl_has_data = not long_w_excl.empty
    if not excl_has_data:
        print("  ℹ️  All detection countries are major endemic countries, or no data are available. "
              "Figures 3, 4, and 5 (comparisons excluding endemic countries) cannot be generated. "
              "To generate these figures, analyze sequences from multiple detection countries, including countries outside the excluded group.")

    has_city = long_w["source_city"].notna().any() if "source_city" in long_w else False
    city_endemic = city_source_for_endemic(long_w, rmap, ENDEMIC_REGIONS,
                                            exclude_self=True, top_city=15)
    if has_city:
        n_ctry = city_endemic["source_country"].nunique() if not city_endemic.empty else 0
        print(f"[city] Source-city breakdown for endemic countries: {n_ctry} countries (regions={sorted(ENDEMIC_REGIONS)})")
    else:
        print("[city] No top{k}_location columns found in the input r1 CSV. Skipping city-level analysis. "
              "(Rerun the analysis pipeline with GROUP_LEVEL='city'.)")

    os.makedirs(out_dir, exist_ok=True); os.makedirs(fig_dir, exist_ok=True)
    tables = {"per_country_source_country": pc_c, "per_country_source_region": pc_r,
              "overall_source_country": ov_c, "overall_source_region": ov_r,
              "region_flow_matrix": flow, "endemic_vs_imported": endemic,
              "endemic_source_city": city_endemic}
    for name, d in tables.items():
        if d is None or (hasattr(d, "empty") and d.empty):
            continue
        d.to_csv(os.path.join(out_dir, f"{name}_{file_tag}.csv"),
                 index=(name == "region_flow_matrix"), encoding="utf-8-sig")

    figs = [fig_overall_region(ov_r, fig_dir, meta=meta, tag=file_tag, lang=lang),
            fig_overall_country(ov_c, fig_dir, topn=15, meta=meta, tag=file_tag, lang=lang),
            fig_endemic(endemic_x, fig_dir, topn=topn, meta=meta, tag=file_tag, lang=lang) if excl_has_data else None,
            fig_flow_heatmap(flow_x, fig_dir, meta=meta, tag=file_tag, lang=lang) if excl_has_data else None,
            fig_per_country_facets(pc_r_x, endemic_x, fig_dir, topn=10, meta=meta, tag=file_tag, lang=lang) if excl_has_data else None,
            fig_city_source_endemic(city_endemic, fig_dir, topn_country=10, meta=meta, tag=file_tag, lang=lang)]
    print(f"[done] scheme={scheme} | tables -> {out_dir}/ | figures -> {fig_dir}/")
    for f in figs:
        if f: print("   ", f)
    return tables, figs


# =============================================================================
# 메인 실행
# =============================================================================
def main(lang="ko"):
    """Step 3 메인 실행 함수 (stage1.main() / stage2.main() 과 동일한 형태로 통일)."""
    paths = get_path_config(s)

    # 원본 In[5] 셀에 해당하는 사전 점검 (선택 사항)
    check_location_column(paths)

    INPUT_DIR = paths['results']                              # r1(-1)*.csv 가 있는 폴더
    REGION_CSV = None                                          # 내장 REGION_MAP 사용. 일부만 덮어쓰려면 "override.csv"
    OUT_DIR = paths['results'] / "01_output"                   # results 폴더 안에 생성
    FIG_DIR = paths['results'] / "02_figures"                  # results 폴더 안에 생성
    SCHEME = "sim"          # sim | rank | rank_sim | top1
    TOPN = 30               # 차트에 표시할 발견국 수

    tables, figs = run(str(INPUT_DIR), REGION_CSV, str(OUT_DIR), str(FIG_DIR), SCHEME, TOPN, lang=lang)

    print("Overall source-region ranking"); print(tables["overall_source_region"])
    print("Top 10 source countries overall"); print(tables["overall_source_country"].head(10))
    print("Local circulation vs. imported sources by detection country"); print(tables["endemic_vs_imported"].head(TOPN))

    if "endemic_source_city" in tables and not tables["endemic_source_city"].empty:
        print("Source-city distribution in endemic countries (South America, Southeast Asia, Africa, South Asia)")
        print(tables["endemic_source_city"])
    else:
        print("No city-level breakdown available for endemic countries (a top{k}_location column is required in the input)")

    return tables, figs


if __name__ == "__main__":
    main()