diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 384dfb28..5254d9e3 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -15,6 +15,7 @@
- [ ] `make check` (ruff + pytest)가 통과합니다
- [ ] 다른 사람의 폴더나 `core/`를 (합의 없이) 수정하지 않았습니다
- [ ] 원자료·가공 데이터 파일을 커밋하지 않았습니다 (시뮬레이션·조례 목록 제외)
+- [ ] 결과 PR이면 작성자가 아닌 리뷰어가 [검토 체크리스트](docs/ops/review-checklist.md) 여덟 항목을 리뷰 댓글로 확인했습니다
## 리뷰어에게
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 67d8cc45..57f2512c 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -56,3 +56,27 @@ jobs:
cases/_example_night_clinic/figures/
if-no-files-found: warn
retention-days: 14
+
+ # PyWhy(DoWhy)·CausalML 연계 — 무거운 선택 설치라 따로 돈다
+ causal:
+ runs-on: ubuntu-latest
+ timeout-minutes: 20
+ env:
+ MPLBACKEND: Agg
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+ cache: pip
+ cache-dependency-path: pyproject.toml
+ - name: Install (causal extra)
+ run: |
+ python -m pip install --upgrade pip
+ pip install -e ".[dev,causal]"
+ - name: License check with causal extra
+ run: python scripts/check_licenses.py
+ - name: PyWhy·CausalML tests
+ run: pytest -q tests/test_causal.py
+ - name: Second opinion on the example case
+ run: python -m core.causal cases/_example_night_clinic --no-write
diff --git a/Makefile b/Makefile
index 6ec5a887..2dadd898 100644
--- a/Makefile
+++ b/Makefile
@@ -1,4 +1,4 @@
-.PHONY: install check lint test format app activity flow demo site lineage readme
+.PHONY: install check lint test format app activity flow demo site lineage readme pywhy draft
PY ?= python
@@ -25,6 +25,15 @@ CASE ?= cases/_example_night_clinic
flow:
$(PY) -m core.agent $(CASE)
+# 두 번째 의견: PyWhy(DoWhy) 식별·반박 검정 + CausalML 단위별 효과 → cases/<케이스>/pywhy_check.json
+# 먼저 pip install -e ".[causal]"
+pywhy:
+ $(PY) -m core.causal $(CASE)
+
+# 질문 한 줄 → 가설·데이터 점검 → plan.yaml 초안 (Q="질문", NEW=<내ID>-<주제> 를 주면 cases/ 에 저장)
+draft:
+ $(PY) -m core.causal.draft "$(Q)" $(if $(NEW),--case $(NEW) --write,)
+
# 연습: 토지거래허가구역 예시를 _demo/ 에 복사해 돌린다. 레포 파일은 바뀌지 않는다.
demo:
rm -rf _demo && mkdir -p _demo && cp -r cases/t3-land-permit-2025 _demo/
diff --git a/README.md b/README.md
index 4bd5e9e0..6b97ba71 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
"효과 있었다", "실패했다"는 말이 나올 때 **진짜 효과인지 확인하는 장치**입니다. 정책을 받은 동네와 안 받은 동네를 공공데이터로 비교하고, 데이터가 모르면 "판단 불가"라고 정직하게 말합니다. 질문부터 데이터·계보·분석·대시보드까지 전부 오픈소스입니다.
-🔎 **[정책 이름으로 찾기](https://causalinferencelab.github.io/policy-effect-analytics-agent/search.html)** — 이미 확인한 결과와 판정, 쓸 수 있는 공공데이터, 데이터 계보가 한 번에 나옵니다. 결과가 없으면 그 자리에서 분석을 요청할 수 있습니다.
+🔎 **[정책 이름으로 찾기](https://causalinferencelab.github.io/policy-effect-analytics-agent/search.html)** — 이미 확인한 결과와 판정, 쓸 수 있는 공공데이터, 데이터 계보가 한 번에 나옵니다. 결과가 없으면 그 자리에서 분석을 요청할 수 있습니다. **뉴스 문장을 통째로 붙여 넣으면** 그 문장이 결과로 뒷받침되는지(뒷받침 · 범위 안 · 결과를 넘어섬 · 결과와 다름) 보여 줍니다.
[](https://causalinferencelab.github.io/policy-effect-analytics-agent/)
[](https://causalinferencelab.github.io/policy-effect-analytics-agent/results.html)
@@ -33,6 +33,7 @@
| **궁금한 시민** | [검색](https://causalinferencelab.github.io/policy-effect-analytics-agent/search.html)에 정책 이름 넣기, 또는 [사이트](https://causalinferencelab.github.io/policy-effect-analytics-agent/) 대화창에 물어보기. 주제·데이터·조심할 점을 같이 정리해 줍니다 |
| **기자 · 공무원 · 연구자** | [분석 결과](https://causalinferencelab.github.io/policy-effect-analytics-agent/results.html)에서 판정과 그대로 가져다 써도 되는 인용문, 쓴 데이터, CSV를 받기 |
| **분석가 · 개발자** | 아래 [5분 만에 돌려 보기](#5분-만에-돌려-보기) → [참여 가이드](docs/ops/mentee-guide.md). 공개 API(`api/*.json`)로 서비스를 만들어도 좋습니다 |
+| **인과추론을 하는 사람** | `make draft Q="질문"`으로 가설·데이터 점검과 plan.yaml 초안, `make pywhy`로 [PyWhy(DoWhy)](https://github.com/py-why/dowhy)·[CausalML](https://github.com/uber/causalml) 두 번째 의견(식별·반박 검정·단위별 효과)을 붙이기 |
## 지금까지 만든 것
diff --git a/cases/t3-land-permit-2025/pywhy_check.json b/cases/t3-land-permit-2025/pywhy_check.json
new file mode 100644
index 00000000..d3d81c8f
--- /dev/null
+++ b/cases/t3-land-permit-2025/pywhy_check.json
@@ -0,0 +1,88 @@
+{
+ "case": "t3-land-permit-2025",
+ "status": "ok",
+ "data": {
+ "path": "cases/t3-land-permit-2025/data/panel.csv",
+ "rows": 500
+ },
+ "outcome": {
+ "col": "log_trades",
+ "name": "아파트 매매 거래건수(로그)",
+ "unit": "log 건",
+ "expected": "decrease"
+ },
+ "units": {
+ "treated": 4,
+ "control": 21
+ },
+ "did_2x2": -0.4395291160608205,
+ "baseline_estimate": -0.4033194212892391,
+ "same_direction_as_baseline": true,
+ "dowhy": {
+ "status": "ok",
+ "graph": {
+ "nodes": [
+ "T",
+ "dy",
+ "y_pre"
+ ],
+ "edges": [
+ [
+ "T",
+ "dy"
+ ],
+ [
+ "y_pre",
+ "T"
+ ],
+ [
+ "y_pre",
+ "dy"
+ ]
+ ]
+ },
+ "identification": {
+ "method": "backdoor",
+ "adjust_for": [
+ "y_pre"
+ ]
+ },
+ "estimate": -0.43955510446812324,
+ "ci": [
+ -0.47734353202397894,
+ -0.40176667691226764
+ ],
+ "refutations": [
+ {
+ "method": "placebo_treatment_refuter",
+ "label": "가짜 처치(처치 순서 섞기)",
+ "rule": "가짜 처치의 효과는 0 근처여야 해요",
+ "new_effect": 0.012393113285063689,
+ "p_value": 0.94,
+ "status": "pass"
+ },
+ {
+ "method": "random_common_cause",
+ "label": "무작위 공통 원인 추가",
+ "rule": "아무 관련 없는 변수를 넣어도 추정치가 거의 같아야 해요",
+ "new_effect": -0.4408768057224783,
+ "p_value": 0.76,
+ "status": "pass"
+ },
+ {
+ "method": "data_subset_refuter",
+ "label": "80% 부분 표본",
+ "rule": "일부 단위를 빼도 추정치가 거의 같아야 해요",
+ "new_effect": -0.4389682781910143,
+ "p_value": 0.8799999999999999,
+ "status": "pass"
+ }
+ ],
+ "warning": "처치 단위가 4곳뿐이라 회귀 신뢰구간은 참고용입니다(기본 추정은 무작위화 추론을 씁니다)"
+ },
+ "causalml": {
+ "status": "skipped",
+ "message": "처치 4곳 · 비교 21곳 — 단위별 효과는 각각 10곳 이상일 때만 봅니다"
+ },
+ "note": "두 번째 의견입니다. 판정은 plan.yaml 과 기본 추정(make flow)이 냅니다."
+}
diff --git a/catalog/projects.yaml b/catalog/projects.yaml
index d9583b71..3194bf7a 100644
--- a/catalog/projects.yaml
+++ b/catalog/projects.yaml
@@ -4,6 +4,10 @@
# plan.yaml → 계획 · fetch.py → 수집 · flow_log.json → 분석 · discussion.md(템플릿과 다르면) → 해석
# reproduced_by: [GitHub ID, ...] — 다른 참여자가 make flow 로 같은 판정을 얻었으면 재현 이슈를 확인하고 추가합니다.
# 답 페이지의 '이 결과를 얼마나 믿을 수 있나'와 카드의 '교차 재현됨' 배지로 나옵니다.
+# reviewed_by: [GitHub ID, ...] — 작성자가 아닌 사람이 docs/ops/review-checklist.md 여덟 항목을 확인했으면 추가합니다('검토됨' 배지).
+# claims: 뉴스·발표에서 나온 구체적인 주장을 이 결과로 검토했을 때만 적습니다 → 답 페이지에 팩트체크 표준 마크업(ClaimReview)
+# - text: "주장 문장 그대로" by: "말한 사람·기관" url: "주장이 실린 곳" date: YYYY-MM-DD
+# rating: "결과와 맞음" | "범위 안" | "결과를 넘어섬" | "결과와 다름" (검토한 사람이 고름)
version: 1
projects:
- case: sgim49697-ops-gangnam-bus-2024
diff --git a/core/causal/__init__.py b/core/causal/__init__.py
new file mode 100644
index 00000000..3f2e0fa2
--- /dev/null
+++ b/core/causal/__init__.py
@@ -0,0 +1,15 @@
+"""인과추론 라이브러리 연계 — PyWhy(DoWhy)와 CausalML.
+
+이 패키지는 기본 추정(core.estimators: 이중차분·이벤트 스터디·무작위화 추론)을 **대신하지 않습니다.**
+판정은 여전히 plan.yaml 과 기본 추정이 냅니다. 여기서는 세 가지를 덧붙입니다.
+
+1. feasibility 가설·데이터 점검 (추가 설치 없음)
+ "이 질문을 지금 있는 공공데이터로 분석할 수 있나?" — 처치 시점 근거 · 결과 데이터 · 공통 원인(통제) 데이터 ·
+ 공간×시간 단위가 맞는지를 카탈로그로 확인하고, PyWhy 식 인과 그래프(정책 → 결과, 공통 원인 → 둘 다)를 만든다.
+2. pywhy DoWhy 로 같은 질문을 다시 묻기 (pip install -e ".[causal]")
+ 단위별 '정책 전후 변화'로 바꾼 표에서 인과 그래프 → 식별(뒷문 기준) → 추정 → 반박 검정 3종
+ (가짜 처치 · 무작위 공통 원인 추가 · 부분 표본). 기본 추정과 방향이 같은지 본다.
+3. hte CausalML 메타러너(T-러너)로 효과가 단위마다 달랐는지 (처치·비교 단위가 각각 10곳 이상일 때만)
+
+실행: python -m core.causal cases/<케이스> → cases/<케이스>/pywhy_check.json (사이트 답 페이지에 표시)
+"""
diff --git a/core/causal/__main__.py b/core/causal/__main__.py
new file mode 100644
index 00000000..5ccac5fe
--- /dev/null
+++ b/core/causal/__main__.py
@@ -0,0 +1,47 @@
+"""python -m core.causal cases/<케이스> [--data 분석용표.csv] [--no-write]"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+
+from .pywhy import check_case, write
+
+
+def main(argv=None) -> int:
+ ap = argparse.ArgumentParser(description="PyWhy(DoWhy)·CausalML 두 번째 의견")
+ ap.add_argument("case")
+ ap.add_argument("--data", default=None)
+ ap.add_argument("--no-write", action="store_true")
+ a = ap.parse_args(argv)
+ r = check_case(a.case, a.data)
+ if r["status"] != "ok":
+ print(r.get("message", r["status"]), file=sys.stderr)
+ return 1
+ dw, ml = r["dowhy"], r["causalml"]
+ print(
+ f"[{r['case']}] {r['outcome']['name']} · 처치 {r['units']['treated']} / 비교 {r['units']['control']}"
+ )
+ print(f" 2×2 이중차분 {r['did_2x2']:+.4g} · 기본 추정 {r['baseline_estimate']}")
+ if dw["status"] == "ok":
+ print(
+ f" DoWhy 추정 {dw['estimate']:+.4g} (보정: {', '.join(dw['identification']['adjust_for'])})"
+ )
+ for x in dw["refutations"]:
+ print(f" - {x['label']}: {x.get('status')} (새 추정 {x.get('new_effect')})")
+ else:
+ print(" DoWhy:", dw.get("message"))
+ print(
+ " CausalML:",
+ ml.get("message") or f"ATE {ml['ate']:+.4g}, 단위별 효과 p10~p90 {ml['cate_quantiles']}",
+ )
+ if not a.no_write:
+ print(" 저장:", write(a.case, r))
+ else:
+ print(json.dumps(r, ensure_ascii=False, indent=1, default=str)[:400])
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/core/causal/draft.py b/core/causal/draft.py
new file mode 100644
index 00000000..3160c25e
--- /dev/null
+++ b/core/causal/draft.py
@@ -0,0 +1,187 @@
+"""질문 한 줄 → 가설·데이터 점검 → plan.yaml 초안 (사람이 승인하는 에이전트의 첫 단계).
+
+ python -m core.causal.draft "서울 토허제 확대 뒤 옆 동네 집값이 올랐나" # 화면에만
+ python -m core.causal.draft "…" --case gildong-ltp-spillover --write # cases/<케이스>/plan.yaml
+
+하는 일
+ 1. 질문을 주제·지금 이슈에 맞춘다 (core.discovery.match — 키워드 점수, 지어내지 않음)
+ 2. 그 주제의 가설·데이터 점검(feasibility)을 붙인다 — 처치 시점 근거, 결과·통제 데이터, 단위
+ 3. 스키마(core.schema.plan)를 통과하는 plan.yaml 초안을 만든다. 사람이 확인해야 할 칸은 'TODO' 주석.
+ 시행일은 지금 이슈(issues.yaml)의 공식 시행일만 쓰고, 없으면 TODO 로 남긴다.
+ 4. --write 는 새 폴더에만 쓴다(있으면 멈춤). 데이터는 받지 않는다 — fetch.py 는 사람이 쓴다.
+
+LLM 은 쓰지 않는다. 숫자·날짜·데이터 id 는 전부 카탈로그에서 온다.
+"""
+
+from __future__ import annotations
+
+import argparse
+import re
+import sys
+from pathlib import Path
+
+import yaml
+
+from core.discovery.catalog import ROOT, load_catalog, load_topics
+from core.discovery.match import match_topic
+from core.discovery.ontology import load_datasets, load_issues
+
+from .feasibility import topic_feasibility
+
+DESIGN_METHOD = {
+ "did_simultaneous": "event_study",
+ "did_staggered": "event_study",
+ "scm": "did",
+ "its": "its",
+}
+
+
+def _q(s: str) -> str:
+ return '"' + str(s).replace("\\", "\\\\").replace('"', '\\"') + '"'
+
+
+def draft(question: str, case_id: str = "gildong-topic") -> dict:
+ topics = load_topics()
+ m = match_topic(question, topics, load_catalog())
+ if not m:
+ return {
+ "matched": False,
+ "message": "주제를 찾지 못했어요. 정책 이름·지역을 넣어 다시 물어보세요.",
+ }
+ topic = m[0].topic
+ datasets, issues = load_datasets(), load_issues()
+ feas = topic_feasibility(topic, datasets, issues)
+ my_issues = [i for i in issues if i.topic == topic.id]
+ qn = re.sub(r"\s+", "", question)
+ issue = max(
+ my_issues,
+ key=lambda i: sum(w in qn for w in re.findall(r"[가-힣A-Za-z0-9]{2,}", i.name)),
+ default=None,
+ )
+ ds = [d for d in datasets if topic.id in d.topics]
+ outs = sorted(
+ [d for d in ds if "outcome" in d.roles],
+ key=lambda d: (
+ d.id not in (issue.datasets if issue else []),
+ d.approval not in {"즉시", "자동승인", "없음"},
+ ),
+ )
+ covs = [d for d in ds if "covariate" in d.roles][:2]
+ when = issue.effective if issue else None
+ monthly = any(("월" in d.time) for d in outs[:1])
+ t_col, freq = ("month", "month") if monthly else ("year", "year")
+ treat_time = (when[:7] if monthly else int(when[:4])) if when else None
+ expected = "unknown"
+ lines = [
+ "# 질문에서 만든 plan.yaml 초안 (python -m core.causal.draft) — 데이터를 보기 전에 TODO 를 채우고 PR 로 사전 등록하세요.",
+ f"# 원래 질문: {question}",
+ f"# 가설·데이터 점검: {feas['label']} — "
+ + " · ".join(f"{c['label']} {c['status']}" for c in feas["checks"]),
+ f"case_id: {case_id}",
+ f"title: {_q((issue.name if issue else topic.name) + ' 효과 분석')}",
+ "question: >",
+ f" {question.strip()}",
+ "synthetic_data: false",
+ "",
+ "unit: {name: 시군구, id_col: region_id} # TODO: 결과 데이터의 공간 단위에 맞추기",
+ f"time: {{col: {t_col}, freq: {freq}, start: TODO, end: TODO}} # TODO: 정책 전 최소 3시점"
+ if not when
+ else f"time: {{col: {t_col}, freq: {freq}, start: {_q(str(int(when[:4]) - 3) + (when[4:7] if monthly else '')) if monthly else int(when[:4]) - 3}, end: {_q(when[:4] + '-12') if monthly else int(when[:4]) + 2}}} # TODO: 기간 확인",
+ "",
+ "treatment:",
+ f" definition: {_q(issue.treatment if issue else 'TODO: 정책을 받은 곳과 시점')}",
+ " group_col: treated",
+ f" treat_time: {_q(treat_time) if isinstance(treat_time, str) else treat_time if treat_time else 'TODO # 공식 시행일'}",
+ "control:",
+ f" definition: {_q(issue.control if issue else 'TODO: 같은 기간 정책을 받지 않은 곳')}",
+ ' rationale: "TODO: 정책 전 추세가 나란했다고 볼 이유 (결과를 보고 고르지 않기)"',
+ "",
+ "outcomes:",
+ f" - name: {_q(issue.outcomes[0] if issue and issue.outcomes else (outs[0].measures[0] if outs and outs[0].measures else '주요 결과 지표'))}",
+ " col: outcome",
+ ' definition: "TODO: 분자/분모/기간까지 조작적으로"',
+ " primary: true",
+ f" expected_direction: {expected} # TODO: increase | decrease (데이터 보기 전에)",
+ "",
+ "estimator:",
+ f" method: {DESIGN_METHOD.get(issue.design, 'event_study') if issue else 'event_study'}",
+ " cluster_col: region_id",
+ f" covariates: [] # 공통 원인 후보(인과 그래프): {', '.join(d.name for d in covs) or '없음'}",
+ "",
+ "assumptions:",
+ " - name: 평행추세",
+ ' description: "정책이 없었다면 두 집단의 추세는 같았을 것"',
+ " check: pretrend_test",
+ " - name: 동시 정책 없음",
+ f" description: {_q(issue.pitfalls[0] if issue and issue.pitfalls else '같은 시점에 결과에 영향을 준 다른 정책이 없음')}",
+ " check: manual",
+ "",
+ "refutations:",
+ " - kind: placebo_time",
+ " params: {shift: 2}",
+ "",
+ "abstention:",
+ " - when: pretrend_rejected",
+ " verdict: not_identified",
+ " - when: few_treated_clusters",
+ " verdict: conditional",
+ " - when: ci_crosses_zero",
+ " verdict: conditional",
+ "",
+ "data_sources:",
+ ]
+ for d in (outs[:2] + covs) or []:
+ lic = d.license if d.license.startswith("KOGL") or d.license == "other" else "other"
+ lines += [
+ f" - name: {_q(d.name)}",
+ f" provider: {_q(d.provider)}",
+ f" url: {_q(d.url)}",
+ f" license: {lic} # 카탈로그: {d.license}",
+ f" notes: {_q('역할: ' + '/'.join(d.roles) + ' · 단위: ' + d.space + ' × ' + d.time)}",
+ ]
+ if not (outs or covs):
+ lines += [' - name: "TODO"', ' provider: "TODO"', " license: other"]
+ text = "\n".join(lines) + "\n"
+ return {
+ "matched": True,
+ "topic": topic.id,
+ "issue": issue.id if issue else None,
+ "feasibility": feas,
+ "plan_yaml": text,
+ "todo": text.count("TODO"),
+ }
+
+
+def write(case_id: str, text: str) -> Path:
+ case = ROOT / "cases" / case_id
+ if case.exists():
+ raise FileExistsError(f"{case} 가 이미 있어요. 다른 이름을 쓰세요")
+ case.mkdir(parents=True)
+ (case / "plan.yaml").write_text(text, encoding="utf-8")
+ return case / "plan.yaml"
+
+
+def main(argv=None) -> int:
+ ap = argparse.ArgumentParser(description="질문 → 가설·데이터 점검 → plan.yaml 초안")
+ ap.add_argument("question")
+ ap.add_argument("--case", default="gildong-topic")
+ ap.add_argument("--write", action="store_true")
+ a = ap.parse_args(argv)
+ r = draft(a.question, a.case)
+ if not r["matched"]:
+ print(r["message"], file=sys.stderr)
+ return 1
+ f = r["feasibility"]
+ print(f"주제: {r['topic']} · 이슈: {r['issue'] or '없음'} · 판정: {f['label']}")
+ print(f"가설: {f['hypothesis']['sentence']}")
+ for c in f["checks"]:
+ print(f" [{c['status']:>4}] {c['label']} — {c['detail']}")
+ print(f"\n--- plan.yaml 초안 (TODO {r['todo']}곳) ---\n{r['plan_yaml']}")
+ if a.write:
+ print("저장:", write(a.case, r["plan_yaml"]))
+ yaml.safe_load(r["plan_yaml"]) # 최소한 YAML 로 읽혀야 한다
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/core/causal/feasibility.py b/core/causal/feasibility.py
new file mode 100644
index 00000000..7375b4e7
--- /dev/null
+++ b/core/causal/feasibility.py
@@ -0,0 +1,206 @@
+"""가설·데이터 점검 — "이 질문, 지금 있는 데이터로 분석할 수 있나?" (추가 설치 없음).
+
+주제(topics.yaml) 하나를 받아 카탈로그만 보고 판단한다. 데이터를 받거나 숫자를 계산하지 않는다.
+
+ 가설 정책(처치) ─▶ 결과 지표, 예상 방향
+ 점검 6개 ① 언제(처치 시점 근거) ② 누가(받은 곳·안 받은 곳) ③ 결과 데이터 ④ 공통 원인(통제) 데이터
+ ⑤ 공간 단위 ⑥ 시간 단위 — 처치 근거와 결과 데이터가 같은 단위로 만날 수 있나
+ 판정 바로 분석 가능 · 데이터 한 가지 더 필요 · 아직 어려움
+
+인과 그래프는 PyWhy(DoWhy)가 쓰는 모양(노드·화살표)으로 만든다: 정책 → 결과, 공통 원인 → 정책·결과.
+공통 원인 데이터가 있으면 뒷문(backdoor) 경로를 막을 후보가 있다는 뜻이고, 없으면 이중차분의
+'정책 전 추세가 나란했다'는 가정에 더 기대야 한다는 뜻이다.
+"""
+
+from __future__ import annotations
+
+import re
+
+READY = {"즉시", "자동승인", "없음"}
+SPACE = [ # 굵은 단위 → 세밀한 단위
+ ("전국", 0),
+ ("시도", 1),
+ ("시군구", 2),
+ ("자치구", 2),
+ ("시군", 2),
+ ("읍면동", 3),
+ ("법정동", 3),
+ ("행정동", 3),
+ ("상권", 4),
+ ("지점", 4),
+ ("도로", 4),
+ ("개별", 5),
+]
+SPACE_KO = {0: "전국", 1: "시도", 2: "시군구", 3: "읍면동", 4: "지점·상권", 5: "개별 건"}
+TIME = [
+ ("연", 0),
+ ("반기", 1),
+ ("분기", 1),
+ ("월", 2),
+ ("주", 3),
+ ("일", 4),
+ ("시간", 5),
+ ("실시간", 5),
+]
+TIME_KO = {0: "연", 1: "분기", 2: "월", 3: "주", 4: "일", 5: "시간"}
+GATE_OK = {"pass": "ok", "check": "warn", "key": "warn", "fail": "miss"}
+
+
+def space_level(text: str) -> int | None:
+ """데이터셋 space 글 → 단위 단계. 시군구(법정동)처럼 둘이면 더 세밀한 쪽."""
+ hits = [lv for k, lv in SPACE if k in (text or "")]
+ return max(hits) if hits else None
+
+
+def time_level(text: str) -> int | None:
+ t = text or ""
+ if "실시간" in t:
+ return 5
+ hits = [lv for k, lv in TIME if re.search(rf"(^|[^가-힣]){k}($|[^가-힣])", t) or t == k]
+ return max(hits) if hits else None
+
+
+def _ready(d) -> bool:
+ return d.approval in READY or "자동승인" in d.approval or d.approval.startswith("없음")
+
+
+def topic_feasibility(topic, datasets, issues=(), n_results: int = 0) -> dict:
+ ds = [d for d in datasets if topic.id in d.topics]
+ by = {r: [d for d in ds if r in d.roles] for r in ("treatment", "outcome", "covariate")}
+ outs_ready = [d for d in by["outcome"] if _ready(d)]
+ my_issues = [i for i in issues if i.topic == topic.id]
+ legal = bool(topic.legal and (topic.legal.laws or topic.legal.admin_rules))
+ events = list(getattr(topic, "events", []) or [])
+
+ checks: list[dict] = []
+
+ def add(key, status, label, detail):
+ checks.append({"key": key, "status": status, "label": label, "detail": detail})
+
+ gates = topic.gates
+ when_src = []
+ if my_issues:
+ when_src.append(f"지금 이슈 {len(my_issues)}개의 공식 시행일")
+ if legal:
+ when_src.append("법제처 법령·행정규칙 개정일")
+ if events:
+ when_src.append(f"정리된 정책 사건 {len(events)}개")
+ if by["treatment"]:
+ when_src.append(f"처치 데이터 {len(by['treatment'])}개")
+ g = gates.get("when")
+ st = GATE_OK.get(g.status, "warn") if g else ("ok" if when_src else "miss")
+ if not when_src:
+ st = "miss"
+ add(
+ "when",
+ st,
+ "언제 시작했나 (처치 시점)",
+ ", ".join(when_src) or "시행일 근거를 아직 못 찾았어요",
+ )
+ g = gates.get("who")
+ add(
+ "who",
+ GATE_OK.get(g.status, "warn") if g else "warn",
+ "누가 받았고 누가 안 받았나 (비교 대상)",
+ (g.note if g and g.note else "받은 곳과 안 받은 곳을 나눌 기준을 확인해야 해요"),
+ )
+ if outs_ready:
+ add(
+ "what",
+ "ok",
+ "무엇으로 재나 (결과 데이터)",
+ f"결과 데이터 {len(by['outcome'])}개 중 {len(outs_ready)}개는 오늘 받을 수 있어요",
+ )
+ elif by["outcome"]:
+ add(
+ "what",
+ "warn",
+ "무엇으로 재나 (결과 데이터)",
+ f"결과 데이터 {len(by['outcome'])}개 — 키 발급·신청이 필요해요",
+ )
+ else:
+ add(
+ "what", "miss", "무엇으로 재나 (결과 데이터)", "결과를 잴 공공데이터를 아직 못 찾았어요"
+ )
+ add(
+ "confounders",
+ "ok" if by["covariate"] else "warn",
+ "공통 원인 (통제 데이터)",
+ f"인구·기상 같은 통제 데이터 {len(by['covariate'])}개 — 인과 그래프의 뒷문 경로를 막을 후보"
+ if by["covariate"]
+ else "통제 데이터가 없어요. '정책 전 추세가 나란했다'는 가정에 더 기대야 해요",
+ )
+ # 단위: 결과 데이터가 처치 근거와 만날 수 있는 가장 세밀한 단위
+ o_space = [lv for d in by["outcome"] if (lv := space_level(d.space)) is not None]
+ o_time = [lv for d in by["outcome"] if (lv := time_level(d.time)) is not None]
+ # 정책은 지역 단위로 배정된다 — 처치 자료가 개별 건이어도 읍면동보다 세밀하게 나누지 않는다
+ t_space = [min(lv, 3) for d in by["treatment"] if (lv := space_level(d.space)) is not None]
+ t_time = [lv for d in by["treatment"] if (lv := time_level(d.time)) is not None]
+ if legal or my_issues: # 법령·고시·조례 시행일은 시군구·일 단위로 나뉜다고 본다
+ t_space.append(2)
+ t_time.append(4)
+ space_common = min(max(o_space), max(t_space)) if o_space and t_space else None
+ time_common = min(max(o_time), max(t_time)) if o_time and t_time else None
+ add(
+ "space",
+ "ok"
+ if space_common is not None and space_common >= 2
+ else "warn"
+ if space_common is not None
+ else "miss",
+ "공간 단위가 맞나",
+ f"{SPACE_KO[space_common]} 단위까지 처치와 결과를 맞출 수 있어요"
+ if space_common is not None
+ else "처치·결과 데이터의 공간 단위를 확인해야 해요",
+ )
+ add(
+ "time",
+ "ok"
+ if time_common is not None and time_common >= 2
+ else "warn"
+ if time_common is not None
+ else "miss",
+ "시간 단위가 맞나",
+ f"{TIME_KO[time_common]} 단위 전후 비교가 가능해요 (정책 전 최소 3시점 필요)"
+ if time_common is not None
+ else "결과 데이터의 시간 단위를 확인해야 해요",
+ )
+ miss = sum(c["status"] == "miss" for c in checks)
+ warn = sum(c["status"] == "warn" for c in checks)
+ if miss == 0 and warn == 0:
+ verdict, label = "go", "바로 분석 가능"
+ elif miss == 0:
+ verdict, label = "warn", f"확인 {warn}가지 뒤 가능"
+ elif miss == 1:
+ verdict, label = "warn", "데이터 한 가지 더 필요"
+ else:
+ verdict, label = "stop", "아직 어려움"
+ outcome_name = (my_issues[0].outcomes[0] if my_issues and my_issues[0].outcomes else None) or (
+ by["outcome"][0].measures[0] if by["outcome"] and by["outcome"][0].measures else "결과 지표"
+ )
+ policy_name = my_issues[0].name if my_issues else f"{topic.name} 정책"
+ covs = [d.name for d in by["covariate"]][:4]
+ sentence = (
+ f"'{policy_name}'(처치)이 '{outcome_name}'(결과)을 바꿨다 — 받은 곳과 안 받은 곳의 전후 변화 차이로 확인"
+ if my_issues
+ else f"{topic.question} — 정책을 받은 곳과 안 받은 곳의 전후 변화 차이로 확인 (결과 후보: {outcome_name})"
+ )
+ return {
+ "topic": topic.id,
+ "hypothesis": {
+ "question": topic.question,
+ "treatment": policy_name,
+ "outcome": outcome_name,
+ "sentence": sentence,
+ },
+ "checks": checks,
+ "verdict": verdict,
+ "label": label,
+ "n_results": n_results,
+ "graph": { # PyWhy(DoWhy) 그래프와 같은 모양: 노드 · 화살표
+ "nodes": ["정책", "결과", *[f"공통 원인: {c}" for c in covs], "시간 추세"],
+ "edges": [["정책", "결과"], ["시간 추세", "결과"]]
+ + [[f"공통 원인: {c}", "정책"] for c in covs]
+ + [[f"공통 원인: {c}", "결과"] for c in covs],
+ },
+ }
diff --git a/core/causal/pywhy.py b/core/causal/pywhy.py
new file mode 100644
index 00000000..a19e5f2a
--- /dev/null
+++ b/core/causal/pywhy.py
@@ -0,0 +1,270 @@
+"""PyWhy(DoWhy)·CausalML 로 같은 질문을 다시 묻기 — 기본 추정의 '두 번째 의견'.
+
+ 단위 × 시점 패널 ──▶ 단위별 정책 전후 변화(Δy) 표
+ T = 처치 여부(0/1)
+ Δy = 정책 뒤 평균 − 정책 전 평균 (주 지표)
+ y_pre 와 plan 의 covariates(정책 전 평균) = 공통 원인 후보
+ DoWhy 인과 그래프(공통 원인 → T, 공통 원인 → Δy, T → Δy) → 식별(뒷문 기준) → 선형 회귀 추정
+ → 반박 검정 3종: 가짜 처치(순서 섞기) · 무작위 공통 원인 추가 · 80% 부분 표본
+ CausalML T-러너로 단위별 효과(CATE) — 처치·비교가 각각 10곳 이상일 때만. 정책 전 수준(y_pre)별로 나눠 본다.
+
+Δy 의 처치-비교 차이는 2×2 이중차분과 같은 양이다(공통 원인을 넣지 않으면 정확히 같음). 그래서 기본 추정과
+방향·크기가 크게 다르면 그것 자체가 점검 신호다. 판정은 바꾸지 않는다.
+
+라이브러리는 선택 설치: pip install -e ".[causal]" (dowhy, causalml). 없으면 그 단계만 '설치 안 됨'으로 남긴다.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import warnings
+from pathlib import Path
+
+import numpy as np
+import pandas as pd
+
+MIN_HTE_UNITS = 10 # CausalML 단위별 효과: 처치·비교 각각 이 수 이상일 때만
+N_SIM = 100 # 반박 검정 반복 수
+
+
+def _num(x):
+ try:
+ v = float(x)
+ except (TypeError, ValueError):
+ return None
+ return v if math.isfinite(v) else None
+
+
+def _as_time(s: pd.Series):
+ """시점 열을 비교 가능한 값으로: 숫자면 숫자, 아니면 날짜."""
+ num = pd.to_numeric(s, errors="coerce")
+ if num.notna().all():
+ return num
+ return pd.to_datetime(s, errors="coerce")
+
+
+def unit_changes(plan, df: pd.DataFrame, outcome_col: str | None = None) -> pd.DataFrame:
+ """패널 → 단위별 [T, dy, y_pre, <공변량 정책 전 평균>]. 처치 시점은 단위별 first_treat 또는 treat_time."""
+ uid, tcol = plan.unit.id_col, plan.time.col
+ y = outcome_col or plan.primary_outcome.col
+ tr = plan.treatment
+ d = df[
+ [c for c in {uid, tcol, tr.group_col, y, *(tr.first_treat_col or "",)} if c in df]
+ ].copy()
+ covs = [c for c in plan.estimator.covariates if c in df.columns]
+ for c in covs:
+ d[c] = df[c]
+ d["_t"] = _as_time(d[tcol])
+ if tr.treat_time is not None:
+ cut = _as_time(pd.Series([tr.treat_time])).iloc[0]
+ d["_cut"] = cut
+ else: # 시차 도입: 처치 단위는 자기 시점, 비교 단위는 처치 시점들의 중앙값
+ ft = _as_time(df[tr.first_treat_col])
+ d["_cut"] = ft
+ med = ft.dropna().median()
+ d.loc[d["_cut"].isna(), "_cut"] = med
+ d["_post"] = d["_t"] >= d["_cut"]
+ g = d.groupby([uid, "_post"])
+ pre = g[y].mean().xs(False, level="_post")
+ post = g[y].mean().xs(True, level="_post")
+ out = pd.DataFrame({"y_pre": pre, "dy": post - pre}).dropna()
+ out["T"] = d.groupby(uid)[tr.group_col].max().reindex(out.index).astype(int)
+ for c in covs:
+ out[c] = d[~d["_post"]].groupby(uid)[c].mean().reindex(out.index)
+ return out.dropna()
+
+
+def dowhy_check(frame: pd.DataFrame, covariates: list[str], seed: int = 7) -> dict:
+ try:
+ import dowhy # noqa: F401
+ from dowhy import CausalModel
+ except ImportError:
+ return {
+ "status": "not_installed",
+ "message": 'pip install -e ".[causal]" 로 dowhy 를 설치하세요',
+ }
+ common = ["y_pre", *covariates]
+ np.random.seed(seed)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ model = CausalModel(data=frame, treatment="T", outcome="dy", common_causes=common)
+ estimand = model.identify_effect(proceed_when_unidentifiable=True)
+ est = model.estimate_effect(
+ estimand, method_name="backdoor.linear_regression", test_significance=True
+ )
+ base = _num(est.value)
+ refs = []
+ for method, kw, label, rule in (
+ (
+ "placebo_treatment_refuter",
+ {"placebo_type": "permute", "num_simulations": N_SIM},
+ "가짜 처치(처치 순서 섞기)",
+ "가짜 처치의 효과는 0 근처여야 해요",
+ ),
+ (
+ "random_common_cause",
+ {"num_simulations": N_SIM},
+ "무작위 공통 원인 추가",
+ "아무 관련 없는 변수를 넣어도 추정치가 거의 같아야 해요",
+ ),
+ (
+ "data_subset_refuter",
+ {"subset_fraction": 0.8, "num_simulations": N_SIM},
+ "80% 부분 표본",
+ "일부 단위를 빼도 추정치가 거의 같아야 해요",
+ ),
+ ):
+ try:
+ r = model.refute_estimate(estimand, est, method_name=method, random_seed=seed, **kw)
+ except Exception as ex: # 라이브러리 버전에 따라 일부 반박이 실패할 수 있다
+ refs.append(
+ {"method": method, "label": label, "status": "error", "message": str(ex)[:160]}
+ )
+ continue
+ new = _num(r.new_effect)
+ p = (
+ _num((r.refutation_result or {}).get("p_value"))
+ if isinstance(r.refutation_result, dict)
+ else None
+ )
+ if method == "placebo_treatment_refuter":
+ ok = new is not None and base is not None and abs(new) < max(abs(base), 1e-9) * 0.5
+ else:
+ ok = (
+ new is not None
+ and base is not None
+ and abs(new - base) <= max(abs(base) * 0.2, 1e-9)
+ )
+ refs.append(
+ {
+ "method": method,
+ "label": label,
+ "rule": rule,
+ "new_effect": new,
+ "p_value": p,
+ "status": "pass" if ok else "warn",
+ }
+ )
+ try:
+ backdoor = list(estimand.get_backdoor_variables())
+ except Exception:
+ backdoor = common
+ try:
+ ci = [_num(v) for v in np.ravel(est.get_confidence_intervals())]
+ except Exception:
+ ci = None
+ return {
+ "status": "ok",
+ "graph": {
+ "nodes": ["T", "dy", *common],
+ "edges": [["T", "dy"], *[[c, "T"] for c in common], *[[c, "dy"] for c in common]],
+ },
+ "identification": {"method": "backdoor", "adjust_for": backdoor},
+ "estimate": base,
+ "ci": ci,
+ "refutations": refs,
+ }
+
+
+def causalml_hte(frame: pd.DataFrame, covariates: list[str]) -> dict:
+ n_t, n_c = int(frame["T"].sum()), int((1 - frame["T"]).sum())
+ if min(n_t, n_c) < MIN_HTE_UNITS:
+ return {
+ "status": "skipped",
+ "message": f"처치 {n_t}곳 · 비교 {n_c}곳 — 단위별 효과는 각각 {MIN_HTE_UNITS}곳 이상일 때만 봅니다",
+ }
+ try:
+ from causalml.inference.meta import BaseTRegressor
+ from sklearn.linear_model import LinearRegression
+ except ImportError:
+ return {
+ "status": "not_installed",
+ "message": 'pip install -e ".[causal]" 로 causalml 을 설치하세요',
+ }
+ feats = ["y_pre", *covariates]
+ X = frame[feats].to_numpy(dtype=float)
+ T = frame["T"].to_numpy()
+ y = frame["dy"].to_numpy(dtype=float)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ learner = BaseTRegressor(learner=LinearRegression(), control_name=0)
+ ate, lb, ub = learner.estimate_ate(X=X, treatment=T, y=y)
+ cate = np.ravel(learner.fit_predict(X=X, treatment=T, y=y))
+ groups = []
+ q = pd.qcut(
+ frame["y_pre"], 3, labels=["정책 전 낮음", "중간", "정책 전 높음"], duplicates="drop"
+ )
+ for name, idx in frame.groupby(q, observed=True).groups.items():
+ m = frame.index.isin(idx)
+ groups.append({"group": str(name), "n": int(m.sum()), "cate_mean": _num(cate[m].mean())})
+ return {
+ "status": "ok",
+ "learner": "T-learner (LinearRegression)",
+ "features": feats,
+ "ate": _num(np.ravel([ate])[0]),
+ "ate_ci": [_num(np.ravel([lb])[0]), _num(np.ravel([ub])[0])],
+ "cate_quantiles": {
+ k: _num(np.quantile(cate, v)) for k, v in (("p10", 0.1), ("p50", 0.5), ("p90", 0.9))
+ },
+ "by_baseline": groups,
+ }
+
+
+def check_case(case_dir: str | Path, data_path: str | Path | None = None) -> dict:
+ """케이스 하나: plan.yaml + 분석용 표 → DoWhy·CausalML 점검 결과 dict."""
+ from core.schema.plan import load_plan
+
+ case = Path(case_dir)
+ plan = load_plan(case / "plan.yaml")
+ path = Path(data_path) if data_path else case / plan.data_sources[0].path
+ if not path.exists():
+ return {
+ "case": case.name,
+ "status": "no_data",
+ "message": f"{path} 가 없습니다. fetch.py 로 분석용 표를 만든 뒤 다시 실행하세요",
+ }
+ df = pd.read_csv(path)
+ o = plan.primary_outcome
+ frame = unit_changes(plan, df, o.col)
+ covs = [c for c in plan.estimator.covariates if c in frame.columns]
+ did = _num(frame.loc[frame["T"] == 1, "dy"].mean() - frame.loc[frame["T"] == 0, "dy"].mean())
+ base = None
+ log = case / "flow_log.json"
+ if log.exists():
+ try:
+ rows = json.loads(log.read_text(encoding="utf-8")).get("results") or []
+ r = next((x for x in rows if x.get("outcome") == o.col), rows[0] if rows else None)
+ base = _num((r or {}).get("estimate"))
+ except (ValueError, AttributeError):
+ base = None
+ dw = dowhy_check(frame, covs)
+ n_t = int(frame["T"].sum())
+ if dw.get("status") == "ok" and n_t < MIN_HTE_UNITS:
+ dw["warning"] = (
+ f"처치 단위가 {n_t}곳뿐이라 회귀 신뢰구간은 참고용입니다(기본 추정은 무작위화 추론을 씁니다)"
+ )
+ same_dir = None
+ if dw.get("estimate") is not None and base is not None:
+ same_dir = bool(np.sign(dw["estimate"]) == np.sign(base))
+ return {
+ "case": case.name,
+ "status": "ok",
+ "data": {"path": str(path), "rows": int(len(df))},
+ "outcome": {"col": o.col, "name": o.name, "unit": o.unit, "expected": o.expected_direction},
+ "units": {"treated": int(frame["T"].sum()), "control": int((1 - frame["T"]).sum())},
+ "did_2x2": did,
+ "baseline_estimate": base,
+ "same_direction_as_baseline": same_dir,
+ "dowhy": dw,
+ "causalml": causalml_hte(frame, covs),
+ "note": "두 번째 의견입니다. 판정은 plan.yaml 과 기본 추정(make flow)이 냅니다.",
+ }
+
+
+def write(case_dir: str | Path, result: dict) -> Path:
+ out = Path(case_dir) / "pywhy_check.json"
+ out.write_text(
+ json.dumps(result, ensure_ascii=False, indent=1, default=str) + "\n", encoding="utf-8"
+ )
+ return out
diff --git a/docs/ops/review-checklist.md b/docs/ops/review-checklist.md
new file mode 100644
index 00000000..8840e484
--- /dev/null
+++ b/docs/ops/review-checklist.md
@@ -0,0 +1,23 @@
+# 결과 검토 체크리스트
+
+사이트의 판정은 '이 데이터와 이 비교로는'이라는 조건이 붙은 답입니다. 작성자가 아닌 사람이 아래 여덟 가지를 확인하면 그 결과에 **검토됨** 배지가 붙습니다.
+검토는 결과가 맞다는 보증이 아니라, 결과가 **자기 규칙을 지켰다**는 확인입니다. 숫자를 다시 돌려 보는 것은 [교차 재현](../../.github/ISSUE_TEMPLATE/reproduction.yml)이 따로 맡습니다.
+
+| # | 확인할 것 | 어디서 보나 | 통과 기준 |
+|---|---|---|---|
+| 1 | 계획이 결과보다 먼저인가 | 답 페이지 '이 결과를 얼마나 믿을 수 있나' · `git log -- cases/<케이스>/plan.yaml` | 계획 먼저 커밋, 또는 결과 뒤 수정 이유가 discussion.md '계획에서 바뀐 것'에 있음 |
+| 2 | 처치 시점이 공식 문서로 확인되나 | plan.yaml `treatment.definition` · README | 법령·고시·보도자료·조례 중 하나의 링크 |
+| 3 | 비교 대상이 결과를 보고 고른 것이 아닌가 | plan.yaml `control.rationale` · fetch.py | 선정 규칙이 코드나 문장으로 고정돼 있음 |
+| 4 | 데이터 이용 조건이 공개에 맞나 | plan.yaml `data_sources[].license` | 공공누리 1유형·이용허락 제한 없음, 또는 원자료를 커밋하지 않음 |
+| 5 | 원자료·개인정보·키가 레포에 없나 | PR 파일 목록 | `data/`·`.env`·키 없음 |
+| 6 | 판정 문장이 판정을 넘지 않나 | discussion.md '결과를 한 문장으로' · README | '크기를 판별하지 못함'·'판단 불가'를 '효과 없음'으로 쓰지 않음, 인과 단정 없음 |
+| 7 | 한계가 적혀 있나 | discussion.md · plan.yaml `cautions` | 동시에 일어난 다른 사건, 대조군 오염, 측정 문제 중 해당하는 것 |
+| 8 | 지표 정의가 재현 가능한가 | plan.yaml `outcomes[].definition` · fetch.py | 다른 사람이 같은 표를 만들 수 있을 만큼 구체적임 |
+
+## 절차
+
+1. 결과 PR에서 위 표를 복사해 PR 리뷰 댓글에 ✅/❌로 채웁니다. ❌가 있으면 작성자가 고친 뒤 다시 봅니다.
+2. 여덟 개가 모두 ✅면 `catalog/projects.yaml`의 그 케이스에 `reviewed_by: [내 GitHub ID]`를 더하는 커밋을 같은 PR에 올립니다.
+3. 사이트가 다시 빌드되면 결과 카드·검색 판정 패널에 **검토됨**, 답 페이지 신뢰 항목에 '검토 · 통과'가 나옵니다.
+
+작성자 본인은 자기 결과를 검토할 수 없습니다. 멘토 예시도 같은 규칙을 따릅니다.
diff --git a/docs/tracks/analysis.md b/docs/tracks/analysis.md
index c3631f1e..2ddc13c2 100644
--- a/docs/tracks/analysis.md
+++ b/docs/tracks/analysis.md
@@ -38,6 +38,24 @@ make demo # 예시로 한 바퀴 먼저
| 지역마다 시작일이 다름 | 시차 도입 이중차분 | 준비 중 — 그 전까지는 같은 날 시작한 지역만 골라 1차 추정 |
| 정책 지역이 1~5곳 | 합성통제 | 준비 중 — 그 전까지는 무작위화 추론으로 1차 추정, 한계에 기록 |
+## 질문에서 계획까지, 그리고 두 번째 의견 (PyWhy · CausalML)
+
+```bash
+make draft Q="서울 토허제 전역 확대 뒤 집값이 잡혔나" # 가설·데이터 점검 + plan.yaml 초안 (화면에만)
+make draft Q="…" NEW=<내ID>-<주제> # cases/<내ID>-<주제>/plan.yaml 로 저장 (새 폴더만)
+pip install -e ".[causal]" && make pywhy CASE=cases/<내ID>-<주제> # make flow 뒤: DoWhy·CausalML 두 번째 의견
+```
+
+| 단계 | 무엇을 하나 | 어디에 보이나 |
+|---|---|---|
+| 가설·데이터 점검 (`core/causal/feasibility.py`) | 주제마다 ① 처치 시점 근거 ② 비교 대상 ③ 결과 데이터 ④ 공통 원인(통제) 데이터 ⑤ 공간 ⑥ 시간 단위를 카탈로그로 확인. PyWhy 식 인과 그래프(정책 → 결과, 공통 원인 → 둘 다) | 이슈 보드 맨 위, 검색에서 결과가 없을 때 |
+| plan.yaml 초안 (`core/causal/draft.py`) | 질문 → 주제·이슈 매칭 → 스키마를 통과하는 초안. 시행일은 `issues.yaml`의 공식 날짜만, 모르는 칸은 `TODO` | 터미널, `cases/` |
+| DoWhy (`core/causal/pywhy.py`) | 단위별 정책 전후 변화(Δy) 표 → 뒷문 기준 식별(정책 전 수준·공변량 보정) → 추정 → 반박 검정 3종(가짜 처치 · 무작위 공통 원인 · 80% 부분 표본) | 답 페이지 '두 번째 의견' |
+| CausalML | T-러너로 단위별 효과(CATE), 정책 전 수준 셋으로 나눠 평균. 처치·비교가 각각 10곳 이상일 때만 | 답 페이지 '두 번째 의견' |
+
+판정은 바꾸지 않습니다. 기본 추정(`make flow`)과 방향이 다르거나 반박 검정이 '확인 필요'면 그 자체가 discussion.md 에 적을 점검 신호입니다.
+결과는 `cases/<케이스>/pywhy_check.json` 으로 커밋하면 사이트에 나옵니다(예: `cases/t3-land-permit-2025`).
+
## 비교군을 못 찾았을 때: 관측 통계로 공개하기
정책 지역과 비교할 곳을 끝내 고르지 못했거나 시작일이 확인되지 않으면 `make flow` 대신 **관측 통계**로 공개할 수 있습니다.
diff --git a/pyproject.toml b/pyproject.toml
index 1aa891b4..f835e9ff 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -24,7 +24,7 @@ dependencies = [
[project.optional-dependencies]
agent = ["langgraph>=0.2", "langchain-core>=0.3"]
-causal = ["dowhy>=0.12"]
+causal = ["dowhy>=0.12", "causalml>=0.15", "networkx<3.5"] # PyWhy·CausalML 두 번째 의견: python -m core.causal · networkx<3.5: causalml 0.18 이 고정하는 dowhy 0.12 가 nx.d_separated 를 씀
dev = ["pytest>=8", "ruff>=0.6", "pre-commit>=3.7"]
app = ["streamlit>=1.35"]
analysis = ["holidays>=0.50"] # 탐색 분석(공휴일 달력): scripts/explore_climate_card.py # 개발용 화면(선택). 공개 사이트는 site/ 의 정적 페이지
diff --git a/scripts/refresh_trends.py b/scripts/refresh_trends.py
index 9bb3162d..510c9243 100644
--- a/scripts/refresh_trends.py
+++ b/scripts/refresh_trends.py
@@ -8,7 +8,9 @@
새 키는 NCP 'NAVER API HUB'(Search Trend)에서 발급합니다(2026.7.30부터 개발자센터 신규 신청 중단).
개발자센터에서 전에 받은 키도 2027.6.30까지 쓸 수 있어, 두 주소를 차례로 시도합니다.
네이버 결과값은 네이버 소유이므로 사이트에는 값이 아니라 '순위'만 보여 줍니다.
-둘 다 없으면 사이트는 '최근 시행·발표 순'으로 보여 주고 그렇게 표시한다.
+ 3. 뉴스 언급 — 구글 뉴스 RSS 검색(키 없음)에서 주제 키워드가 나온 최근 7일 기사 수.
+ 기사 제목·본문은 저장하지 않고 개수와 검색 링크만 남긴다.
+셋 다 없으면 사이트는 '최근 시행·발표 순'으로 보여 주고 그렇게 표시한다.
python scripts/refresh_trends.py
"""
@@ -161,6 +163,51 @@ def fetch_naver(topics) -> dict[str, float] | None:
return combine_batches(batches, anchor["groupName"])
+# ─── 3. 뉴스 언급 (구글 뉴스 RSS, 키 없음) ──────────────────────────────────────
+NEWS_RSS = "https://news.google.com/rss/search"
+NEWS_DAYS = 7
+
+
+def news_query(t) -> str:
+ return " OR ".join(f'"{k}"' for k in t.keywords[:3]) + f" when:{NEWS_DAYS}d"
+
+
+def news_link(t) -> str:
+ from urllib.parse import urlencode
+
+ return "https://news.google.com/search?" + urlencode(
+ {"q": news_query(t), "hl": "ko", "gl": "KR", "ceid": "KR:ko"}
+ )
+
+
+def count_rss_items(xml_text: str) -> int:
+ import xml.etree.ElementTree as ET
+
+ try:
+ return len(ET.fromstring(xml_text).findall("./channel/item"))
+ except ET.ParseError:
+ return 0
+
+
+def fetch_news(topics) -> dict[str, int] | None:
+ import time
+
+ out: dict[str, int] = {}
+ for t in topics:
+ r = requests.get(
+ NEWS_RSS,
+ params={"q": news_query(t), "hl": "ko", "gl": "KR", "ceid": "KR:ko"},
+ headers={
+ "User-Agent": "policy-effect-analytics-agent (+https://github.com/CausalInferenceLab/policy-effect-analytics-agent)"
+ },
+ timeout=20,
+ )
+ r.raise_for_status()
+ out[t.id] = count_rss_items(r.text)
+ time.sleep(1)
+ return out
+
+
def main() -> int:
topics = load_topics()
ids = {t.id for t in topics}
@@ -195,6 +242,19 @@ def main() -> int:
data["topics"].setdefault(t, {})["search"] = v
print("네이버 데이터랩 검색 관심도 반영")
+ try:
+ news = fetch_news(topics)
+ except requests.RequestException as e:
+ print(f"뉴스 언급 수집 실패(건너뜀): {e}")
+ news = None
+ if news is not None and any(news.values()):
+ data["sources"].append("news")
+ for t in topics:
+ d = data["topics"].setdefault(t.id, {})
+ d["news"] = news.get(t.id, 0)
+ d["news_url"] = news_link(t)
+ print("뉴스 언급 수 반영 (최근 7일)")
+
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"→ {OUT.relative_to(ROOT)} (신호: {', '.join(data['sources']) or '없음'})")
diff --git a/site/answers.py b/site/answers.py
index 7a85bc63..f238e9f7 100644
--- a/site/answers.py
+++ b/site/answers.py
@@ -287,6 +287,69 @@ def reject(reason):
}
+def _read_json(path: Path) -> dict | None:
+ try:
+ d = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ return d if isinstance(d, dict) and d.get("status") == "ok" else None
+
+
+def _f(v, digits: int = 3) -> str:
+ return "-" if v is None else f"{v:+.{digits}g}"
+
+
+def pywhy_block(e, a: dict) -> str:
+ """두 번째 의견: PyWhy(DoWhy) 식별·반박 검정, CausalML 단위별 효과 (python -m core.causal 결과)."""
+ r = a.get("pywhy")
+ if not r:
+ return (
+ " 아직 돌리지 않았어요. 분석용 표가 있으면 "
+ f'두 번째 의견 · PyWhy · CausalML
"
+ "pip install -e ".[causal]" 뒤 python -m core.causal cases/{e(a["case"])} 로 만들 수 있어요.
T-러너 평균 효과 {_f(ml.get('ate'))} {e(unit)}. 단위별 효과(10~90%): " + f"{_f(ml['cate_quantiles']['p10'])} ~ {_f(ml['cate_quantiles']['p90'])}
" + f"| 정책 전 수준 | 단위 수 | 평균 효과 |
|---|
{e(ml.get('message', '돌리지 않음'))}
" + warn = f"{e(dw['warning'])}
" if dw.get("warning") else "" + return f"""같은 질문을 인과추론 오픈소스 라이브러리로 다시 물었어요. 판정은 바꾸지 않고, 기본 추정과 어긋나는지만 봅니다.
+인과 그래프: 공통 원인 → 정책, 공통 원인 → 결과, 정책 → 결과. 뒷문 기준으로 보정한 공통 원인: {e(adj)}
+단위별 정책 전후 변화로 추정 {_f(dw.get("estimate"))} {e(unit)}{e(ci_txt)} · 2×2 이중차분 {_f(r.get("did_2x2"))} · 기본 추정 {_f(r.get("baseline_estimate"))}
+처치 {r["units"]["treated"]}곳 · 비교 {r["units"]["control"]}곳 · 만든 명령 python -m core.causal cases/{e(a["case"])} · pywhy_check.json
교차 재현을 하셨나요? 재현 기록 남기기
""" -def _usage(e, a: dict) -> str: +def primary_range(a: dict) -> dict | None: + """주 지표의 추정치·95% 범위 (로그 지표는 % 로). 문장 검증·검색 패널이 쓴다.""" + r = next( + (x for x in a["results"] if x.get("est") is not None and x.get("lo") is not None), None + ) + if not r: + return None + col, unit = r.get("col") or "", r.get("unit") + pct = interpret.is_log(col, unit) + + def tx(v): + return round((math.exp(v) - 1) * 100 if pct else v, 4) + + return { + "name": r.get("name") or col, + "est": tx(r["est"]), + "lo": tx(r["lo"]), + "hi": tx(r["hi"]), + "unit": "%" if pct else (unit or ""), + } + + +def forest_svg(e, answers: list[dict], up: str = "") -> str: + """한 주제의 결과를 한 축(%)에: 효과를 합치지 않고(설계가 다름) 범위만 나란히 놓는다. + 판단 불가는 진단용이라 그리지 않는다.""" + rows = [] + skipped = [] + for a in answers: + if a.get("execution_kind") == "descriptive_only" or a["verdict"] == "not_identified": + skipped.append(a) + continue + pr = primary_range(a) + if not pr or pr["unit"] != "%": + skipped.append(a) + continue + rows.append((a, pr)) + if len(rows) < 2: + return "" + lo = min(min(pr["lo"], 0) for _, pr in rows) + hi = max(max(pr["hi"], 0) for _, pr in rows) + span = (hi - lo) or 1 + lo, hi = lo - span * 0.06, hi + span * 0.06 + W, L, R, RH, TOP = 720, 270, 24, 40, 26 + x = lambda v: L + (v - lo) / (hi - lo) * (W - L - R) # noqa: E731 + step = 5 if span <= 40 else 10 if span <= 100 else 25 + ticks = [t for t in range(int(lo // step * step), int(hi) + step, step) if lo <= t <= hi] + H = TOP + RH * len(rows) + 8 + out = [ + f"") + note = ( + f"판단 불가·관측 통계·단위가 다른 결과 {len(skipped)}개는 함께 그리지 않았어요.
" + if skipped + else "" + ) + return ( + "각 줄은 결과 하나의 주 지표 95% 범위(점은 추정치)예요. 설계·지역·기간이 달라 숫자를 합치지 않고 나란히만 놓았어요. " + "모든 막대가 0을 지나면 '이 주제에서 큰 효과는 아직 확인되지 않았다'까지만 말할 수 있어요.
" + + "".join(out) + + note + + "{e(a["question"])}
연도별 관측값을 정리했습니다. 인과효과 추정은 실행하지 않아 정책 효과를 판단할 수 없습니다.
{author}연도별 관측값을 정리했습니다. 인과효과 추정은 실행하지 않아 정책 효과를 판단할 수 없습니다.
{takeaway_html(e, a)}{author} {_usage(e, a)}{e(t["text"])}
{e(VERDICT_PLAIN.get(a["verdict"], ""))}
+{takeaway_html(e, a)} {author}{e(auto_summary(a))}
원자료는 레포에 올리지 않습니다. 아래 명령이 공개 창구에서 직접 받아 같은 결과를 만듭니다. 각 데이터의 단위·받는 법·키 필요 여부는 데이터 지도에 있습니다.
뉴스에서 "효과 있었다", "실패했다"는 말이 나올 때, 공공데이터로 '받은 동네 vs 안 받은 동네'를 비교해 진짜 효과인지 확인하는 곳이에요. 데이터가 모른다고 하면 모른다고 말하는 것까지가 이 사이트의 규칙이에요.
- + + {flow} -로컬 Ollama는 OLLAMA_ORIGINS=https://causalinferencelab.github.io로 실행해야 브라우저에서 부를 수 있습니다.
AI도 결과를 계산하지 않습니다. 주제·데이터·계획을 함께 정리할 뿐이고, 숫자는 레포의 분석 코드가 냅니다. 법률 자문이 아닙니다.
주제마다 이슈 → 공공데이터 → 계보 → 분석 → 대시보드가 어디까지 채워졌는지 보입니다. 칸의 숫자는 개수, 빈칸은 채울 곳입니다. {basis}
{topic_html}논쟁 중인 정책을 어떤 비교로, 어떤 데이터로 볼 수 있는지 정리했습니다.
-정리한 공공데이터 {len(datasets)}개 중 {board.ready_count(datasets)}개는 키 발급 즉시 또는 키 없이 오늘 받을 수 있습니다. 데이터마다 단위·기간·받는 법·이용 조건을 적었습니다.
-코딩을 몰라도 레벨 1부터 시작할 수 있어요. 한 칸씩 올라가 보세요.
-이 사이트가 잘 쓰이고 있는지는 성과에서 매일 다시 세요.
이 사이트가 잘 쓰이고 있는지는 성과에서 매일 다시 셉니다.
""" return page("정책 효과 분석 플랫폼", body, "index.html", path="index.html") @@ -871,6 +851,34 @@ def legal_block(t) -> str: ) +FEAS_MARK = {"ok": ("✓", "go"), "warn": ("!", "warn"), "miss": ("✕", "stop")} + + +def feasibility_card(t, datasets, issues, n_results: int) -> str: + """이 주제, 지금 있는 데이터로 분석할 수 있나 — 가설 한 줄 + 점검 6개 + PyWhy 식 인과 그래프.""" + from core.causal.feasibility import topic_feasibility + + f = topic_feasibility(t, datasets, issues, n_results) + items = "".join( + f"가설 {e(f["hypothesis"]["sentence"])}
인과 그래프(PyWhy 방식) 정책 → 결과 · 시간 추세 → 결과 · 공통 원인 → 정책·결과. 공통 원인 후보: {e(cov_txt)}.
+분석용 표가 생기면 python -m core.causal cases/<케이스> 로 DoWhy 반박 검정과 CausalML 단위별 효과를 붙일 수 있어요.
{e(t.question)}
현업 개발자·분석가들이 각자 궁금했던 정책을 골라 공공데이터로 직접 비교했어요. 그림을 누르면 결과와 인용문, 따라 하는 법이 나와요.
-함께 만든 사람 {len(crew)}명. 여러분 자리도 비워 뒀어요 → 참여하기
참여자가 공공데이터로 '받은 곳 vs 안 받은 곳'을 비교한 결과예요. 판정이 '모른다'여도 말할 수 있는 범위를 함께 적었어요.
+시민 데이터 과학자 {len(crew)}명이 프로젝트 {len(mentee)}개를 함께 만들고 있어요. 참여하기
${esc(q)}` + + `
${esc(r.rules[0][0])}
비교한 분석: ${esc(r.title)}. 키워드 규칙으로 읽은 결과라, 문장의 지역·기간·지표가 이 분석과 같은지는 직접 확인하세요. 법률 자문이나 공식 팩트체크가 아니에요.
`; + box.hidden = false; + if (window.track) window.track("claim-check"); + } + function counts(hits) { + document.querySelectorAll(".sf").forEach((b) => { + const n = b.dataset.t ? hits.filter((it) => it.t === b.dataset.t).length : hits.length; + b.querySelector(".n").textContent = hits.length ? n : ""; + b.disabled = !!b.dataset.t && hits.length > 0 && n === 0; + }); } function render(q) { const qn = norm(q), tks = tokens(q); - if (!qn) { res.innerHTML = ""; none.hidden = true; verdict.hidden = true; return 0; } + idle.hidden = !!qn; + if (!qn) { res.innerHTML = ""; none.hidden = true; verdict.hidden = true; $("#claim").hidden = true; counts([]); return 0; } const hits = items.map((it) => [it, score(it, tks, qn)]).filter(([, s]) => s > 0).sort((a, b) => b[1] - a[1]).map(([it]) => it); + counts(hits); const shown = kind ? hits.filter((it) => it.t === kind) : hits; - const groups = ORDER.map((t) => [t, shown.filter((it) => it.t === t)]).filter(([, xs]) => xs.length); - res.innerHTML = groups.map(([t, xs]) => - `이 질문과 가장 가까운 분석
` + - `${esc(top.badge)} ${esc(top.sub)}
` + - `판정은 '이 데이터와 이 비교로는' 이라는 조건이 붙은 답입니다. 결과 페이지에서 쓸 수 있는 문장과 한계를 함께 보세요.` + - (results.length > 1 ? ` 비슷한 분석 ${results.length - 1}개가 더 있어요.` : "") + `
`; + verdict.className = "v-panel v-" + top.cls; + verdict.innerHTML = `${esc(top.sub)}
${esc(top.ro.text)}
판정은 '이 데이터와 이 비교로는'이라는 조건이 붙은 답이에요.
`; verdict.hidden = false; } else if (hits.length) { - verdict.innerHTML = `아직 이 정책의 효과를 잰 분석은 없어요. 대신 아래 이슈·데이터·계보로 시작할 수 있어요. ` + - `분석 요청하기
`; + const tp = hits.find((it) => it.t === "topic" && it.feas); + const MK = { ok: ["✓", "go"], warn: ["!", "warn"], miss: ["✕", "stop"] }; + const feas = tp ? `지금 있는 데이터로 분석할 수 있나 · ${esc(tp.title)}
` + + `${esc(tp.feas.label)}
` + + `${esc(tp.feas.hyp)}
이 정책의 효과를 잰 분석은 아직 없어요. 아래 이슈·데이터·계보로 시작할 수 있어요.
` + feas + + ``; verdict.hidden = false; } else verdict.hidden = true; none.hidden = hits.length > 0; @@ -94,8 +180,13 @@ const q = new URLSearchParams(location.search).get("q") || ""; input.value = q; if (q) run(q, true); - }).catch(() => { res.innerHTML = '검색 목록을 불러오지 못했어요. 새로고침해 보세요.
'; }); + }).catch(() => { res.innerHTML = '검색 목록을 불러오지 못했어요. 새로고침해 보세요.
'; }); input.addEventListener("input", () => run(input.value, false)); + document.addEventListener("keydown", (ev) => { // '/' 로 검색창에 바로 + if (ev.key === "/" && document.activeElement !== input && !/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName)) { + ev.preventDefault(); input.focus(); input.select(); + } + }); $("#sform").addEventListener("submit", (ev) => { ev.preventDefault(); run(input.value, true); }); document.querySelectorAll("[data-q]").forEach((a) => a.addEventListener("click", (ev) => { ev.preventDefault(); input.value = a.dataset.q; run(a.dataset.q, true); diff --git a/site/search.py b/site/search.py index e93babe7..8579fede 100644 --- a/site/search.py +++ b/site/search.py @@ -36,7 +36,17 @@ def _j(*parts) -> str: def index(topics, issues, datasets, answers, projects, lineages) -> list[dict]: """검색 항목 목록. kw 는 찾는 데만 쓰는 글(화면에 안 보임).""" - from answers import DESCRIPTIVE_LABEL, VERDICT, card_line + from html import escape + + from answers import ( + DESCRIPTIVE_LABEL, + VERDICT, + card_line, + primary_range, + range_glyph, + takeaway, + usage_rules, + ) from core.discovery.links import dataset_users, is_auto @@ -57,6 +67,13 @@ def index(topics, issues, datasets, answers, projects, lineages) -> list[dict]: "badge": lab, "cls": cls, "who": "멘토 예시" if a["mentor"] else f"@{a['owner']}", + "g": range_glyph(escape, a), + # 판정 패널 · 문장 검증용 + "v": "descriptive" if desc else a["verdict"], + "ro": takeaway(a), + "pr": None if desc or a["verdict"] == "not_identified" else primary_range(a), + "rules": usage_rules(a), + "rev": bool(a.get("reviewed_by")), "kw": _j(a["question"], tname.get(a["topic"]), a["owner"], a["case"]), } ) @@ -86,9 +103,18 @@ def index(topics, issues, datasets, answers, projects, lineages) -> list[dict]: "kw": _j(i.treatment, " ".join(i.outcomes), tname.get(i.topic)), } ) + from core.causal.feasibility import topic_feasibility + for t in topics: + f = topic_feasibility(t, datasets, issues, sum(a["topic"] == t.id for a in answers)) out.append( { + "feas": { + "label": f["label"], + "verdict": f["verdict"], + "hyp": f["hypothesis"]["sentence"], + "checks": [[c["status"], c["label"], c["detail"]] for c in f["checks"]], + }, "t": "topic", "title": t.name, "sub": getattr(t, "question", "") or "", @@ -147,45 +173,72 @@ def write(out_dir, items: list[dict]) -> None: ) +CLAIM_EXAMPLE = "토지거래허가구역 지정 뒤 옆 동네 집값이 20% 넘게 올랐다" + + +def hot_html(e, hot: list[dict]) -> str: + if not hot: + return "" + rows = "".join( + f'뉴스에서 본 정책 이름·지역·키워드를 넣어 보세요. 이미 확인한 분석 결과와 판정, 쓸 수 있는 공공데이터, 데이터가 이어지는 길(계보)을 한 번에 찾아 드려요.
- +뉴스 문장을 통째로 붙여 넣어도 돼요. 그 문장이 분석 결과로 뒷받침되는지 봐 드려요. +예: "{e(CLAIM_EXAMPLE)}"
그게 바로 다음 분석 거리예요. 무엇이 궁금한지 남겨 주면 참여자가 데이터부터 찾아봅니다.
분석 결과 {n_results}개 · 검색 항목 {n_items}개를 이 브라우저 안에서 찾습니다.
-검색어는 서버에 저장하지 않습니다. 이용 통계가 켜진 경우에만 숫자·이메일·주소를 지운 짧은 검색어(30자)의 횟수를 쿠키 없이 셉니다(GoatCounter, 브라우저의 '추적 안 함'을 따름). -많이 찾았는데 결과가 없던 검색어는 성과에 공개되고 다음 분석 주제의 후보가 됩니다.
+지금 찾을 수 있는 것: 분석 결과 {n_results}개를 포함해 이슈·법령·계보·공공데이터 {n_items}개.
{hot_html(e, hot or [])}검색은 이 브라우저 안에서만 합니다. 이용 통계가 켜진 경우에만 숫자·이메일·주소를 지운 30자 이내 검색어의 횟수를 쿠키 없이 셉니다(GoatCounter, '추적 안 함'을 따름). +결과가 없던 검색어는 성과에 공개되어 다음 분석 주제의 후보가 됩니다.
""" diff --git a/site/style.css b/site/style.css index d2569a0e..97051371 100644 --- a/site/style.css +++ b/site/style.css @@ -519,7 +519,7 @@ html.js:not(.calm) .lin-svg .edges path { transition: stroke-dashoffset 1.2s eas .show .who .avatar { width: 22px; height: 22px } .show-meta { margin-top: auto; display: flex; gap: 8px; align-items: center; flex-wrap: wrap } .crew { margin-top: 18px; display: flex; align-items: center; gap: 14px; flex-wrap: wrap } -.faces { display: flex } +.faces { display: flex; flex-wrap: wrap; row-gap: 6px; max-width: 100% } .faces a { margin-left: -8px } .faces a:first-child { margin-left: 0 } .faces img { width: 40px; height: 40px; border-radius: 50%; border: 3px solid var(--paper); background: var(--sunk); display: block } .faces a:hover img { transform: translateY(-3px) } @@ -537,21 +537,179 @@ details.todo[open] summary { font-weight: 700; color: var(--ink) } @media (max-width: 960px) { ol.path { grid-template-columns: repeat(2, minmax(0, 1fr)) } } @media (max-width: 560px) { ol.path { grid-template-columns: minmax(0, 1fr) } } -/* 통합 검색 */ +/* 통합 검색 — 표지 요소는 판정 패널 하나. 나머지는 조용한 목록 */ .sbox { display: flex; gap: 8px; margin: 18px 0 10px; max-width: 760px } -.sbox input { flex: 1; min-width: 0; font: inherit; font-size: 17px; padding: 13px 16px; border: 2px solid var(--ink); border-radius: 12px; background: var(--surface); color: var(--ink) } -.sbox input:focus-visible { outline: 3px solid var(--accent-soft); outline-offset: 1px } -.sbox .btn { border: 0; cursor: pointer; white-space: nowrap } -.home-search { margin-top: 22px } -.s-verdict { margin: 16px 0; border-left: 5px solid var(--accent) } -.s-group { padding: 18px 0 4px } -.s-group h2 { font-size: 17px; margin: 0 0 10px } -.s-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 320px), 1fr)); gap: 10px } -.s-item { display: flex; flex-direction: column; gap: 4px; padding: 12px 14px; background: var(--surface); border: 1px solid var(--hair); border-radius: 12px; text-decoration: none; color: inherit } -.s-item:hover { border-color: var(--ink2) } -.s-item b { color: var(--ink); line-height: 1.45 } -.s-item .s-top { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; min-height: 4px } -.s-result { border-left: 4px solid var(--accent) } +.sbox input { flex: 1; min-width: 0; font: inherit; font-size: 17px; padding: 13px 16px; border: 1px solid var(--hair); border-radius: 14px; background: var(--surface); color: var(--ink); box-shadow: 0 10px 28px -20px rgba(20, 23, 28, .45) } +.sbox input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 4px var(--accent-soft) } +.sbox .btn { border: 0; cursor: pointer; white-space: nowrap; border-radius: 14px; padding: 0 22px } +.home-search { max-width: 760px; margin: 26px 0 6px } +details.ask { margin-top: 26px; border-top: 1px solid var(--hair); padding-top: 4px } +details.ask > summary { cursor: pointer; list-style: none; padding: 14px 0; font-weight: 700; color: var(--ink); display: flex; gap: 6px 12px; flex-wrap: wrap; align-items: baseline } +details.ask > summary::-webkit-details-marker { display: none } +details.ask > summary::before { content: "+"; display: inline-grid; place-items: center; width: 22px; height: 22px; border-radius: 50%; background: var(--sunk); font-weight: 700 } +details.ask[open] > summary::before { content: "−" } +details.ask > summary span { font-weight: 400; font-size: 14px; color: var(--muted) } +@media (max-width: 560px) { .sbox { flex-direction: column } .sbox .btn { padding: 12px 22px } } + +.s-hero { padding: 64px 0 4px; max-width: 820px } +.s-hero h1 { font-size: clamp(34px, 6.2vw, 58px); line-height: 1.08; letter-spacing: -.045em; font-weight: 800; margin: 0 0 16px } +.s-hero .lede { font-size: 17px; max-width: 54ch } +.qbar { position: relative; display: grid; grid-template-columns: 52px minmax(0, 1fr) auto auto; align-items: center; margin: 28px 0 14px; + background: var(--surface); border: 1px solid var(--hair); border-radius: 20px; padding: 6px; min-height: 68px; + box-shadow: 0 1px 0 var(--hair), 0 22px 44px -30px rgba(20, 23, 28, .55); transition: border-color .15s, box-shadow .15s } +.qbar:focus-within { border-color: var(--accent); box-shadow: 0 0 0 5px var(--accent-soft), 0 22px 44px -30px rgba(20, 23, 28, .55) } +.qbar-icon { width: 22px; height: 22px; justify-self: center; fill: none; stroke: var(--muted); stroke-width: 2.2; stroke-linecap: round } +.qbar input { border: 0; background: transparent; color: var(--ink); font: inherit; font-size: clamp(17px, 2.4vw, 21px); font-weight: 700; letter-spacing: -.02em; padding: 12px 6px; min-width: 0 } +.qbar input::placeholder { color: var(--muted); font-weight: 400 } +.qbar input:focus { outline: none } +.qbar input::-webkit-search-cancel-button { cursor: pointer } +.qbar-key { font: 12px var(--mono); color: var(--muted); border: 1px solid var(--hair); border-bottom-width: 2px; border-radius: 6px; padding: 1px 7px; margin-right: 10px } +.qbar:focus-within .qbar-key { visibility: hidden } +.qbar-go { border: 0; border-radius: 14px; background: var(--ink); color: var(--paper); font: inherit; font-weight: 700; font-size: 15px; padding: 0 22px; align-self: stretch; cursor: pointer } +.qbar-go:hover { background: var(--accent); color: #fff } +.qbar-go:focus-visible, .q-chip:focus-visible, .sf:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px } +.q-examples { display: flex; flex-wrap: wrap; gap: 8px } +.q-chip { font-size: 14px; color: var(--ink2); text-decoration: none; background: var(--sunk); border-radius: 10px; padding: 7px 12px; line-height: 1.4 } +.q-chip:hover { background: var(--ink); color: var(--paper) } +@media (max-width: 640px) { + .q-examples { flex-wrap: nowrap; overflow-x: auto; margin: 0 -16px; padding: 0 16px 4px; scrollbar-width: none } + .q-chip { flex: none } + .qbar { grid-template-columns: 40px minmax(0, 1fr) auto auto; min-height: 60px } + .qbar-go { padding: 0 16px } +} + +.s-body { padding-top: 34px } +.s-filters { display: flex; gap: 2px; overflow-x: auto; border-bottom: 1px solid var(--hair); margin-bottom: 22px; scrollbar-width: none } +.sf { flex: none; border: 0; background: none; font: inherit; font-size: 14.5px; color: var(--muted); padding: 10px 12px 11px; cursor: pointer; border-bottom: 2px solid transparent; margin-bottom: -1px } +.sf .n { font-size: 12px; margin-left: 5px; color: var(--muted); font-variant-numeric: tabular-nums } +.sf:hover { color: var(--ink) } +.sf[aria-pressed=true] { color: var(--ink); font-weight: 700; border-bottom-color: var(--ink) } +.sf:disabled { opacity: .35; cursor: default } + +.v-panel { --v: var(--warn); --v-bg: var(--warn-bg); position: relative; background: var(--surface); border: 1px solid var(--hair); border-radius: 20px; + padding: 22px 26px 18px 34px; margin: 0 0 26px; overflow: hidden; animation: v-in .22s ease-out } +.v-panel::before { content: ""; position: absolute; inset: 0 auto 0 0; width: 8px; background: var(--v) } +.v-panel.v-go { --v: var(--go); --v-bg: var(--go-bg) } .v-panel.v-stop { --v: var(--stop); --v-bg: var(--stop-bg) } +.v-panel.v-info { --v: var(--accent); --v-bg: var(--accent-soft) } .v-panel.v-none { --v: var(--hair); --v-bg: var(--sunk) } +.v-head { display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap } +.v-label { font-size: 13.5px; color: var(--muted) } +.v-stamp { font-size: clamp(24px, 3.6vw, 34px); font-weight: 800; letter-spacing: -.04em; color: var(--v); line-height: 1.15 } +.v-panel.v-none .v-stamp { color: var(--ink2) } +.v-body { display: grid; grid-template-columns: minmax(0, 1fr) 280px; gap: 26px; align-items: center; margin-top: 10px } +.v-body h2 { font-size: 19px; line-height: 1.45; margin: 0 0 6px } .v-body h2 a { color: var(--ink); text-decoration: none } .v-body h2 a:hover { text-decoration: underline } +.v-body p, .v-msg { margin: 0; color: var(--ink2); font-size: 15px } +.v-glyph { background: var(--v-bg); border-radius: 14px; padding: 16px 16px 10px } +.v-glyph:empty { display: none } +.v-glyph .glyph svg { height: 46px } +.v-foot { display: flex; flex-wrap: wrap; gap: 6px 18px; margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--hair); font-size: 14.5px; align-items: baseline } +.v-foot a { font-weight: 700; color: var(--ink); text-underline-offset: 3px } +.v-foot span { color: var(--muted); margin-left: auto } +.v-note { margin: 10px 0 0; font-size: 13px; color: var(--muted) } +@keyframes v-in { from { opacity: 0; transform: translateY(6px) } } +@media (prefers-reduced-motion: reduce) { .v-panel { animation: none } } +@media (max-width: 720px) { .v-body { grid-template-columns: 1fr } .v-panel { padding: 20px 18px 16px 26px } .v-foot span { margin-left: 0 } } + +.s-group { padding: 6px 0 22px } +.s-group h2 { font-size: 15px; font-weight: 700; color: var(--ink2); margin: 0 0 10px; display: flex; gap: 8px; align-items: baseline } +.s-group h2 .n { font-size: 13px; color: var(--muted); font-weight: 400 } +.r-list { display: flex; flex-direction: column; gap: 8px } +.r-card { --v: var(--warn); display: grid; grid-template-columns: minmax(0, 1fr) 220px; gap: 20px; align-items: center; padding: 14px 18px 14px 20px; + background: var(--surface); border: 1px solid var(--hair); border-left: 4px solid var(--v); border-radius: 14px; text-decoration: none; color: inherit } +.r-card.v-go { --v: var(--go) } .r-card.v-stop { --v: var(--stop) } .r-card.v-info { --v: var(--accent) } +.r-card:hover { border-color: var(--ink2); border-left-color: var(--v) } +.r-main { display: flex; flex-direction: column; gap: 4px; align-items: flex-start; min-width: 0 } +.r-main b { color: var(--ink); line-height: 1.45 } +.r-line { color: var(--ink2); font-size: 14px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden } +.r-who { color: var(--muted); font-size: 13px } +@media (max-width: 640px) { .r-card { grid-template-columns: 1fr } } +.s-rows { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 440px), 1fr)); column-gap: 28px; border-top: 1px solid var(--hair) } +.s-row { display: grid; grid-template-columns: 52px minmax(0, 1fr) auto; gap: 12px; align-items: center; padding: 11px 4px; border-bottom: 1px solid var(--hair); text-decoration: none; color: inherit } +.s-row:hover b { color: var(--accent) } +.s-kind { font-size: 12px; color: var(--muted); text-align: center; background: var(--sunk); border-radius: 6px; padding: 2px 0 } +.t-issue .s-kind { background: var(--r-treat-bg); color: var(--r-treat) } .t-dataset .s-kind { background: var(--r-out-bg); color: var(--r-out) } +.t-lineage .s-kind { background: var(--go-bg); color: var(--go) } .t-project .s-kind { background: var(--warn-bg); color: var(--warn) } +.s-txt { min-width: 0; display: flex; flex-direction: column } +.s-txt b { font-size: 15px; line-height: 1.45; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap } +.s-txt span { font-size: 13px; color: var(--muted); overflow: hidden; text-overflow: ellipsis; white-space: nowrap } +.s-meta { font-size: 12.5px; color: var(--muted); white-space: nowrap } +.s-more summary { cursor: pointer; font-size: 14px; color: var(--ink2); padding: 10px 4px } +.s-empty { background: var(--surface); border: 1px dashed var(--hair); border-radius: 20px; padding: 26px } +.s-empty h2 { font-size: 20px; margin: 0 0 6px } +.s-idle p { color: var(--muted); font-size: 15px; margin: 0 } +.s-privacy { color: var(--muted); font-size: 13px; max-width: 74ch; margin-top: 40px; padding-top: 16px; border-top: 1px solid var(--hair) } .search-terms { display: flex; flex-wrap: wrap; gap: 6px } .search-terms .chip b { font-weight: 700; margin-left: 4px } -@media (max-width: 560px) { .sbox { flex-direction: column } } + +/* 판정 옆 '그래도 말할 수 있는 것' */ +.takeaway { margin: 12px 0; padding: 12px 16px; border-radius: 12px; background: var(--sunk) } +.takeaway span { display: block; font-size: 13px; font-weight: 700; color: var(--ink2); margin-bottom: 2px } +.takeaway p { margin: 0; font-size: 15.5px; color: var(--ink); line-height: 1.6 } + +/* 문장 검증 패널 */ +.q-hint { font-size: 14px; color: var(--muted); margin: 14px 0 0 } +.q-hint a { color: var(--ink2) } +.c-panel { --c: var(--accent); background: var(--surface); border: 1px solid var(--hair); border-top: 6px solid var(--c); border-radius: 20px; padding: 20px 26px; margin: 0 0 18px; animation: v-in .22s ease-out } +.c-panel.c-go { --c: var(--go) } .c-panel.c-warn { --c: var(--warn) } .c-panel.c-stop { --c: var(--stop) } +.c-head { display: flex; gap: 14px; align-items: baseline; flex-wrap: wrap } +.c-stamp { font-size: clamp(22px, 3.2vw, 30px); font-weight: 800; letter-spacing: -.04em; color: var(--c) } +.c-panel blockquote { margin: 12px 0; padding: 4px 0 4px 14px; border-left: 3px solid var(--hair); font-size: 17px; color: var(--ink) } +.c-parts { list-style: none; padding: 0; margin: 0 0 6px; display: flex; flex-direction: column; gap: 8px } +.c-parts li { display: flex; gap: 10px; align-items: baseline; font-size: 15px; color: var(--ink2) } +.c-parts .badge { flex: none } +@media (prefers-reduced-motion: reduce) { .c-panel { animation: none } } + +/* 홈: 최근 확인한 판정 — 같은 모양의 줄. 표지는 95% 범위 그림 */ +.vboard { display: flex; flex-direction: column; border-top: 1px solid var(--hair) } +.vb-row { --v: var(--warn); display: grid; grid-template-columns: 190px minmax(0, 1fr) 200px; gap: 22px; align-items: center; + padding: 16px 6px 16px 14px; border-bottom: 1px solid var(--hair); text-decoration: none; color: inherit; position: relative } +.vb-row.v-go { --v: var(--go) } .vb-row.v-stop { --v: var(--stop) } .vb-row.v-info { --v: var(--accent) } +.vb-row::before { content: ""; position: absolute; left: 0; top: 16px; bottom: 16px; width: 3px; border-radius: 2px; background: var(--v) } +.vb-row:hover { background: var(--surface) } +.vb-row:hover b { color: var(--accent) } +.vb-side { display: flex; flex-direction: column; gap: 6px; align-items: flex-start; min-width: 0 } +.vb-who { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; color: var(--ink2) } +.vb-who img { width: 20px; height: 20px; border-radius: 50% } +.vb-topic { font-size: 12.5px; color: var(--muted) } +.vb-main { display: flex; flex-direction: column; gap: 4px; min-width: 0 } +.vb-main b { font-size: 16px; line-height: 1.45; color: var(--ink) } +.vb-main span { font-size: 14px; color: var(--ink2); display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden } +.vb-glyph:empty { display: none } +@media (max-width: 760px) { + .vb-row { grid-template-columns: minmax(0, 1fr); gap: 8px; padding-left: 16px } + .vb-side { flex-direction: row; flex-wrap: wrap; align-items: center; gap: 6px 10px } + .vb-glyph { max-width: 240px } +} + +/* 주제별: 결과를 한 축에 */ +.forest-wrap { background: var(--surface); border: 1px solid var(--hair); border-radius: 16px; padding: 18px 20px; margin: 0 0 16px } +.forest-wrap h3 { margin: 0 0 4px } +.forest { width: 100%; height: auto; display: block; margin-top: 8px; overflow: visible } +.forest .tick { stroke: var(--hair); stroke-width: 1 } +.forest .tl { fill: var(--muted); font-size: 11px; text-anchor: middle } +.forest .zero { stroke: var(--ink); stroke-width: 1.5 } +.forest .fn { fill: var(--ink); font-size: 13px } +.forest .band { stroke-width: 7; stroke-linecap: round; stroke: var(--warn); opacity: .45 } +.forest .est { fill: var(--warn); stroke: var(--surface); stroke-width: 2 } +.forest .f-go .band { stroke: var(--go) } .forest .f-go .est { fill: var(--go) } +.forest a:hover .fn { fill: var(--accent); text-decoration: underline } + +/* 가설·데이터 점검 */ +.fz { --fz: var(--accent); background: var(--surface); border: 1px solid var(--hair); border-left: 6px solid var(--fz); border-radius: 18px; padding: 20px 24px; margin: 18px 0 8px } +.fz.go { --fz: var(--go) } .fz.warn { --fz: var(--warn) } .fz.stop { --fz: var(--stop) } +.fz-head > div { display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap } +.fz-stamp { font-size: clamp(20px, 2.8vw, 26px); font-weight: 800; letter-spacing: -.03em; color: var(--fz) } +.fz-hyp { margin: 8px 0 12px; color: var(--ink2) } +.fz-list { list-style: none; padding: 0; margin: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 300px), 1fr)); gap: 10px 22px } +.fz-list li { display: grid; grid-template-columns: 24px minmax(0, 1fr); gap: 10px; align-items: start } +.fz-list li > span:last-child { display: flex; flex-direction: column; gap: 2px } +.fz-mark { width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; font-size: 12px; font-weight: 800; color: #fff; background: var(--go) } +.fz-warn .fz-mark { background: var(--warn) } .fz-miss .fz-mark { background: var(--stop) } +.fz-graph { margin: 14px 0 0; padding-top: 12px; border-top: 1px solid var(--hair) } +.v-feas { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--hair) } +.v-feas .v-label { margin: 0 } +.v-feas-stamp { font-size: 22px; font-weight: 800; letter-spacing: -.03em; margin: 2px 0 4px } +.v-feas-stamp.c-go { color: var(--go) } .v-feas-stamp.c-warn { color: var(--warn) } .v-feas-stamp.c-stop { color: var(--stop) } +.v-checks { list-style: none; padding: 0; margin: 8px 0 0; display: flex; flex-direction: column; gap: 6px; font-size: 14.5px } +.hot-h { font-size: 16px; margin: 22px 0 8px } +.hot { margin: 0; padding-left: 22px; display: flex; flex-direction: column; gap: 6px } +.hot li a { margin-right: 10px } diff --git a/tests/test_causal.py b/tests/test_causal.py new file mode 100644 index 00000000..17d117b6 --- /dev/null +++ b/tests/test_causal.py @@ -0,0 +1,124 @@ +"""PyWhy(DoWhy)·CausalML 연계와 가설·데이터 점검. + +feasibility·draft·unit_changes 는 추가 설치 없이, DoWhy·CausalML 단계는 설치돼 있을 때만 돈다(CI 의 causal 작업). +""" + +from pathlib import Path + +import numpy as np +import pandas as pd +import pytest +import yaml + +from core.causal.draft import draft +from core.causal.feasibility import space_level, time_level, topic_feasibility +from core.causal.pywhy import check_case, unit_changes +from core.discovery.catalog import load_topics +from core.discovery.ontology import load_datasets, load_issues +from core.schema.plan import Plan, load_plan + +ROOT = Path(__file__).resolve().parents[1] +EX = ROOT / "cases" / "_example_night_clinic" + + +def test_unit_levels(): + assert ( + space_level("시군구(법정동)") == 3 + and space_level("지점(역)") == 4 + and space_level("확인필요") is None + ) + assert time_level("월") == 2 and time_level("실시간") == 5 and time_level("수시") is None + + +def test_feasibility_for_every_topic_has_six_checks_and_graph(): + ds, iss = load_datasets(), load_issues() + for t in load_topics(): + f = topic_feasibility(t, ds, iss) + assert [c["key"] for c in f["checks"]] == [ + "when", + "who", + "what", + "confounders", + "space", + "time", + ] + assert f["verdict"] in {"go", "warn", "stop"} and f["label"] + assert ["정책", "결과"] in f["graph"]["edges"] + assert f["hypothesis"]["sentence"] + + +def test_draft_is_schema_valid_and_uses_official_date(): + r = draft("서울 토허제 전역 확대 뒤 집값이 잡혔나", "gildong-ltp") + assert r["matched"] and r["issue"] == "seoul-ltp-1015-2025" + plan = Plan.model_validate(yaml.safe_load(r["plan_yaml"])) + assert plan.treatment.treat_time == "2025-10" # issues.yaml 의 공식 시행일 2025-10-20 + assert r["todo"] > 0 # 사람이 채울 칸은 남긴다 + assert draft("반려동물 등록제 효과")["matched"] is False + + +def test_unit_changes_equals_two_by_two_did(): + plan = load_plan(EX / "plan.yaml") + df = pd.read_csv(EX / "data" / "panel.csv") + f = unit_changes(plan, df) + y = plan.primary_outcome.col + post = df[plan.time.col] >= plan.treatment.treat_time + m = df.groupby([plan.treatment.group_col, post])[y].mean() + did = (m[1, True] - m[1, False]) - (m[0, True] - m[0, False]) + est = f.loc[f["T"] == 1, "dy"].mean() - f.loc[f["T"] == 0, "dy"].mean() + assert np.isclose(est, did, atol=1e-9) + assert set(f.columns) >= {"T", "dy", "y_pre"} and f["T"].sum() == 30 + + +def test_check_case_without_data_says_so(tmp_path): + case = tmp_path / "c" + case.mkdir() + (case / "plan.yaml").write_text( + (EX / "plan.yaml").read_text(encoding="utf-8"), encoding="utf-8" + ) + assert check_case(case)["status"] == "no_data" + + +def test_dowhy_and_causalml_recover_the_synthetic_effect(): + pytest.importorskip("dowhy") + pytest.importorskip("causalml") + r = check_case(EX) + assert r["status"] == "ok" and r["same_direction_as_baseline"] is True + dw, ml = r["dowhy"], r["causalml"] + assert dw["status"] == "ok" and abs(dw["estimate"] - (-5.0)) < 0.6 # 합성 데이터의 참효과 -5.0 + assert {x["status"] for x in dw["refutations"]} == {"pass"} + assert "y_pre" in dw["identification"]["adjust_for"] + assert ml["status"] == "ok" and abs(ml["ate"] - (-5.0)) < 0.6 and len(ml["by_baseline"]) == 3 + + +def test_causalml_skips_with_few_treated_units(): + from core.causal.pywhy import causalml_hte + + f = pd.DataFrame({"T": [1] * 4 + [0] * 21, "dy": np.arange(25.0), "y_pre": np.arange(25.0)}) + assert causalml_hte(f, [])["status"] == "skipped" + + +def test_committed_second_opinion_renders_on_answer_page(): + import sys + from html import escape + + sys.path.insert(0, str(ROOT / "site")) + import answers as ans + + a = {x["case"]: x for x in ans.load_answers()}["t3-land-permit-2025"] + assert a["pywhy"] and a["pywhy"]["dowhy"]["status"] == "ok" + html = ans.pywhy_block(escape, a) + assert "DoWhy" in html and "CausalML" in html and "가짜 처치" in html + + +def test_news_rss_count_parses_items(): + import importlib.util + + spec = importlib.util.spec_from_file_location("rt", ROOT / "scripts" / "refresh_trends.py") + rt = importlib.util.module_from_spec(spec) + spec.loader.exec_module(rt) + xml = "