dag_remediation_traces / generate_dag_traces.py
vkatg's picture
Upload generate_dag_traces.py
0a4f45e verified
Raw
History Blame Contribute Delete
9.38 kB
import json
import math
import os
import random
from typing import Dict, List
ACTION_CATALOG = {
"mask_direct_id": {"base_cost": 0.05, "modalities": ["text", "image"], "reduces": 0.35},
"generalize_dob": {"base_cost": 0.03, "modalities": ["text", "ehr"], "reduces": 0.12},
"suppress_geo": {"base_cost": 0.04, "modalities": ["text", "ehr"], "reduces": 0.10},
"redact_image_face": {"base_cost": 0.12, "modalities": ["image"], "reduces": 0.20},
"redact_image_tag": {"base_cost": 0.08, "modalities": ["image"], "reduces": 0.14},
"strip_audio_voice": {"base_cost": 0.15, "modalities": ["audio"], "reduces": 0.18},
"anon_audio_content": {"base_cost": 0.10, "modalities": ["audio"], "reduces": 0.12},
"drop_rare_code": {"base_cost": 0.06, "modalities": ["ehr"], "reduces": 0.09},
"k_anon_table": {"base_cost": 0.20, "modalities": ["ehr", "text"], "reduces": 0.22},
"perturb_numerics": {"base_cost": 0.07, "modalities": ["ehr"], "reduces": 0.07},
"retokenize_text": {"base_cost": 0.09, "modalities": ["text"], "reduces": 0.11},
"cross_modal_unlink": {"base_cost": 0.18, "modalities": ["text", "image", "audio", "ehr"], "reduces": 0.28},
"federated_noise": {"base_cost": 0.25, "modalities": ["text", "image", "audio", "ehr"], "reduces": 0.15},
"audit_log_purge": {"base_cost": 0.02, "modalities": ["text", "image", "audio", "ehr"], "reduces": 0.03},
}
PRECEDE = {
"retokenize_text": ["mask_direct_id"],
"k_anon_table": ["generalize_dob", "suppress_geo", "drop_rare_code"],
"cross_modal_unlink": ["redact_image_face", "strip_audio_voice", "mask_direct_id"],
"federated_noise": ["k_anon_table", "cross_modal_unlink"],
"audit_log_purge": ["federated_noise"],
"redact_image_tag": ["redact_image_face"],
"anon_audio_content": ["strip_audio_voice"],
}
RISK_THRESHOLD = 0.20
ALL_MODALITIES = ["text", "image", "audio", "ehr"]
def _score(action: str, meta: Dict, risk: float, retok: float, active: List[str], mw: Dict) -> float:
overlap = [m for m in meta["modalities"] if m in active]
if not overlap:
return 0.0
w = max(mw.get(m, 1.0) for m in overlap)
rb = 0.15 if action == "retokenize_text" and retok > 0.55 else 0.0
roi = (meta["reduces"] * w + rb) / (meta["base_cost"] + 1e-9)
return roi * math.log1p(risk * 5.0)
def _select(risk: float, retok: float, active: List[str], budget: float, mw: Dict) -> Dict:
scored = sorted(
[(a, m, _score(a, m, risk, retok, active, mw)) for a, m in ACTION_CATALOG.items() if _score(a, m, risk, retok, active, mw) > 0],
key=lambda x: -x[2],
)
selected = {}
cumcost = cumred = 0.0
target = max(0.0, risk - RISK_THRESHOLD)
for action, meta, s in scored:
if cumcost + meta["base_cost"] > budget:
continue
selected[action] = (s, meta)
cumcost += meta["base_cost"]
cumred += meta["reduces"]
if cumred >= target and cumcost >= 0.1:
break
return selected
def _build_nodes(selected: Dict) -> Dict:
nodes = {a: {"score": s, "meta": m, "deps": []} for a, (s, m) in selected.items()}
injected = []
for action in list(nodes.keys()):
for dep in PRECEDE.get(action, []):
if dep in nodes:
nodes[action]["deps"].append(dep)
elif dep in ACTION_CATALOG:
nodes[dep] = {"score": 0.01, "meta": ACTION_CATALOG[dep], "deps": [], "injected": True}
nodes[action]["deps"].append(dep)
injected.append(dep)
return nodes, injected
def _topo(nodes: Dict) -> List[str]:
visited, order = set(), []
def visit(n):
if n in visited:
return
visited.add(n)
for dep in nodes[n]["deps"]:
if dep in nodes:
visit(dep)
order.append(n)
for n in sorted(nodes.keys(), key=lambda x: -nodes[x]["score"]):
visit(n)
return order
def plan(risk: float, retok: float, active: List[str], budget: float, mw: Dict, patient_id: str) -> Dict:
if risk <= RISK_THRESHOLD:
return {
"patient_id": patient_id,
"input": {"risk_score": risk, "retok_prob": retok, "active_modalities": active, "budget": budget},
"plan": [],
"trace": {"selected_actions": [], "injected_deps": [], "topo_order": []},
"estimated_residual_risk": risk,
"total_cost": 0.0,
"status": "below_threshold",
}
selected = _select(risk, retok, active, budget, mw)
nodes, injected = _build_nodes(selected)
order = _topo(nodes)
plan_out = [
{
"action": a,
"priority": round(nodes[a]["score"], 4),
"cost": nodes[a]["meta"]["base_cost"],
"risk_delta": nodes[a]["meta"]["reduces"],
"deps": nodes[a]["deps"],
}
for a in order
]
total_red = sum(nodes[a]["meta"]["reduces"] for a in nodes)
total_cost = sum(nodes[a]["meta"]["base_cost"] for a in nodes)
residual = round(max(0.0, risk - total_red), 4)
return {
"patient_id": patient_id,
"input": {"risk_score": round(risk, 4), "retok_prob": round(retok, 4),
"active_modalities": active, "budget": budget},
"plan": plan_out,
"trace": {
"selected_actions": list(selected.keys()),
"injected_deps": injected,
"topo_order": order,
"score_breakdown": {a: round(nodes[a]["score"], 4) for a in order},
},
"estimated_residual_risk": residual,
"total_cost": round(total_cost, 4),
"status": "plan_ready" if residual <= RISK_THRESHOLD else "partial_plan",
}
def generate_record(idx: int, rng: random.Random) -> Dict:
risk = round(rng.uniform(0.05, 0.99), 4)
retok = round(rng.uniform(0.0, 1.0), 4)
n_mod = rng.randint(1, 4)
active = rng.sample(ALL_MODALITIES, n_mod)
budget = round(rng.uniform(0.4, 1.5), 2)
mw = {m: round(rng.uniform(0.8, 1.5), 2) for m in active if rng.random() < 0.4}
pid = "P-%06d" % idx
return plan(risk, retok, active, budget, mw, pid)
def main():
os.makedirs("data", exist_ok=True)
rng = random.Random(7)
train = [generate_record(i, rng) for i in range(6000)]
test = [generate_record(i, rng) for i in range(6000, 7500)]
with open("data/train.jsonl", "w") as f:
for r in train:
f.write(json.dumps(r) + "\n")
with open("data/test.jsonl", "w") as f:
for r in test:
f.write(json.dumps(r) + "\n")
hard = []
rng_hard = random.Random(42)
idx = 0
while len(hard) < 1000:
risk = round(rng_hard.uniform(0.75, 0.99), 4)
retok = round(rng_hard.uniform(0.0, 1.0), 4)
n_mod = rng_hard.randint(1, 4)
active = rng_hard.sample(ALL_MODALITIES, n_mod)
budget = round(rng_hard.uniform(0.3, 0.6), 2)
mw = {m: round(rng_hard.uniform(0.8, 1.5), 2) for m in active if rng_hard.random() < 0.4}
pid = "P-H%05d" % idx
hard.append(plan(risk, retok, active, budget, mw, pid))
idx += 1
with open("data/hard.jsonl", "w") as f:
for r in hard:
f.write(json.dumps(r) + "\n")
train_statuses = {}
for r in train:
s = r["status"]
train_statuses[s] = train_statuses.get(s, 0) + 1
hard_statuses = {}
for r in hard:
s = r["status"]
hard_statuses[s] = hard_statuses.get(s, 0) + 1
train_planned = [r for r in train if r["status"] == "plan_ready"]
hard_planned = [r for r in hard if r["status"] == "plan_ready"]
avg_actions_all_train = sum(len(r["plan"]) for r in train) / len(train)
avg_residual_all_train = sum(r["estimated_residual_risk"] for r in train) / len(train)
avg_actions_pln_train = sum(len(r["plan"]) for r in train_planned) / len(train_planned)
avg_residual_pln_train = sum(r["estimated_residual_risk"] for r in train_planned) / len(train_planned)
avg_actions_all_hard = sum(len(r["plan"]) for r in hard) / len(hard)
avg_residual_all_hard = sum(r["estimated_residual_risk"] for r in hard) / len(hard)
avg_actions_pln_hard = sum(len(r["plan"]) for r in hard_planned) / len(hard_planned)
avg_residual_pln_hard = sum(r["estimated_residual_risk"] for r in hard_planned) / len(hard_planned)
print("train: %d test: %d hard: %d" % (len(train), len(test), len(hard)))
print("train status dist:", train_statuses)
print("hard status dist:", hard_statuses)
print()
print("train avg actions -- all: %.2f planned only: %.2f" % (avg_actions_all_train, avg_actions_pln_train))
print("train avg residual -- all: %.4f planned only: %.4f" % (avg_residual_all_train, avg_residual_pln_train))
print("hard avg actions -- all: %.2f planned only: %.2f" % (avg_actions_all_hard, avg_actions_pln_hard))
print("hard avg residual -- all: %.4f planned only: %.4f" % (avg_residual_all_hard, avg_residual_pln_hard))
if __name__ == "__main__":
main()