Download Biomanus/experiments/graph_noise_robustness/scripts/perturb_graph.py from czty/BioOcto: direct link, hf CLI and curl.
- Browser
- Download file 5.33 kB
-
https://huggingface.co/datasets/czty/BioOcto/resolve/main/Biomanus/experiments/graph_noise_robustness/scripts/perturb_graph.py
- Command line
-
hf download hf://datasets/czty/BioOcto/Biomanus/experiments/graph_noise_robustness/scripts/perturb_graph.py
-
curl -L -o perturb_graph.py https://huggingface.co/datasets/czty/BioOcto/resolve/main/Biomanus/experiments/graph_noise_robustness/scripts/perturb_graph.py
5.33 kB
| #!/usr/bin/env python3 | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import random | |
| import shutil | |
| from collections import Counter | |
| from pathlib import Path | |
| DATATYPE_EDGE_TYPES = {"consumes", "produces", "accepts"} | |
| TRANSITION_EDGE_TYPES = {"follows", "typed_flow", "adjacent_stage"} | |
| ASSIGNMENT_EDGE_TYPES = {"implements_operation", "belongs_to_stage"} | |
| DEFAULT_TYPES = DATATYPE_EDGE_TYPES | TRANSITION_EDGE_TYPES | |
| def load_graph(graph_dir: Path): | |
| nodes = json.loads((graph_dir / "graph_nodes.json").read_text()) | |
| edges = json.loads((graph_dir / "graph_edges.json").read_text()) | |
| summary = json.loads((graph_dir / "graph_summary.json").read_text()) if (graph_dir / "graph_summary.json").exists() else {} | |
| return nodes, edges, summary | |
| def write_graph(out_dir: Path, nodes, edges, summary, metadata, source_graph_dir: Path): | |
| if out_dir.exists(): | |
| shutil.rmtree(out_dir) | |
| shutil.copytree(source_graph_dir, out_dir) | |
| (out_dir / "graph_nodes.json").write_text(json.dumps(nodes, indent=2)) | |
| (out_dir / "graph_edges.json").write_text(json.dumps(edges, indent=2)) | |
| new_summary = dict(summary) | |
| new_summary["edge_count"] = len(edges) | |
| new_summary["edge_type_counts"] = dict(Counter(e.get("type") for e in edges)) | |
| new_summary["noise_metadata"] = metadata | |
| (out_dir / "graph_summary.json").write_text(json.dumps(new_summary, indent=2, sort_keys=True)) | |
| (out_dir / "noise_metadata.json").write_text(json.dumps(metadata, indent=2, sort_keys=True)) | |
| def select_edge_indices(edges, target_types, fraction, rng): | |
| idxs = [i for i, e in enumerate(edges) if e.get("type") in target_types] | |
| rng.shuffle(idxs) | |
| n = round(len(idxs) * fraction) | |
| return set(idxs[:n]), len(idxs) | |
| def remove_edges(edges, target_types, fraction, rng): | |
| selected, eligible = select_edge_indices(edges, target_types, fraction, rng) | |
| out = [e for i, e in enumerate(edges) if i not in selected] | |
| return out, {"eligible_edges": eligible, "perturbed_edges": len(selected)} | |
| def replacement_targets(nodes): | |
| by_type = {} | |
| for node in nodes: | |
| by_type.setdefault(node.get("type"), []).append(node.get("id")) | |
| return by_type | |
| def replace_edges(nodes, edges, target_types, fraction, rng): | |
| selected, eligible = select_edge_indices(edges, target_types, fraction, rng) | |
| by_type = replacement_targets(nodes) | |
| out = [] | |
| changed = 0 | |
| for i, edge in enumerate(edges): | |
| if i not in selected: | |
| out.append(edge) | |
| continue | |
| et = edge.get("type") | |
| new = dict(edge) | |
| if et in DATATYPE_EDGE_TYPES: | |
| pool = by_type.get("datatype", []) | |
| elif et == "belongs_to_stage" or et == "adjacent_stage": | |
| pool = by_type.get("stage", []) | |
| elif et == "implements_operation": | |
| pool = by_type.get("operation", []) | |
| elif et in {"follows", "typed_flow"}: | |
| target_type = "tool" if str(edge.get("target", "")).startswith("tool:") else "operation" | |
| pool = by_type.get(target_type, []) | |
| else: | |
| pool = [] | |
| choices = [x for x in pool if x != edge.get("target")] | |
| if choices: | |
| new["target"] = rng.choice(choices) | |
| new.pop("shared_datatypes", None) | |
| changed += 1 | |
| out.append(new) | |
| return out, {"eligible_edges": eligible, "perturbed_edges": changed} | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Create corrupted typed capability graphs for robustness experiments.") | |
| parser.add_argument("--source-graph-dir", type=Path, required=True) | |
| parser.add_argument("--out-dir", type=Path, required=True) | |
| parser.add_argument("--mode", choices=["copy", "remove", "replace"], required=True) | |
| parser.add_argument("--fraction", type=float, default=0.0) | |
| parser.add_argument("--edge-groups", default="datatype,transition", help="Comma list: datatype,transition,assignment") | |
| parser.add_argument("--seed", type=int, default=20260710) | |
| args = parser.parse_args() | |
| nodes, edges, summary = load_graph(args.source_graph_dir) | |
| groups = {x.strip() for x in args.edge_groups.split(",") if x.strip()} | |
| target_types = set() | |
| if "datatype" in groups: | |
| target_types |= DATATYPE_EDGE_TYPES | |
| if "transition" in groups: | |
| target_types |= TRANSITION_EDGE_TYPES | |
| if "assignment" in groups: | |
| target_types |= ASSIGNMENT_EDGE_TYPES | |
| rng = random.Random(args.seed) | |
| if args.mode == "copy": | |
| new_edges = list(edges) | |
| stats = {"eligible_edges": 0, "perturbed_edges": 0} | |
| elif args.mode == "remove": | |
| new_edges, stats = remove_edges(edges, target_types, args.fraction, rng) | |
| else: | |
| new_edges, stats = replace_edges(nodes, edges, target_types, args.fraction, rng) | |
| metadata = { | |
| "source_graph_dir": str(args.source_graph_dir), | |
| "mode": args.mode, | |
| "fraction": args.fraction, | |
| "edge_groups": sorted(groups), | |
| "target_edge_types": sorted(target_types), | |
| "seed": args.seed, | |
| "original_edge_count": len(edges), | |
| "new_edge_count": len(new_edges), | |
| **stats, | |
| } | |
| write_graph(args.out_dir, nodes, new_edges, summary, metadata, args.source_graph_dir) | |
| print(json.dumps(metadata, indent=2, sort_keys=True)) | |
| if __name__ == "__main__": | |
| main() | |