Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions .github/ISSUE_TEMPLATE/claim-review.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
name: 뉴스 주장 검토 기록
description: 검색 화면의 '문장 검증' 결과를 실제 주장(기사·발표)의 검토 기록으로 남깁니다 → 답 페이지 팩트체크 마크업
title: "[주장 검토] "
labels: ["claim-review"]
body:
- type: markdown
attributes:
value: |
누군가 **실제로 한 주장**만 기록합니다. 검토자(작성자가 아닌 참여자)가 아래를 확인한 뒤 `catalog/projects.yaml` 의
그 케이스 `claims:` 에 한 줄을 추가하면 답 페이지에 schema.org ClaimReview 가 붙습니다.
주장 문장은 원문 그대로, 짧게(한 문장) 적어 주세요. 기사 전문을 옮기지 마세요.
- type: input
id: claim
attributes:
label: 주장 문장 (원문 그대로 한 문장)
validations:
required: true
- type: input
id: by
attributes:
label: 누가 말했나 (기관·언론사·인물)
validations:
required: true
- type: input
id: url
attributes:
label: 주장이 실린 곳 (URL)
validations:
required: true
- type: input
id: date
attributes:
label: 주장 날짜 (YYYY-MM-DD)
- type: input
id: case
attributes:
label: 비교한 분석 (cases/ 폴더 이름)
validations:
required: true
- type: input
id: auto
attributes:
label: 자동 문장 검증 결과
description: "뒷받침 · 범위 안 · 결과를 넘어섬 · 결과와 다름 — 검색 화면에서 채워집니다"
- type: dropdown
id: rating
attributes:
label: 검토자 평가 (projects.yaml claims.rating 에 그대로)
options:
- 결과와 맞음
- 범위 안
- 결과를 넘어섬
- 결과와 다름
validations:
required: true
- type: textarea
id: notes
attributes:
label: 검토 메모 — 주장과 분석의 지역·기간·지표가 같은가
1 change: 1 addition & 0 deletions .github/PULL_REQUEST_TEMPLATE.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
- [ ] `make check` (ruff + pytest)가 통과합니다
- [ ] 다른 사람의 폴더나 `core/`를 (합의 없이) 수정하지 않았습니다
- [ ] 원자료·가공 데이터 파일을 커밋하지 않았습니다 (시뮬레이션·조례 목록 제외)
- [ ] 결과 PR이면 작성자가 아닌 리뷰어가 [검토 체크리스트](docs/ops/review-checklist.md) 여덟 항목을 리뷰 댓글로 확인했습니다

## 리뷰어에게
<!-- 특히 봐줬으면 하는 부분, 막힌 부분 -->
24 changes: 24 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
76 changes: 76 additions & 0 deletions .github/workflows/plan-agent.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
name: Plan agent (작업 제안 → 가설·데이터 점검 → plan 초안 PR)

# 작업 제안 이슈가 열리거나 고쳐지면: 가설·데이터 점검과 plan.yaml 초안을 댓글로 (하나의 댓글을 계속 고침)
# 메인테이너가 'plan-approved' 라벨을 붙이면: 그 초안으로 브랜치와 PR 을 연다 — 사람이 승인하는 관문
# 이슈 본문은 믿지 않는 입력이라 셸에 넣지 않고 환경변수로만 파이썬에 넘긴다.
on:
issues:
types: [opened, edited, labeled]

permissions:
contents: read

jobs:
comment:
if: contains(github.event.issue.labels.*.name, 'case-proposal') && github.event.action != 'labeled'
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
cache-dependency-path: pyproject.toml
- run: pip install -e .
- name: Feasibility comment
env:
ISSUE_TITLE: ${{ github.event.issue.title }}
ISSUE_BODY: ${{ github.event.issue.body }}
GH_TOKEN: ${{ github.token }}
NUM: ${{ github.event.issue.number }}
run: |
python -m core.causal.issue_agent comment > comment.md
id=$(gh api "repos/$GITHUB_REPOSITORY/issues/$NUM/comments" --paginate \
--jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith("<!-- plan-agent -->"))) | .id' | head -1)
if [ -n "$id" ]; then
gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$id" -F body=@comment.md > /dev/null
else
gh api "repos/$GITHUB_REPOSITORY/issues/$NUM/comments" -F body=@comment.md > /dev/null
fi

draft-pr:
if: github.event.action == 'labeled' && github.event.label.name == 'plan-approved' && contains(github.event.issue.labels.*.name, 'case-proposal')
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
cache-dependency-path: pyproject.toml
- run: pip install -e .
- name: Write plan draft and open PR
env:
ISSUE_TITLE: ${{ github.event.issue.title }}
ISSUE_BODY: ${{ github.event.issue.body }}
GH_TOKEN: ${{ github.token }}
NUM: ${{ github.event.issue.number }}
run: |
branch="agent/plan-issue-$NUM"
git switch -c "$branch"
case=$(python -m core.causal.issue_agent write)
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add "cases/$case/plan.yaml"
git commit -m "plan($case): 작업 제안 #$NUM 에서 만든 plan.yaml 초안 (TODO 를 채운 뒤 머지)"
git push origin "$branch"
printf '작업 제안 #%s 에서 `python -m core.causal.draft` 로 만든 초안입니다.\n\n- [ ] 데이터를 보기 **전에** TODO 를 모두 채웠습니다\n- [ ] 처치 시점·비교 대상 근거를 확인했습니다\n\n이 PR 을 머지하는 것이 사전 등록입니다. Closes #%s 는 결과 PR 에서 씁니다.\n' "$NUM" "$NUM" > pr.md
if ! gh pr create --head "$branch" --title "plan($case): 질문에서 만든 초안 (#$NUM)" --body-file pr.md; then
gh api "repos/$GITHUB_REPOSITORY/issues/$NUM/comments" -f body="초안 브랜치 \`$branch\` 를 만들었어요. 저장소 설정에서 Actions 의 PR 생성이 꺼져 있어 PR 은 직접 열어 주세요." > /dev/null
fi
11 changes: 10 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -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

Expand All @@ -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/
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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://img.shields.io/badge/사이트-열기-1d4e89)](https://causalinferencelab.github.io/policy-effect-analytics-agent/)
[![분석 결과](https://img.shields.io/badge/분석_결과-보기-1e6a4d)](https://causalinferencelab.github.io/policy-effect-analytics-agent/results.html)
Expand Down Expand Up @@ -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) 두 번째 의견(식별·반박 검정·단위별 효과)을 붙이기 |

## 지금까지 만든 것

Expand Down
88 changes: 88 additions & 0 deletions cases/t3-land-permit-2025/pywhy_check.json
Original file line number Diff line number Diff line change
@@ -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)이 냅니다."
}
4 changes: 4 additions & 0 deletions catalog/projects.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions core/causal/__init__.py
Original file line number Diff line number Diff line change
@@ -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 (사이트 답 페이지에 표시)
"""
47 changes: 47 additions & 0 deletions core/causal/__main__.py
Original file line number Diff line number Diff line change
@@ -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())
Loading
Loading