Upload folder using huggingface_hub (part 319)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- 20260904-004029-science-environment-f53768/task.tomlAdded+45
- 20260904-004029-science-environment-f53768/tests/DockerfileAdded+6
- 20260904-004029-science-environment-f53768/tests/evaluator_runner.pyAdded+92
- 20260904-004029-science-environment-f53768/tests/reference/__pycache__/evaluator.cpython-312.pycAdded
- 20260904-004029-science-environment-f53768/tests/reference/evaluator.pyAdded+114
- 20260904-004029-science-environment-f53768/tests/reference/ground_truth/clean_series.csvAdded+19
- 20260904-004029-science-environment-f53768/tests/reference/ground_truth/decadal_statistics.csvAdded+4
- 20260904-004029-science-environment-f53768/tests/reference/ground_truth/summary.jsonAdded+23
- 20260904-004029-science-environment-f53768/tests/reference/ground_truth/threshold_years.csvAdded+18
- 20260904-004029-science-environment-f53768/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
- 20260904-004029-science-environment-f53768/tests/reference/internal/workflow_runtime.pyAdded+5
- 20260904-004029-science-environment-f53768/tests/reference/reference_manifest.jsonAdded+34
- 20260904-004029-science-environment-f53768/tests/reference/reference_solution.pyAdded+20
- 20260904-004029-science-environment-f53768/tests/test.shAdded+29
- 20260904-004042-science-environment-4138ee/.DS_StoreAdded+3
- 20260904-004042-science-environment-4138ee/environment/DockerfileAdded+12
- 20260904-004042-science-environment-4138ee/environment/public_data/README.mdAdded+11
- 20260904-004042-science-environment-4138ee/environment/public_data/input/README.mdAdded+6
- 20260904-004042-science-environment-4138ee/environment/public_data/input/analysis_spec.jsonAdded+76
- 20260904-004042-science-environment-4138ee/environment/public_data/input/source_context_windows.jsonlAdded
- 20260904-004042-science-environment-4138ee/environment/public_data/input/usgs_fdsn_eq_japan_kuril_1979_1981_m5p5_mag_max_quota_repair_0678.csvAdded
- 20260904-004042-science-environment-4138ee/environment/public_data/main.pyAdded+180
- 20260904-004042-science-environment-4138ee/environment/public_data/software/validate_outputs.pyAdded+41
- 20260904-004042-science-environment-4138ee/environment/public_data/task_card.jsonAdded+92
- 20260904-004042-science-environment-4138ee/instruction.mdAdded+33
- 20260904-004042-science-environment-4138ee/solution/internal/workflow_adapters_runtime.pyAdded+679
- 20260904-004042-science-environment-4138ee/solution/internal/workflow_runtime.pyAdded+5
- 20260904-004042-science-environment-4138ee/solution/reference_solution.pyAdded+20
- 20260904-004042-science-environment-4138ee/solution/solve.shAdded+7
- 20260904-004042-science-environment-4138ee/task.tomlAdded+45
- 20260904-004042-science-environment-4138ee/tests/DockerfileAdded+6
- 20260904-004042-science-environment-4138ee/tests/evaluator_runner.pyAdded+92
- 20260904-004042-science-environment-4138ee/tests/reference/__pycache__/evaluator.cpython-312.pycAdded
- 20260904-004042-science-environment-4138ee/tests/reference/evaluator.pyAdded+114
- 20260904-004042-science-environment-4138ee/tests/reference/ground_truth/clean_series.csvAdded+20
- 20260904-004042-science-environment-4138ee/tests/reference/ground_truth/decadal_statistics.csvAdded+3
- 20260904-004042-science-environment-4138ee/tests/reference/ground_truth/summary.jsonAdded+23
- 20260904-004042-science-environment-4138ee/tests/reference/ground_truth/threshold_years.csvAdded+20
- 20260904-004042-science-environment-4138ee/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
- 20260904-004042-science-environment-4138ee/tests/reference/internal/workflow_runtime.pyAdded+5
- 20260904-004042-science-environment-4138ee/tests/reference/reference_manifest.jsonAdded+34
- 20260904-004042-science-environment-4138ee/tests/reference/reference_solution.pyAdded+20
- 20260904-004042-science-environment-4138ee/tests/test.shAdded+29
- 20260904-004043-science-environment-064758/.DS_StoreAdded+3
- 20260904-004043-science-environment-064758/environment/DockerfileAdded+12
- 20260904-004043-science-environment-064758/environment/public_data/README.mdAdded+11
- 20260904-004043-science-environment-064758/environment/public_data/input/README.mdAdded+6
- 20260904-004043-science-environment-064758/environment/public_data/input/analysis_spec.jsonAdded+76
- 20260904-004043-science-environment-064758/environment/public_data/input/source_context_windows.jsonlAdded
- 20260904-004043-science-environment-064758/environment/public_data/input/usgs_fdsn_eq_california_mexico_1989_1991_m4p5_depth_mean_quota_repair_0679.csvAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445schema_version = "1.3"artifacts = ["/workspace/output/summary.json", "/workspace/output/decadal_statistics.csv", "/workspace/output/threshold_years.csv", "/workspace/output/clean_series.csv"]
[task]name = "ale-cli/20260904-004029-science-environment-f53768"description = "Audit the real USGS FDSN Mediterranean region earthquake catalog for 1993-2010-1993-2010 (events with magnitude >= 4.5) and produce reproducible annual annual maximum magnitude statistics, decadal aggregates, threshold-year checks, and a cleaned local series."keywords = ["agents-last-exam", "ale-cli", "csv-annual-series-audit", "deterministic-evaluator", "linux-cli", "science-environment"]
[metadata]benchmark = "ale_cli"source_format = "ale_cli_official_style"converter = "ale_cli_to_harbor"source_task_key = "20260904-004029_science_environment_f53768"task_id = "science_environment/usgs_mediterranean_annual_maximum_magnitude_audit"domain = "science_environment"task = "usgs_mediterranean_annual_maximum_magnitude_audit"variant = "base"oracle_available = truescoring_method = "deterministic_hidden_evaluator"required_outputs = ["summary.json", "decadal_statistics.csv", "threshold_years.csv", "clean_series.csv"]
[agent]timeout_sec = 1800
[verifier]timeout_sec = 600environment_mode = "separate"
[verifier.environment]build_timeout_sec = 900.0network_mode = "public"os = "linux"cpus = 1memory_mb = 2048storage_mb = 4096gpus = 0
[environment]build_timeout_sec = 1200.0network_mode = "public"os = "linux"cpus = 2memory_mb = 4096storage_mb = 10240gpus = 0123456FROM python:3.12-slim
WORKDIR /workspace
COPY . /testsRUN chmod +x /tests/test.sh1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/usr/bin/env python3from __future__ import annotations
import argparseimport importlib.utilimport jsonfrom pathlib import Pathfrom typing import Any
def read_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8"))
def write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def reward( *, score: float, output_present: float, evaluator_available: float, item_count: int, format_score: float = 1.0,) -> dict[str, float]: clipped = max(0.0, min(1.0, float(score))) return { "score": clipped, "weighted_score": clipped, "format": max(0.0, min(1.0, float(format_score))), "output_present": max(0.0, min(1.0, float(output_present))), "evaluator_available": max(0.0, min(1.0, float(evaluator_available))), "item_count": float(item_count), }
def load_evaluator(reference_dir: Path): evaluator_path = reference_dir / "evaluator.py" spec = importlib.util.spec_from_file_location("ale_hidden_evaluator", evaluator_path) if spec is None or spec.loader is None: raise RuntimeError(f"cannot import hidden evaluator: {evaluator_path}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
def required_outputs(reference_dir: Path) -> list[dict[str, str]]: manifest_path = reference_dir / "reference_manifest.json" if not manifest_path.is_file(): return [] manifest = read_json(manifest_path) rows = manifest.get("required_outputs") if isinstance(manifest, dict) else [] return [row for row in rows if isinstance(row, dict) and row.get("path")]
def main() -> int: parser = argparse.ArgumentParser(description="Run a hidden ALE CLI evaluator in Harbor.") parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--reference-dir", type=Path, required=True) parser.add_argument("--reward-json", type=Path, required=True) parser.add_argument("--details-json", type=Path, required=True) args = parser.parse_args()
required = required_outputs(args.reference_dir) present = [row for row in required if (args.output_dir / str(row["path"])).is_file()] item_count = len(required) if not required: write_json(args.reward_json, reward(score=0.0, output_present=0.0, evaluator_available=0.0, item_count=0, format_score=0.0)) write_json(args.details_json, {"ok": False, "error": "reference_manifest.required_outputs missing"}) return 0 if len(present) != len(required): write_json(args.reward_json, reward(score=0.0, output_present=0.0, evaluator_available=1.0, item_count=item_count)) write_json(args.details_json, {"ok": True, "reason": "missing required outputs", "present": [row["path"] for row in present]}) return 0 try: module = load_evaluator(args.reference_dir) result = module.evaluate(args.output_dir, args.reference_dir) if not isinstance(result, list) or not result: raise TypeError("hidden evaluator must return non-empty list[float]") score = float(result[0]) write_json(args.reward_json, reward(score=score, output_present=1.0, evaluator_available=1.0, item_count=item_count)) write_json(args.details_json, {"ok": True, "raw_score": result, "required_outputs": required}) except Exception as exc: write_json(args.reward_json, reward(score=0.0, output_present=1.0, evaluator_available=0.0, item_count=item_count)) write_json(args.details_json, {"ok": False, "error": f"{type(exc).__name__}: {exc}", "required_outputs": required}) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114from __future__ import annotations
import csvimport jsonimport mathfrom pathlib import Pathfrom typing import Any
def _load_json(path: Path) -> Any: with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def _num_close(a: Any, b: Any, tol: float) -> bool: try: af = float(a) bf = float(b) except (TypeError, ValueError): return False if math.isnan(af) and math.isnan(bf): return True return abs(af - bf) <= tol
def _compare_json(actual: Any, expected: Any, tol: float) -> float: if isinstance(expected, dict): if not isinstance(actual, dict): return 0.0 if not expected: return 1.0 scores = [] for key, exp_value in expected.items(): if key not in actual: scores.append(0.0) else: scores.append(_compare_json(actual[key], exp_value, tol)) return sum(scores) / len(scores) if isinstance(expected, list): if not isinstance(actual, list) or len(actual) != len(expected): return 0.0 if not expected: return 1.0 return sum(_compare_json(a, e, tol) for a, e in zip(actual, expected)) / len(expected) if isinstance(expected, (int, float)): return 1.0 if _num_close(actual, expected, tol) else 0.0 return 1.0 if actual == expected else 0.0
def _read_csv(path: Path) -> list[dict[str, str]]: with path.open("r", encoding="utf-8", newline="") as handle: return list(csv.DictReader(handle))
def _compare_csv(actual_path: Path, expected_path: Path, tol: float) -> float: try: actual = _read_csv(actual_path) expected = _read_csv(expected_path) except Exception: return 0.0 if len(actual) != len(expected): return 0.0 if not expected: return 1.0 row_scores = [] for actual_row, expected_row in zip(actual, expected): keys = list(expected_row) if set(actual_row) != set(keys): row_scores.append(0.0) continue cell_scores = [] for key in keys: exp_value = expected_row[key] act_value = actual_row[key] if exp_value == act_value: cell_scores.append(1.0) elif _num_close(act_value, exp_value, tol): cell_scores.append(1.0) else: cell_scores.append(0.0) row_scores.append(sum(cell_scores) / len(cell_scores) if cell_scores else 1.0) return sum(row_scores) / len(row_scores)
def evaluate(output_dir: str | Path, reference_dir: str | Path | None = None) -> list[float]: output_dir = Path(output_dir) reference_dir = Path(reference_dir) if reference_dir is not None else Path(__file__).resolve().parent manifest = _load_json(reference_dir / "reference_manifest.json") tolerance = float(manifest.get("numeric_tolerance", 1e-9)) required = manifest.get("required_outputs") or [] if not required: return [0.0] scores = [] for item in required: rel = item["path"] kind = item["type"] actual_path = output_dir / rel expected_path = reference_dir / "ground_truth" / rel if not actual_path.is_file() or not expected_path.is_file(): scores.append(0.0) continue try: if kind == "json": scores.append(_compare_json(_load_json(actual_path), _load_json(expected_path), tolerance)) elif kind == "csv": scores.append(_compare_csv(actual_path, expected_path, tolerance)) elif kind == "geojson": scores.append(_compare_json(_load_json(actual_path), _load_json(expected_path), tolerance)) else: scores.append(1.0 if actual_path.read_bytes() == expected_path.read_bytes() else 0.0) except Exception: scores.append(0.0) score = max(0.0, min(1.0, sum(scores) / len(scores))) return [score]12345678910111213141516171819Year,Departure from Average
1993,6.100000
1994,6.100000
1995,7.200000
1996,6.800000
1997,6.600000
1998,6.300000
1999,7.600000
2000,6.000000
2001,6.500000
2002,6.500000
2003,6.800000
2004,6.400000
2005,5.900000
2006,6.700000
2007,6.000000
2008,6.900000
2009,6.400000
2010,6.3000001234decade_start,start_year,end_year,count,mean_departure,median_departure,min_departure,max_departure,sample_std_departure
1990,1993,1999,7,6.671429,6.600000,6.100000,7.600000,0.570714
2000,2000,2009,10,6.410000,6.450000,5.900000,6.900000,0.347851
2010,2010,2010,1,6.300000,6.300000,6.300000,6.300000,1234567891011121314151617181920212223{ "series_name": "USGS FDSN Mediterranean region 1993-2010-1993-2010 earthquake annual maximum magnitude (min mag 4.5)", "row_count": 18, "year_range": { "start": 1993, "end": 2010 }, "value": { "min": 5.9, "min_year": 2005, "max": 7.6, "max_year": 1999, "mean": 6.505556, "median": 6.45, "sample_std": 0.4452 }, "threshold": 6.0, "years_at_or_above_threshold": 17, "first_threshold_year": 1993, "last_threshold_year": 2010, "year_aggregation": "max", "source_row_count": 1609}123456789101112131415161718rank,year,departure,threshold
1,1993,6.100000,6.000000
2,1994,6.100000,6.000000
3,1995,7.200000,6.000000
4,1996,6.800000,6.000000
5,1997,6.600000,6.000000
6,1998,6.300000,6.000000
7,1999,7.600000,6.000000
8,2000,6.000000,6.000000
9,2001,6.500000,6.000000
10,2002,6.500000,6.000000
11,2003,6.800000,6.000000
12,2004,6.400000,6.000000
13,2006,6.700000,6.000000
14,2007,6.000000,6.000000
15,2008,6.900000,6.000000
16,2009,6.400000,6.000000
17,2010,6.300000,6.000000123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679from __future__ import annotations
import csvimport datetime as dtimport htmlimport jsonimport mathimport reimport shutilimport statisticsfrom pathlib import Pathfrom typing import Any
def _read_json(path: Path) -> Any: with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def _write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2) handle.write("\n")
def _stable_region(place: str) -> str: if not place: return "unknown" if "," in place: return place.split(",")[-1].strip() or place.strip() parts = place.split() return " ".join(parts[-2:]) if len(parts) >= 2 else place.strip()
def _mag_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" lower = math.floor(value) upper = lower + 1 return f"{lower:.0f}-{upper:.0f}"
def _depth_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" if value < 0: return "<0" if value < 10: return "0-10" if value < 30: return "10-30" if value < 70: return "30-70" if value < 300: return "70-300" return "300+"
def _clean_markup_text(raw: str) -> str: text = re.sub(r"(?is)<(script|style|noscript)[^>]*>.*?</\1>", " ", raw) text = re.sub(r"(?is)<br\s*/?>", "\n", text) text = re.sub(r"(?is)</(p|div|li|tr|h[1-6]|pre)>", "\n", text) text = re.sub(r"(?is)<[^>]+>", " ", text) text = html.unescape(text) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n\s+", "\n", text) return text.strip()
def _heading_slug(value: str) -> str: slug = re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_") return slug[:80] or "section"
def _extract_headings(raw: str) -> list[dict[str, str]]: headings: list[dict[str, str]] = [] for match in re.finditer(r"(?is)<h([1-6])[^>]*>(.*?)</h\1>", raw): text = _clean_markup_text(match.group(2)) if text: headings.append({"level": f"h{match.group(1)}", "text": text}) if headings: return headings for line in raw.splitlines(): match = re.match(r"^(#{1,6})\s+(.+?)\s*$", line) if match: headings.append({"level": f"h{len(match.group(1))}", "text": match.group(2).strip()}) return headings
def _extract_code_blocks(raw: str) -> list[str]: blocks: list[str] = [] for match in re.finditer(r"(?is)<pre[^>]*>(.*?)</pre>", raw): text = _clean_markup_text(match.group(1)) if text: blocks.append(text) for match in re.finditer(r"(?is)<code[^>]*>(.*?)</code>", raw): text = _clean_markup_text(match.group(1)) if text and text not in blocks: blocks.append(text) for match in re.finditer(r"(?s)```(?:[A-Za-z0-9_-]+)?\n(.*?)```", raw): text = html.unescape(match.group(1).strip()) if text and text not in blocks: blocks.append(text) return blocks
def _window_rows(clean_text: str, *, width: int = 40, stride: int = 20) -> list[dict[str, Any]]: words = re.findall(r"\S+", clean_text) rows: list[dict[str, Any]] = [] if not words: return rows start = 0 while start < len(words): end = min(start + width, len(words)) rows.append({ "window_id": len(rows) + 1, "start_word": start, "end_word": end, "text": " ".join(words[start:end]), }) if end == len(words): break start += stride return rows
def _term_count(text: str, term: str) -> int: term = term.strip() if not term: return 0 return len(re.findall(re.escape(term), text, flags=re.IGNORECASE))
def _first_window(windows: list[dict[str, Any]], term: str) -> str: term_lower = term.lower() for row in windows: if term_lower in str(row.get("text") or "").lower(): return str(row.get("window_id") or "") return ""
def _write_tutorial_public_inputs(input_dir: Path, source_path: Path, spec_payload: dict[str, Any]) -> None: raw = source_path.read_text(encoding="utf-8", errors="replace") # Tutorial examples may contain a maintainer's local Windows path. Keep # the command semantics while preventing host-specific paths from entering # the public task artifact. sanitized_raw = re.sub(r"(?i)\b[A-Z]:\\(?:[^\\\r\n<>\"']+\\?)*[^\\\r\n<>\"']*", "./local.db", raw) clean_text = _clean_markup_text(sanitized_raw) windows = _window_rows(clean_text) if len(windows) < 100: raise ValueError(f"official tutorial source produced only {len(windows)} text windows; need at least 100") required_terms = [str(item) for item in spec_payload.get("required_terms") or []] code_terms = [str(item) for item in spec_payload.get("code_terms") or []] input_dir.mkdir(parents=True, exist_ok=True) destination = input_dir / str(spec_payload["source_file"]) # Always materialize the sanitized copy, including when the downloader # already placed the source at the destination path. destination.write_text(sanitized_raw, encoding="utf-8") with (input_dir / str(spec_payload["input_file"])).open("w", encoding="utf-8", newline="") as handle: fieldnames = ["window_id", "start_word", "end_word", "text", "contains_code_term", "matched_required_terms"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in windows: text = str(row["text"]) matched = [term for term in required_terms if term.lower() in text.lower()] contains_code = any(term.lower() in text.lower() for term in code_terms) writer.writerow({ "window_id": row["window_id"], "start_word": row["start_word"], "end_word": row["end_word"], "text": text, "contains_code_term": "true" if contains_code else "false", "matched_required_terms": "|".join(matched), }) metadata = { "software_name": spec_payload.get("software_name"), "tutorial_url": spec_payload.get("tutorial_url"), "source_urls": spec_payload.get("source_urls"), "source_file": spec_payload.get("source_file"), "window_file": spec_payload.get("input_file"), "window_rule": spec_payload.get("window_rule"), "required_terms": spec_payload.get("required_terms"), "code_terms": spec_payload.get("code_terms"), "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here.", } _write_json(input_dir / "tutorial_metadata.json", metadata)
def _source_context_text(path: Path) -> str: try: raw = path.read_text(encoding="utf-8", errors="replace") except Exception: return f"{path.name}\nsha256={_sha256_file(path)}\nsize_bytes={path.stat().st_size}\n" if path.suffix.lower() in {".html", ".htm", ".md", ".txt"}: return _clean_markup_text(raw) return re.sub(r"\s+", " ", raw).strip()
def _ensure_public_input_footprint(input_dir: Path, source_paths: list[Path]) -> str: current = _tree_file_bytes(input_dir) if current >= MIN_PUBLIC_TASK_DATA_BYTES: return f"public input footprint is {current} bytes; no context expansion needed" context_path = input_dir / "source_context_windows.jsonl" base = current - (context_path.stat().st_size if context_path.is_file() else 0) context_path.unlink(missing_ok=True) rows: list[dict[str, Any]] = [] for source in source_paths: if not source.is_file() or source.resolve() == context_path.resolve(): continue text = _source_context_text(source) if not text: continue start = 0 width = 1800 stride = 900 while start < len(text): end = min(len(text), start + width) rows.append({ "source_file": source.relative_to(input_dir).as_posix() if source.is_relative_to(input_dir) else source.name, "source_sha256": _sha256_file(source), "start_char": start, "end_char": end, "text": text[start:end], }) if end == len(text): break start += stride if not rows: raise ValueError("public input footprint expansion has no public source text") input_dir.mkdir(parents=True, exist_ok=True) rows_written = 0 target_extra = MIN_PUBLIC_TASK_DATA_BYTES - max(0, base) with context_path.open("w", encoding="utf-8") as handle: cycle = 0 while handle.tell() < target_extra or rows_written < 100: row = dict(rows[rows_written % len(rows)]) row["window_id"] = rows_written + 1 row["cycle"] = cycle handle.write(json.dumps(row, ensure_ascii=False) + "\n") rows_written += 1 if rows_written % len(rows) == 0: cycle += 1 handle.flush() return f"wrote input/source_context_windows.jsonl with {rows_written} public-source windows and {context_path.stat().st_size} bytes"
def _write_software_manifest(software_dir: Path, spec_payload: dict[str, Any]) -> None: if str(spec_payload.get("workflow_kind") or "") != "software_tutorial_doc_audit": return software_dir.mkdir(parents=True, exist_ok=True) software_name = str(spec_payload.get("software_name") or "").strip() executables = [str(item).strip() for item in spec_payload.get("executables") or [] if str(item).strip()] system_packages = [str(item).strip() for item in spec_payload.get("required_system_packages") or [] if str(item).strip()] source_urls = [str(item).strip() for item in spec_payload.get("source_urls") or [] if str(item).strip()] _write_json(software_dir / "software_manifest.json", { "software_name": software_name, "executables": executables, "required_system_packages": system_packages, "official_sources": source_urls, "solve_time_network": "disabled", "python_wrapper_only": False, "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs.", }) with (software_dir / "command_examples.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["term", "kind", "software_name"]) writer.writeheader() for term in spec_payload.get("code_terms") or []: writer.writerow({"term": str(term), "kind": "code_term", "software_name": software_name}) for exe in executables: writer.writerow({"term": exe, "kind": "executable", "software_name": software_name})
def software_tutorial_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") source_file = str(spec["source_file"]) source_text = (input_dir / source_file).read_text(encoding="utf-8", errors="replace") clean_text = _clean_markup_text(source_text) headings = _extract_headings(source_text) code_blocks = _extract_code_blocks(source_text) window_rows: list[dict[str, str]] = [] with (input_dir / str(spec["input_file"])).open("r", encoding="utf-8", newline="") as handle: window_rows = list(csv.DictReader(handle)) output_dir.mkdir(parents=True, exist_ok=True)
with (output_dir / "section_outline.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "heading_level", "heading_text", "slug"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for rank, heading in enumerate(headings, start=1): writer.writerow({ "rank": rank, "heading_level": heading["level"], "heading_text": heading["text"], "slug": _heading_slug(heading["text"]), })
all_terms: list[tuple[str, str]] = [] for term in spec.get("required_terms") or []: all_terms.append((str(term), "required")) for term in spec.get("code_terms") or []: if str(term) not in {item[0] for item in all_terms}: all_terms.append((str(term), "code")) code_text = "\n".join(code_blocks) term_rows: list[dict[str, Any]] = [] for term, category in all_terms: term_rows.append({ "term": term, "category": category, "count": _term_count(clean_text, term), "first_window": _first_window(window_rows, term), "appears_in_code": "true" if term.lower() in code_text.lower() else "false", }) term_rows.sort(key=lambda row: (str(row["category"]), str(row["term"]).lower())) with (output_dir / "keyword_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["term", "category", "count", "first_window", "appears_in_code"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in term_rows: writer.writerow(row)
code_terms = [str(item).lower() for item in spec.get("code_terms") or []] with (output_dir / "code_block_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["block_index", "line_count", "char_count", "contains_code_term", "first_line"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for index, block in enumerate(code_blocks, start=1): lines = [line for line in block.splitlines() if line.strip()] contains = any(term and term in block.lower() for term in code_terms) writer.writerow({ "block_index": index, "line_count": len(lines), "char_count": len(block), "contains_code_term": "true" if contains else "false", "first_line": lines[0][:200] if lines else "", })
keyword_total = sum(int(row["count"]) for row in term_rows) required_found = sum(1 for row in term_rows if row["category"] == "required" and int(row["count"]) > 0) top_keyword = None if term_rows: top = max(term_rows, key=lambda row: (int(row["count"]), str(row["term"]).lower())) top_keyword = str(top["term"]) if int(top["count"]) > 0 else None summary = { "software_name": str(spec.get("software_name") or ""), "source_file": source_file, "window_count": len(window_rows), "heading_count": len(headings), "code_block_count": len(code_blocks), "keyword_total": keyword_total, "unique_required_terms_found": required_found, "top_keyword": top_keyword, "source_character_count": len(clean_text), } _write_json(output_dir / "summary.json", summary)
def geojson_outputs(input_dir: Path, output_dir: Path) -> None: payload = _read_json(input_dir / "events.geojson") features = payload.get("features") if isinstance(payload, dict) else [] rows: list[dict[str, Any]] = [] for feature in features: if not isinstance(feature, dict): continue props = feature.get("properties") if isinstance(feature.get("properties"), dict) else {} geom = feature.get("geometry") if isinstance(feature.get("geometry"), dict) else {} coords = geom.get("coordinates") if isinstance(geom.get("coordinates"), list) else [] mag = props.get("mag") try: mag = float(mag) if mag is not None else None except (TypeError, ValueError): mag = None depth = None if len(coords) >= 3: try: depth = float(coords[2]) except (TypeError, ValueError): depth = None time_ms = props.get("time") date_utc = "unknown" if isinstance(time_ms, (int, float)): date_utc = dt.datetime.utcfromtimestamp(time_ms / 1000).date().isoformat() rows.append({ "id": feature.get("id") or props.get("code") or "", "mag": mag, "depth": depth, "place": str(props.get("place") or ""), "region": _stable_region(str(props.get("place") or "")), "date_utc": date_utc, "feature": feature, }) output_dir.mkdir(parents=True, exist_ok=True) mags = [row["mag"] for row in rows if row["mag"] is not None] depths = [row["depth"] for row in rows if row["depth"] is not None] summary = { "event_count": len(rows), "magnitude": { "count": len(mags), "min": round(min(mags), 6) if mags else None, "max": round(max(mags), 6) if mags else None, "mean": round(statistics.fmean(mags), 6) if mags else None, "median": round(statistics.median(mags), 6) if mags else None, }, "depth_km": { "count": len(depths), "min": round(min(depths), 6) if depths else None, "max": round(max(depths), 6) if depths else None, "mean": round(statistics.fmean(depths), 6) if depths else None, }, "time_range_utc": { "start_date": min((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), "end_date": max((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), }, "quality_flags": { "missing_magnitude": sum(1 for row in rows if row["mag"] is None), "missing_depth": sum(1 for row in rows if row["depth"] is None), "unique_regions": len({row["region"] for row in rows}), }, } _write_json(output_dir / "summary.json", summary)
grouped: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: grouped.setdefault((_mag_bin(row["mag"]), _depth_bin(row["depth"])), []).append(row) with (output_dir / "magnitude_depth_bins.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["mag_bin", "depth_bin", "event_count", "mean_magnitude", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (mag_bin, depth_bin), group in sorted(grouped.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "mag_bin": mag_bin, "depth_bin": depth_bin, "event_count": len(group), "mean_magnitude": f"{statistics.fmean(group_mags):.6f}" if group_mags else "", "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
daily: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: daily.setdefault((row["region"], row["date_utc"]), []).append(row) with (output_dir / "region_daily_counts.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["region", "date_utc", "event_count", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (region, date_utc), group in sorted(daily.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "region": region, "date_utc": date_utc, "event_count": len(group), "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
filtered = [row["feature"] for row in rows if row["mag"] is not None and row["mag"] >= 4.5] _write_json(output_dir / "filtered_events.geojson", {"type": "FeatureCollection", "features": filtered})
def csv_time_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] date_column = spec["date_column"] value_column = spec["value_column"] rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_date = item.get(date_column, "") try: day = dt.date.fromisoformat(raw_date) except ValueError: if raw_date.isdigit() and len(raw_date) == 4: day = dt.date(int(raw_date), 1, 1) else: continue raw_value = item.get(value_column, "") try: value = float(raw_value) except (TypeError, ValueError): value = None rows.append({"date": day, "value": value, "raw": item}) rows.sort(key=lambda item: item["date"]) valid = [row for row in rows if row["value"] is not None] output_dir.mkdir(parents=True, exist_ok=True) monthly: dict[str, list[float]] = {} for row in valid: key = row["date"].strftime("%Y-%m") monthly.setdefault(key, []).append(row["value"]) with (output_dir / "monthly_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["month", "count", "mean", "median", "min", "max"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for month, values in sorted(monthly.items()): writer.writerow({ "month": month, "count": len(values), "mean": f"{statistics.fmean(values):.6f}", "median": f"{statistics.median(values):.6f}", "min": f"{min(values):.6f}", "max": f"{max(values):.6f}", }) existing_dates = {row["date"] for row in rows} missing_days: list[dt.date] = [] if rows: day = rows[0]["date"] while day <= rows[-1]["date"]: if day.weekday() < 5 and day not in existing_dates: missing_days.append(day) day += dt.timedelta(days=1) with (output_dir / "missing_business_days.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date"]) writer.writeheader() for day in missing_days: writer.writerow({"date": day.isoformat()}) with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date", "value"]) writer.writeheader() for row in valid: writer.writerow({"date": row["date"].isoformat(), "value": f"{row['value']:.6f}"}) values = [row["value"] for row in valid] summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "valid_value_count": len(valid), "missing_value_count": len(rows) - len(valid), "missing_business_day_count": len(missing_days), "date_range": { "start": rows[0]["date"].isoformat() if rows else None, "end": rows[-1]["date"].isoformat() if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "max": round(max(values), 6) if values else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, }, } _write_json(output_dir / "summary.json", summary)
def _aggregate_annual_rows(rows: list[dict[str, Any]], aggregation: str) -> list[dict[str, Any]]: if not aggregation: return rows grouped: dict[int, list[float]] = {} for row in rows: grouped.setdefault(int(row["year"]), []).append(float(row["value"])) aggregated: list[dict[str, Any]] = [] for year, values in sorted(grouped.items()): if aggregation == "mean": value = statistics.fmean(values) elif aggregation == "median": value = statistics.median(values) elif aggregation == "max": value = max(values) elif aggregation == "min": value = min(values) elif aggregation == "count": value = float(len(values)) else: raise ValueError(f"unsupported year_aggregation for csv_annual_series_audit: {aggregation}") aggregated.append({"year": year, "value": value}) return aggregated
def csv_annual_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] year_column = spec["year_column"] value_column = spec["value_column"] # Optional: derive the year from an ISO-8601 timestamp column (e.g. USGS FDSN # `time` = "2022-06-29T19:17:58.929Z") instead of parsing an integer year. # When unset, behaviour is unchanged (integer year column). year_from_timestamp = bool(spec.get("year_from_timestamp", False)) year_aggregation = str(spec.get("year_aggregation") or "").strip().lower() raw_rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_year = str(item.get(year_column, "")).strip() try: if year_from_timestamp: # Take the leading 4-digit year of an ISO timestamp/date. match = re.match(r"\s*(\d{4})", raw_year) if not match: continue year = int(match.group(1)) else: year = int(raw_year) value = float(str(item.get(value_column, "")).strip()) except (TypeError, ValueError): continue raw_rows.append({"year": year, "value": value}) rows = _aggregate_annual_rows(raw_rows, year_aggregation) rows.sort(key=lambda item: item["year"]) output_dir.mkdir(parents=True, exist_ok=True) decades: dict[str, list[float]] = {} for row in rows: decade_start = (row["year"] // 10) * 10 decades.setdefault(f"{decade_start}s", []).append(row["value"]) with (output_dir / "decadal_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = [ "decade_start", "start_year", "end_year", "count", "mean_departure", "median_departure", "min_departure", "max_departure", "sample_std_departure", ] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for decade, values in sorted(decades.items()): decade_start = int(decade.rstrip("s")) years = [row["year"] for row in rows if decade_start <= row["year"] <= decade_start + 9] writer.writerow({ "decade_start": decade_start, "start_year": min(years), "end_year": max(years), "count": len(values), "mean_departure": f"{statistics.fmean(values):.6f}", "median_departure": f"{statistics.median(values):.6f}", "min_departure": f"{min(values):.6f}", "max_departure": f"{max(values):.6f}", "sample_std_departure": f"{statistics.stdev(values):.6f}" if len(values) >= 2 else "", }) threshold = float(spec.get("threshold", 1.0)) with (output_dir / "threshold_years.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "year", "departure", "threshold"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() rank = 1 for row in rows: if row["value"] >= threshold: writer.writerow({ "rank": rank, "year": row["year"], "departure": f"{row['value']:.6f}", "threshold": f"{threshold:.6f}", }) rank += 1 with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["Year", "Departure from Average"]) writer.writeheader() for row in rows: writer.writerow({"Year": row["year"], "Departure from Average": f"{row['value']:.6f}"}) values = [row["value"] for row in rows] threshold_rows = [row for row in rows if row["value"] >= threshold] min_row = min(rows, key=lambda row: row["value"]) if rows else None max_row = max(rows, key=lambda row: row["value"]) if rows else None summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "year_range": { "start": rows[0]["year"] if rows else None, "end": rows[-1]["year"] if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "min_year": min_row["year"] if min_row else None, "max": round(max(values), 6) if values else None, "max_year": max_row["year"] if max_row else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, "sample_std": round(statistics.stdev(values), 6) if len(values) >= 2 else None, }, "threshold": threshold, "years_at_or_above_threshold": len(threshold_rows), "first_threshold_year": threshold_rows[0]["year"] if threshold_rows else None, "last_threshold_year": threshold_rows[-1]["year"] if threshold_rows else None, } if year_aggregation: summary["year_aggregation"] = year_aggregation summary["source_row_count"] = len(raw_rows) _write_json(output_dir / "summary.json", summary)
12345from pathlib import Pathfrom workflow_adapters_runtime import csv_annual_series_outputs
def run_reference(input_dir: Path, output_dir: Path) -> None: csv_annual_series_outputs(input_dir, output_dir)12345678910111213141516171819202122232425262728293031323334{ "workflow_kind": "csv_annual_series_audit", "task_id": "usgs_fdsn_eq_mediterranean_2002_2002_m4p5_mag_max_quota_repair_0677", "domain": "science_environment", "task": "usgs_mediterranean_annual_maximum_magnitude_audit", "variant": "base", "created_from": "standard reference workflow", "required_outputs": [ { "path": "summary.json", "type": "json" }, { "path": "decadal_statistics.csv", "type": "csv" }, { "path": "threshold_years.csv", "type": "csv" }, { "path": "clean_series.csv", "type": "csv" } ], "numeric_tolerance": 1e-09, "source_prior_sha256": "2504f5d0b3f6841871f72dd39b23346683c2cf09e99c1543f8bd7d257eaa2b5f", "gold_output_hashes": { "summary.json": "ebcb2373e18c50abd34644ab9919c3cf5aceee29dead989176f0c981605e0a16", "decadal_statistics.csv": "a1dbec5863bd50cd7654d2d41d611f550e93792a036427fd6e4a4eefe86813f9", "threshold_years.csv": "5276c760458ad393ac790e1dfdb88e8cd5c8524c7fb2b485ac604cf05d979509", "clean_series.csv": "7e703fda79a6c43555bd09b617bad047fce2047ed0c1b5dfdb63ccfe2fd76be4" }}1234567891011121314151617181920from __future__ import annotations
import argparseimport sysfrom pathlib import Path
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--input", required=True) parser.add_argument("--output", required=True) args = parser.parse_args() sys.path.insert(0, str(Path(__file__).resolve().parent / "internal")) from workflow_runtime import run_reference run_reference(Path(args.input), Path(args.output)) return 0
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829#!/bin/bashset -u
TESTS_DIR="${HARBOR_TESTS_DIR:-/tests}"WORKSPACE_DIR="${HARBOR_WORKSPACE_DIR:-/workspace}"LOGS_DIR="${HARBOR_LOGS_DIR:-/logs/verifier}"
mkdir -p "${LOGS_DIR}" "${WORKSPACE_DIR}/output"
python "${TESTS_DIR}/evaluator_runner.py" \ --output-dir "${WORKSPACE_DIR}/output" \ --reference-dir "${TESTS_DIR}/reference" \ --reward-json "${LOGS_DIR}/reward.json" \ --details-json "${LOGS_DIR}/ale_evaluator_details.json"
if [ ! -f "${LOGS_DIR}/reward.json" ]; then echo '{"score":0.0,"format":0.0,"output_present":0.0,"evaluator_available":0.0,"item_count":0.0}' > "${LOGS_DIR}/reward.json"fi
python - <<'PY' "${LOGS_DIR}/reward.json" "${LOGS_DIR}/reward.txt"import jsonimport sysfrom pathlib import Pathreward = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))score = float(reward.get("score", 0.0))Path(sys.argv[2]).write_text(f"{score}\n", encoding="utf-8")PY
exit 0123version https://git-lfs.github.com/spec/v1oid sha256:ee7c303989bf4327f2ed3a8f296345540eeb0f46b38dd2933eeca307a808581fsize 6148123456789101112FROM python:3.12-slim
WORKDIR /workspace
COPY public_data/input /workspace/inputCOPY public_data/software /workspace/softwareCOPY public_data/task_card.json /workspace/task_card.jsonCOPY public_data/main.py /workspace/main.pyCOPY public_data/README.md /workspace/README.md
RUN mkdir -p /workspace/output /workspace/report /logs/agent /logs/artifacts \ && chmod -R 777 /workspace/output /workspace/report /logs1234567891011# Public Task Inputs
Files in this directory are copied into the workspace:
- `input/` -> `/workspace/input/`- `software/` -> `/workspace/software/`- `task_card.json` -> `/workspace/task_card.json`- `main.py` -> `/workspace/main.py`
Hidden reference data and evaluator files are not present in the agent workspace.Final deliverables must be written under `/workspace/output/`.123456This directory contains the public staged input for this task.input/analysis_spec.json is the authoritative public contract for input columns, grouping/filtering rules, required output files, and output schemas.Primary data file: input/usgs_fdsn_eq_japan_kuril_1979_1981_m5p5_mag_max_quota_repair_0678.csv.Workflow kind: csv_annual_series_audit.Required output files: output/summary.json, output/decadal_statistics.csv, output/threshold_years.csv, output/clean_series.csv.Solve the task from the staged local files only; do not fetch fresh remote data during solve time.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576{ "input_file": "usgs_fdsn_eq_japan_kuril_1979_1981_m5p5_mag_max_quota_repair_0678.csv", "workflow_kind": "csv_annual_series_audit", "year_column": "time", "value_column": "mag", "series_name": "USGS FDSN Japan and Kuril trench 1971-1989 earthquake annual maximum magnitude (min mag 4.5)", "threshold": 6.0, "year_from_timestamp": true, "comment_prefix": "#", "required_outputs": [ { "path": "summary.json", "type": "json" }, { "path": "decadal_statistics.csv", "type": "csv" }, { "path": "threshold_years.csv", "type": "csv" }, { "path": "clean_series.csv", "type": "csv" } ], "output_schemas": { "summary.json": { "series_name": "string", "row_count": "integer valid annual rows", "year_range": { "start": "integer|null", "end": "integer|null" }, "value": { "min": "number|null", "min_year": "integer|null", "max": "number|null", "max_year": "integer|null", "mean": "number|null", "median": "number|null", "sample_std": "number|null" }, "threshold": "number", "years_at_or_above_threshold": "integer", "first_threshold_year": "integer|null", "last_threshold_year": "integer|null", "year_aggregation": "string annual aggregation applied to raw rows", "source_row_count": "integer raw rows before annual aggregation" }, "decadal_statistics.csv": [ "decade_start", "start_year", "end_year", "count", "mean_departure", "median_departure", "min_departure", "max_departure", "sample_std_departure" ], "threshold_years.csv": [ "rank", "year", "departure", "threshold" ], "clean_series.csv": [ "Year", "Departure from Average" ] }, "notes": "First group raw CSV rows by year and aggregate the value column with max; then compute reproducible annual-series audit outputs. Do not fetch new data.", "year_aggregation": "max"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180from __future__ import annotations
import importlib.utilimport jsonimport osimport shleximport shutilfrom pathlib import Pathfrom typing import Any
class Task: def __init__(self, task_id: str, description: str, metadata: dict[str, Any]): self.task_id = task_id self.description = description self.prompt = description self.metadata = metadata self.computer = {"setup_config": {"os_type": "linux"}}
def _task_dir() -> Path: return Path(__file__).resolve().parent
def _load_card() -> dict[str, Any]: path = _task_dir() / "task_card.json" if not path.is_file(): return { "taskId": os.environ.get("ALE_TASK_ID", "science_environment/usgs_japan_kuril_annual_earthquake_maximum_audit"), "taskPrompt": "Task card has not been rendered yet; this fallback exists for stage-03 hook smoke only.", "metadata": { "domain": "science_environment", "task": "usgs_japan_kuril_annual_earthquake_maximum_audit", "variant": "base", "domain_name": "science_environment", "task_name": "usgs_japan_kuril_annual_earthquake_maximum_audit", "variant_name": "base", "requires_task_data": True, "task_dir": "/media/user/data/agenthle/science_environment/usgs_japan_kuril_annual_earthquake_maximum_audit/base", "input_dir": "/media/user/data/agenthle/science_environment/usgs_japan_kuril_annual_earthquake_maximum_audit/base/input", "software_dir": "/media/user/data/agenthle/science_environment/usgs_japan_kuril_annual_earthquake_maximum_audit/base/software", "remote_output_dir": "/media/user/data/agenthle/science_environment/usgs_japan_kuril_annual_earthquake_maximum_audit/base/output", "reference_dir": "/media/user/data/agenthle/science_environment/usgs_japan_kuril_annual_earthquake_maximum_audit/base/reference", }, } with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def load() -> list[Task]: card = _load_card() metadata = dict(card.get("metadata") or {}) if not metadata: domain, _, task = str(card["taskId"]).partition("/") variant = "base" task_dir = f"/media/user/data/agenthle/{domain}/{task}/{variant}" metadata.update({ "domain": domain, "task": task, "variant": variant, "domain_name": domain, "task_name": task, "variant_name": variant, "requires_task_data": True, "task_dir": task_dir, "input_dir": f"{task_dir}/input", "software_dir": f"{task_dir}/software", "remote_output_dir": f"{task_dir}/output", "reference_dir": f"{task_dir}/reference", }) return [Task(task_id=card["taskId"], description=card["taskPrompt"], metadata=metadata)]
def _metadata(cfg: Any = None) -> dict[str, Any]: if cfg is None: return {} value = getattr(cfg, "metadata", None) return value if isinstance(value, dict) else {}
def _remote_path(metadata: dict[str, Any], key: str, fallback: str) -> str: value = str(metadata.get(key) or "").strip() return value or fallback
async def _remote_run(session: Any, command: str, *, check: bool = False) -> Any: try: return await session.run_command(command, check=check) except TypeError: return await session.run_command(command)
async def _remote_start(cfg: Any, session: Any) -> dict[str, Any]: metadata = _metadata(cfg) output_dir = _remote_path(metadata, "remote_output_dir", "output") input_dir = _remote_path(metadata, "input_dir", "input") software_dir = _remote_path(metadata, "software_dir", "software") command = ( "set -eu\n" f"mkdir -p {shlex.quote(output_dir)}\n" f"find {shlex.quote(output_dir)} -mindepth 1 -maxdepth 1 -exec rm -rf -- {{}} +\n" ) await _remote_run(session, command, check=True) return {"ok": True, "input_dir": input_dir, "software_dir": software_dir, "output_dir": output_dir}
def start(cfg: Any = None, session: Any = None) -> dict[str, Any]: if session is not None: return _remote_start(cfg, session) del cfg output_dir = Path(os.environ.get("ALE_OUTPUT_DIR", "output")) output_dir.mkdir(parents=True, exist_ok=True) for child in output_dir.iterdir(): if child.is_dir(): shutil.rmtree(child) else: child.unlink() input_dir = Path(os.environ.get("ALE_INPUT_DIR", "input")) software_dir = Path(os.environ.get("ALE_SOFTWARE_DIR", "software")) return { "ok": True, "input_dir": str(input_dir), "software_dir": str(software_dir), "output_dir": str(output_dir), }
async def _remote_evaluate(cfg: Any, session: Any) -> list[float]: metadata = _metadata(cfg) output_dir = _remote_path(metadata, "remote_output_dir", "output") reference_dir = _remote_path(metadata, "reference_dir", "reference") script = f"""import importlib.utilimport jsonimport pathlib
output_dir = pathlib.Path({output_dir!r})reference_dir = pathlib.Path({reference_dir!r})evaluator_path = reference_dir / "evaluator.py"if not evaluator_path.is_file(): raise FileNotFoundError(f"hidden evaluator is missing: {{evaluator_path}}")spec = importlib.util.spec_from_file_location("hidden_ale_evaluator", evaluator_path)if spec is None or spec.loader is None: raise RuntimeError(f"cannot import hidden evaluator: {{evaluator_path}}")module = importlib.util.module_from_spec(spec)spec.loader.exec_module(module)result = module.evaluate(output_dir, reference_dir)print(json.dumps(result))""" command = "python3 - <<'PY'\n" + script + "\nPY" result = await _remote_run(session, command, check=True) stdout = getattr(result, "stdout", "") or "" for line in reversed([item.strip() for item in stdout.splitlines() if item.strip()]): try: payload = json.loads(line) if isinstance(payload, list): return [float(max(0.0, min(1.0, value))) for value in payload] except Exception: continue raise RuntimeError("hidden evaluator did not emit a JSON score list")
def evaluate(cfg: Any = None, session: Any = None) -> list[float]: if session is not None: return _remote_evaluate(cfg, session) del cfg output_dir = Path(os.environ.get("ALE_OUTPUT_DIR", "output")) reference_dir = Path(os.environ.get("ALE_REFERENCE_DIR", "reference")) evaluator_path = reference_dir / "evaluator.py" if not evaluator_path.is_file(): raise FileNotFoundError(f"hidden evaluator is missing: {evaluator_path}") spec = importlib.util.spec_from_file_location("hidden_ale_evaluator", evaluator_path) if spec is None or spec.loader is None: raise RuntimeError(f"cannot import hidden evaluator: {evaluator_path}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) result = module.evaluate(output_dir, reference_dir) if not isinstance(result, list): raise TypeError("hidden evaluator must return list[float]") return [float(max(0.0, min(1.0, value))) for value in result]1234567891011121314151617181920212223242526272829303132333435363738394041#!/usr/bin/env python3from __future__ import annotations
import jsonimport osimport sysfrom pathlib import Path
def required_outputs(input_dir: Path) -> list[str]: spec_path = input_dir / "analysis_spec.json" if spec_path.is_file(): payload = json.loads(spec_path.read_text(encoding="utf-8")) required = payload.get("required_outputs") if isinstance(payload, dict) else None if isinstance(required, list): rows = [str(item.get("path") or "") for item in required if isinstance(item, dict)] rows = [item for item in rows if item] if rows: return rows return [ "summary.json", "magnitude_depth_bins.csv", "region_daily_counts.csv", "filtered_events.geojson", ]
def main() -> int: output_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("output") input_dir = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(os.environ.get("ALE_INPUT_DIR", "input")) required = required_outputs(input_dir) missing = [name for name in required if not (output_dir / name).is_file()] if missing: print(json.dumps({"ok": False, "missing": missing}, indent=2)) return 1 print(json.dumps({"ok": True, "required": required}, indent=2)) return 0
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192{ "taskId": "science_environment/usgs_japan_kuril_annual_earthquake_maximum_audit", "title": "USGS Fdsn Eq Japan Kuril 1979 1981 M5p5 Mag Max Quota Repair 0678", "summary": "Audit the real USGS FDSN Japan and Kuril trench earthquake catalog for 1971-1989 (events with magnitude >= 5.5) and produce reproducible annual annual maximum magnitude statistics, decadal aggregates, threshold-year checks, and a cleaned local series.", "category": "science_environment", "taxonomy": { "domain_id": "science_environment", "domain_code": "science_environment", "subdomain_id": "science_environment.data_analysis", "subdomain_code": "data_analysis", "subdomain_name": "Data Analysis", "classifier": { "source": "deterministic task metadata", "rationale": "CLI-only task derived from a public, reproducible workflow seed." } }, "taskPrompt": "Use a Linux command-line workflow to complete this local data-audit task. Read only the staged files in input/ and software/, write final deliverables under output/, and do not use network access, credentials, GUI tools, browser automation, Windows-only tooling, or mobile apps. The authoritative public contract is input/analysis_spec.json; if any wording elsewhere is less specific, follow analysis_spec.json for file names, columns, filters, grouping rules, rounding rules, and output schemas. The workflow kind is csv_annual_series_audit. The primary staged data file is input/usgs_fdsn_eq_japan_kuril_1979_1981_m5p5_mag_max_quota_repair_0678.csv. Produce exactly these required deliverables: output/summary.json, output/decadal_statistics.csv, output/threshold_years.csv, output/clean_series.csv. The output schemas are:\n- output/summary.json: JSON keys and nested shape {\"first_threshold_year\": \"integer|null\", \"last_threshold_year\": \"integer|null\", \"row_count\": \"integer valid annual rows\", \"series_name\": \"string\", \"source_row_count\": \"integer raw rows before annual aggregation\", \"threshold\": \"number\", \"value\": {\"max\": \"number|null\", \"max_year\": \"integer|null\", \"mean\": \"number|null\", \"median\": \"number|null\", \"min\": \"number|null\", \"min_year\": \"integer|null\", \"sample_std\": \"number|null\"}, \"year_aggregation\": \"string annual aggregation applied to raw rows\", \"year_range\": {\"end\": \"integer|null\", \"start\": \"integer|null\"}, \"years_at_or_above_threshold\": \"integer\"}\n- output/decadal_statistics.csv: CSV header exactly decade_start, start_year, end_year, count, mean_departure, median_departure, min_departure, max_departure, sample_std_departure\n- output/threshold_years.csv: CSV header exactly rank, year, departure, threshold\n- output/clean_series.csv: CSV header exactly Year, Departure from Average\nCompute all requested values from the staged data rather than hard-coding constants. Use deterministic ordering, UTF-8 text, explicit CSV headers, valid JSON/GeoJSON where applicable, and stable numeric formatting. You may run software/validate_outputs.py as a public sanity check after writing outputs, but the deliverables in output/ are what will be evaluated.", "agentMustDo": [ "Read input/analysis_spec.json first and treat it as the authoritative public specification.", "Read input/usgs_fdsn_eq_japan_kuril_1979_1981_m5p5_mag_max_quota_repair_0678.csv and compute results from the staged local data.", "Create output/summary.json as json exactly as specified by analysis_spec.json.", "Create output/decadal_statistics.csv as csv exactly as specified by analysis_spec.json.", "Create output/threshold_years.csv as csv exactly as specified by analysis_spec.json.", "Create output/clean_series.csv as csv exactly as specified by analysis_spec.json.", "Place every final deliverable directly under output/ with the exact required filename.", "Use only local staged files and installed Linux CLI tooling; do not download fresh data." ], "inputFiles": [ { "name": "README.md", "format": "Markdown", "path": "input/README.md", "description": "Agent-visible staged input file for this task." }, { "name": "analysis_spec.json", "format": "JSON", "path": "input/analysis_spec.json", "description": "Agent-visible staged input file for this task." }, { "name": "source_context_windows.jsonl", "format": "JSONL", "path": "input/source_context_windows.jsonl", "description": "Agent-visible staged input file for this task." }, { "name": "usgs_fdsn_eq_japan_kuril_1979_1981_m5p5_mag_max_quota_repair_0678.csv", "format": "CSV", "path": "input/usgs_fdsn_eq_japan_kuril_1979_1981_m5p5_mag_max_quota_repair_0678.csv", "description": "Agent-visible staged input file for this task." } ], "referenceFiles": [ { "name": "summary.json", "format": "JSON", "path": "output/summary.json", "description": "Required agent output file evaluated against hidden reference data." }, { "name": "decadal_statistics.csv", "format": "CSV", "path": "output/decadal_statistics.csv", "description": "Required agent output file evaluated against hidden reference data." }, { "name": "threshold_years.csv", "format": "CSV", "path": "output/threshold_years.csv", "description": "Required agent output file evaluated against hidden reference data." }, { "name": "clean_series.csv", "format": "CSV", "path": "output/clean_series.csv", "description": "Required agent output file evaluated against hidden reference data." } ], "software": [ "Python 3.11", "standard Unix shell", "software/validate_outputs.py" ], "requiredSystemPackages": [], "evaluation": "Final required files under output/ are compared against standard-reference outputs generated by the deterministic workflow for this task.", "vm": { "machineType": "c4-standard-4", "snapshot": "cpu-free-ubuntu", "timeout": 7200 }}123456789101112131415161718192021222324252627282930313233# USGS Fdsn Eq Japan Kuril 1979 1981 M5p5 Mag Max Quota Repair 0678
Audit the real USGS FDSN Japan and Kuril trench earthquake catalog for 1971-1989 (events with magnitude >= 5.5) and produce reproducible annual annual maximum magnitude statistics, decadal aggregates, threshold-year checks, and a cleaned local series.
## Task
Use a Linux command-line workflow to complete this local data-audit task. Read only the staged files in input/ and software/, write final deliverables under output/, and do not use network access, credentials, GUI tools, browser automation, Windows-only tooling, or mobile apps. The authoritative public contract is input/analysis_spec.json; if any wording elsewhere is less specific, follow analysis_spec.json for file names, columns, filters, grouping rules, rounding rules, and output schemas. The workflow kind is csv_annual_series_audit. The primary staged data file is input/usgs_fdsn_eq_japan_kuril_1979_1981_m5p5_mag_max_quota_repair_0678.csv. Produce exactly these required deliverables: output/summary.json, output/decadal_statistics.csv, output/threshold_years.csv, output/clean_series.csv. The output schemas are:- output/summary.json: JSON keys and nested shape {"first_threshold_year": "integer|null", "last_threshold_year": "integer|null", "row_count": "integer valid annual rows", "series_name": "string", "source_row_count": "integer raw rows before annual aggregation", "threshold": "number", "value": {"max": "number|null", "max_year": "integer|null", "mean": "number|null", "median": "number|null", "min": "number|null", "min_year": "integer|null", "sample_std": "number|null"}, "year_aggregation": "string annual aggregation applied to raw rows", "year_range": {"end": "integer|null", "start": "integer|null"}, "years_at_or_above_threshold": "integer"}- output/decadal_statistics.csv: CSV header exactly decade_start, start_year, end_year, count, mean_departure, median_departure, min_departure, max_departure, sample_std_departure- output/threshold_years.csv: CSV header exactly rank, year, departure, threshold- output/clean_series.csv: CSV header exactly Year, Departure from AverageCompute all requested values from the staged data rather than hard-coding constants. Use deterministic ordering, UTF-8 text, explicit CSV headers, valid JSON/GeoJSON where applicable, and stable numeric formatting. You may run software/validate_outputs.py as a public sanity check after writing outputs, but the deliverables in output/ are what will be evaluated.
## Workspace
You are working in `/workspace`.
- Public input files are under `/workspace/input/`.- Public helper software and validation scripts are under `/workspace/software/`.- The public task card is available at `/workspace/task_card.json`.- The public task driver is available at `/workspace/main.py` for reference only.- Do not use hidden reference data, network downloads, credentials, GUI tools, or browser automation.
## Required Outputs
Create every final deliverable exactly at these paths:
- `/workspace/output/summary.json` (json)- `/workspace/output/decadal_statistics.csv` (csv)- `/workspace/output/threshold_years.csv` (csv)- `/workspace/output/clean_series.csv` (csv)
Follow `/workspace/input/analysis_spec.json` whenever it is more specific than prose. You may run public validation helpers, but the files under `/workspace/output/` are what will be evaluated.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679from __future__ import annotations
import csvimport datetime as dtimport htmlimport jsonimport mathimport reimport shutilimport statisticsfrom pathlib import Pathfrom typing import Any
def _read_json(path: Path) -> Any: with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def _write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2) handle.write("\n")
def _stable_region(place: str) -> str: if not place: return "unknown" if "," in place: return place.split(",")[-1].strip() or place.strip() parts = place.split() return " ".join(parts[-2:]) if len(parts) >= 2 else place.strip()
def _mag_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" lower = math.floor(value) upper = lower + 1 return f"{lower:.0f}-{upper:.0f}"
def _depth_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" if value < 0: return "<0" if value < 10: return "0-10" if value < 30: return "10-30" if value < 70: return "30-70" if value < 300: return "70-300" return "300+"
def _clean_markup_text(raw: str) -> str: text = re.sub(r"(?is)<(script|style|noscript)[^>]*>.*?</\1>", " ", raw) text = re.sub(r"(?is)<br\s*/?>", "\n", text) text = re.sub(r"(?is)</(p|div|li|tr|h[1-6]|pre)>", "\n", text) text = re.sub(r"(?is)<[^>]+>", " ", text) text = html.unescape(text) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n\s+", "\n", text) return text.strip()
def _heading_slug(value: str) -> str: slug = re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_") return slug[:80] or "section"
def _extract_headings(raw: str) -> list[dict[str, str]]: headings: list[dict[str, str]] = [] for match in re.finditer(r"(?is)<h([1-6])[^>]*>(.*?)</h\1>", raw): text = _clean_markup_text(match.group(2)) if text: headings.append({"level": f"h{match.group(1)}", "text": text}) if headings: return headings for line in raw.splitlines(): match = re.match(r"^(#{1,6})\s+(.+?)\s*$", line) if match: headings.append({"level": f"h{len(match.group(1))}", "text": match.group(2).strip()}) return headings
def _extract_code_blocks(raw: str) -> list[str]: blocks: list[str] = [] for match in re.finditer(r"(?is)<pre[^>]*>(.*?)</pre>", raw): text = _clean_markup_text(match.group(1)) if text: blocks.append(text) for match in re.finditer(r"(?is)<code[^>]*>(.*?)</code>", raw): text = _clean_markup_text(match.group(1)) if text and text not in blocks: blocks.append(text) for match in re.finditer(r"(?s)```(?:[A-Za-z0-9_-]+)?\n(.*?)```", raw): text = html.unescape(match.group(1).strip()) if text and text not in blocks: blocks.append(text) return blocks
def _window_rows(clean_text: str, *, width: int = 40, stride: int = 20) -> list[dict[str, Any]]: words = re.findall(r"\S+", clean_text) rows: list[dict[str, Any]] = [] if not words: return rows start = 0 while start < len(words): end = min(start + width, len(words)) rows.append({ "window_id": len(rows) + 1, "start_word": start, "end_word": end, "text": " ".join(words[start:end]), }) if end == len(words): break start += stride return rows
def _term_count(text: str, term: str) -> int: term = term.strip() if not term: return 0 return len(re.findall(re.escape(term), text, flags=re.IGNORECASE))
def _first_window(windows: list[dict[str, Any]], term: str) -> str: term_lower = term.lower() for row in windows: if term_lower in str(row.get("text") or "").lower(): return str(row.get("window_id") or "") return ""
def _write_tutorial_public_inputs(input_dir: Path, source_path: Path, spec_payload: dict[str, Any]) -> None: raw = source_path.read_text(encoding="utf-8", errors="replace") # Tutorial examples may contain a maintainer's local Windows path. Keep # the command semantics while preventing host-specific paths from entering # the public task artifact. sanitized_raw = re.sub(r"(?i)\b[A-Z]:\\(?:[^\\\r\n<>\"']+\\?)*[^\\\r\n<>\"']*", "./local.db", raw) clean_text = _clean_markup_text(sanitized_raw) windows = _window_rows(clean_text) if len(windows) < 100: raise ValueError(f"official tutorial source produced only {len(windows)} text windows; need at least 100") required_terms = [str(item) for item in spec_payload.get("required_terms") or []] code_terms = [str(item) for item in spec_payload.get("code_terms") or []] input_dir.mkdir(parents=True, exist_ok=True) destination = input_dir / str(spec_payload["source_file"]) # Always materialize the sanitized copy, including when the downloader # already placed the source at the destination path. destination.write_text(sanitized_raw, encoding="utf-8") with (input_dir / str(spec_payload["input_file"])).open("w", encoding="utf-8", newline="") as handle: fieldnames = ["window_id", "start_word", "end_word", "text", "contains_code_term", "matched_required_terms"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in windows: text = str(row["text"]) matched = [term for term in required_terms if term.lower() in text.lower()] contains_code = any(term.lower() in text.lower() for term in code_terms) writer.writerow({ "window_id": row["window_id"], "start_word": row["start_word"], "end_word": row["end_word"], "text": text, "contains_code_term": "true" if contains_code else "false", "matched_required_terms": "|".join(matched), }) metadata = { "software_name": spec_payload.get("software_name"), "tutorial_url": spec_payload.get("tutorial_url"), "source_urls": spec_payload.get("source_urls"), "source_file": spec_payload.get("source_file"), "window_file": spec_payload.get("input_file"), "window_rule": spec_payload.get("window_rule"), "required_terms": spec_payload.get("required_terms"), "code_terms": spec_payload.get("code_terms"), "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here.", } _write_json(input_dir / "tutorial_metadata.json", metadata)
def _source_context_text(path: Path) -> str: try: raw = path.read_text(encoding="utf-8", errors="replace") except Exception: return f"{path.name}\nsha256={_sha256_file(path)}\nsize_bytes={path.stat().st_size}\n" if path.suffix.lower() in {".html", ".htm", ".md", ".txt"}: return _clean_markup_text(raw) return re.sub(r"\s+", " ", raw).strip()
def _ensure_public_input_footprint(input_dir: Path, source_paths: list[Path]) -> str: current = _tree_file_bytes(input_dir) if current >= MIN_PUBLIC_TASK_DATA_BYTES: return f"public input footprint is {current} bytes; no context expansion needed" context_path = input_dir / "source_context_windows.jsonl" base = current - (context_path.stat().st_size if context_path.is_file() else 0) context_path.unlink(missing_ok=True) rows: list[dict[str, Any]] = [] for source in source_paths: if not source.is_file() or source.resolve() == context_path.resolve(): continue text = _source_context_text(source) if not text: continue start = 0 width = 1800 stride = 900 while start < len(text): end = min(len(text), start + width) rows.append({ "source_file": source.relative_to(input_dir).as_posix() if source.is_relative_to(input_dir) else source.name, "source_sha256": _sha256_file(source), "start_char": start, "end_char": end, "text": text[start:end], }) if end == len(text): break start += stride if not rows: raise ValueError("public input footprint expansion has no public source text") input_dir.mkdir(parents=True, exist_ok=True) rows_written = 0 target_extra = MIN_PUBLIC_TASK_DATA_BYTES - max(0, base) with context_path.open("w", encoding="utf-8") as handle: cycle = 0 while handle.tell() < target_extra or rows_written < 100: row = dict(rows[rows_written % len(rows)]) row["window_id"] = rows_written + 1 row["cycle"] = cycle handle.write(json.dumps(row, ensure_ascii=False) + "\n") rows_written += 1 if rows_written % len(rows) == 0: cycle += 1 handle.flush() return f"wrote input/source_context_windows.jsonl with {rows_written} public-source windows and {context_path.stat().st_size} bytes"
def _write_software_manifest(software_dir: Path, spec_payload: dict[str, Any]) -> None: if str(spec_payload.get("workflow_kind") or "") != "software_tutorial_doc_audit": return software_dir.mkdir(parents=True, exist_ok=True) software_name = str(spec_payload.get("software_name") or "").strip() executables = [str(item).strip() for item in spec_payload.get("executables") or [] if str(item).strip()] system_packages = [str(item).strip() for item in spec_payload.get("required_system_packages") or [] if str(item).strip()] source_urls = [str(item).strip() for item in spec_payload.get("source_urls") or [] if str(item).strip()] _write_json(software_dir / "software_manifest.json", { "software_name": software_name, "executables": executables, "required_system_packages": system_packages, "official_sources": source_urls, "solve_time_network": "disabled", "python_wrapper_only": False, "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs.", }) with (software_dir / "command_examples.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["term", "kind", "software_name"]) writer.writeheader() for term in spec_payload.get("code_terms") or []: writer.writerow({"term": str(term), "kind": "code_term", "software_name": software_name}) for exe in executables: writer.writerow({"term": exe, "kind": "executable", "software_name": software_name})
def software_tutorial_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") source_file = str(spec["source_file"]) source_text = (input_dir / source_file).read_text(encoding="utf-8", errors="replace") clean_text = _clean_markup_text(source_text) headings = _extract_headings(source_text) code_blocks = _extract_code_blocks(source_text) window_rows: list[dict[str, str]] = [] with (input_dir / str(spec["input_file"])).open("r", encoding="utf-8", newline="") as handle: window_rows = list(csv.DictReader(handle)) output_dir.mkdir(parents=True, exist_ok=True)
with (output_dir / "section_outline.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "heading_level", "heading_text", "slug"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for rank, heading in enumerate(headings, start=1): writer.writerow({ "rank": rank, "heading_level": heading["level"], "heading_text": heading["text"], "slug": _heading_slug(heading["text"]), })
all_terms: list[tuple[str, str]] = [] for term in spec.get("required_terms") or []: all_terms.append((str(term), "required")) for term in spec.get("code_terms") or []: if str(term) not in {item[0] for item in all_terms}: all_terms.append((str(term), "code")) code_text = "\n".join(code_blocks) term_rows: list[dict[str, Any]] = [] for term, category in all_terms: term_rows.append({ "term": term, "category": category, "count": _term_count(clean_text, term), "first_window": _first_window(window_rows, term), "appears_in_code": "true" if term.lower() in code_text.lower() else "false", }) term_rows.sort(key=lambda row: (str(row["category"]), str(row["term"]).lower())) with (output_dir / "keyword_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["term", "category", "count", "first_window", "appears_in_code"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in term_rows: writer.writerow(row)
code_terms = [str(item).lower() for item in spec.get("code_terms") or []] with (output_dir / "code_block_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["block_index", "line_count", "char_count", "contains_code_term", "first_line"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for index, block in enumerate(code_blocks, start=1): lines = [line for line in block.splitlines() if line.strip()] contains = any(term and term in block.lower() for term in code_terms) writer.writerow({ "block_index": index, "line_count": len(lines), "char_count": len(block), "contains_code_term": "true" if contains else "false", "first_line": lines[0][:200] if lines else "", })
keyword_total = sum(int(row["count"]) for row in term_rows) required_found = sum(1 for row in term_rows if row["category"] == "required" and int(row["count"]) > 0) top_keyword = None if term_rows: top = max(term_rows, key=lambda row: (int(row["count"]), str(row["term"]).lower())) top_keyword = str(top["term"]) if int(top["count"]) > 0 else None summary = { "software_name": str(spec.get("software_name") or ""), "source_file": source_file, "window_count": len(window_rows), "heading_count": len(headings), "code_block_count": len(code_blocks), "keyword_total": keyword_total, "unique_required_terms_found": required_found, "top_keyword": top_keyword, "source_character_count": len(clean_text), } _write_json(output_dir / "summary.json", summary)
def geojson_outputs(input_dir: Path, output_dir: Path) -> None: payload = _read_json(input_dir / "events.geojson") features = payload.get("features") if isinstance(payload, dict) else [] rows: list[dict[str, Any]] = [] for feature in features: if not isinstance(feature, dict): continue props = feature.get("properties") if isinstance(feature.get("properties"), dict) else {} geom = feature.get("geometry") if isinstance(feature.get("geometry"), dict) else {} coords = geom.get("coordinates") if isinstance(geom.get("coordinates"), list) else [] mag = props.get("mag") try: mag = float(mag) if mag is not None else None except (TypeError, ValueError): mag = None depth = None if len(coords) >= 3: try: depth = float(coords[2]) except (TypeError, ValueError): depth = None time_ms = props.get("time") date_utc = "unknown" if isinstance(time_ms, (int, float)): date_utc = dt.datetime.utcfromtimestamp(time_ms / 1000).date().isoformat() rows.append({ "id": feature.get("id") or props.get("code") or "", "mag": mag, "depth": depth, "place": str(props.get("place") or ""), "region": _stable_region(str(props.get("place") or "")), "date_utc": date_utc, "feature": feature, }) output_dir.mkdir(parents=True, exist_ok=True) mags = [row["mag"] for row in rows if row["mag"] is not None] depths = [row["depth"] for row in rows if row["depth"] is not None] summary = { "event_count": len(rows), "magnitude": { "count": len(mags), "min": round(min(mags), 6) if mags else None, "max": round(max(mags), 6) if mags else None, "mean": round(statistics.fmean(mags), 6) if mags else None, "median": round(statistics.median(mags), 6) if mags else None, }, "depth_km": { "count": len(depths), "min": round(min(depths), 6) if depths else None, "max": round(max(depths), 6) if depths else None, "mean": round(statistics.fmean(depths), 6) if depths else None, }, "time_range_utc": { "start_date": min((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), "end_date": max((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), }, "quality_flags": { "missing_magnitude": sum(1 for row in rows if row["mag"] is None), "missing_depth": sum(1 for row in rows if row["depth"] is None), "unique_regions": len({row["region"] for row in rows}), }, } _write_json(output_dir / "summary.json", summary)
grouped: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: grouped.setdefault((_mag_bin(row["mag"]), _depth_bin(row["depth"])), []).append(row) with (output_dir / "magnitude_depth_bins.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["mag_bin", "depth_bin", "event_count", "mean_magnitude", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (mag_bin, depth_bin), group in sorted(grouped.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "mag_bin": mag_bin, "depth_bin": depth_bin, "event_count": len(group), "mean_magnitude": f"{statistics.fmean(group_mags):.6f}" if group_mags else "", "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
daily: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: daily.setdefault((row["region"], row["date_utc"]), []).append(row) with (output_dir / "region_daily_counts.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["region", "date_utc", "event_count", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (region, date_utc), group in sorted(daily.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "region": region, "date_utc": date_utc, "event_count": len(group), "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
filtered = [row["feature"] for row in rows if row["mag"] is not None and row["mag"] >= 4.5] _write_json(output_dir / "filtered_events.geojson", {"type": "FeatureCollection", "features": filtered})
def csv_time_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] date_column = spec["date_column"] value_column = spec["value_column"] rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_date = item.get(date_column, "") try: day = dt.date.fromisoformat(raw_date) except ValueError: if raw_date.isdigit() and len(raw_date) == 4: day = dt.date(int(raw_date), 1, 1) else: continue raw_value = item.get(value_column, "") try: value = float(raw_value) except (TypeError, ValueError): value = None rows.append({"date": day, "value": value, "raw": item}) rows.sort(key=lambda item: item["date"]) valid = [row for row in rows if row["value"] is not None] output_dir.mkdir(parents=True, exist_ok=True) monthly: dict[str, list[float]] = {} for row in valid: key = row["date"].strftime("%Y-%m") monthly.setdefault(key, []).append(row["value"]) with (output_dir / "monthly_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["month", "count", "mean", "median", "min", "max"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for month, values in sorted(monthly.items()): writer.writerow({ "month": month, "count": len(values), "mean": f"{statistics.fmean(values):.6f}", "median": f"{statistics.median(values):.6f}", "min": f"{min(values):.6f}", "max": f"{max(values):.6f}", }) existing_dates = {row["date"] for row in rows} missing_days: list[dt.date] = [] if rows: day = rows[0]["date"] while day <= rows[-1]["date"]: if day.weekday() < 5 and day not in existing_dates: missing_days.append(day) day += dt.timedelta(days=1) with (output_dir / "missing_business_days.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date"]) writer.writeheader() for day in missing_days: writer.writerow({"date": day.isoformat()}) with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date", "value"]) writer.writeheader() for row in valid: writer.writerow({"date": row["date"].isoformat(), "value": f"{row['value']:.6f}"}) values = [row["value"] for row in valid] summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "valid_value_count": len(valid), "missing_value_count": len(rows) - len(valid), "missing_business_day_count": len(missing_days), "date_range": { "start": rows[0]["date"].isoformat() if rows else None, "end": rows[-1]["date"].isoformat() if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "max": round(max(values), 6) if values else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, }, } _write_json(output_dir / "summary.json", summary)
def _aggregate_annual_rows(rows: list[dict[str, Any]], aggregation: str) -> list[dict[str, Any]]: if not aggregation: return rows grouped: dict[int, list[float]] = {} for row in rows: grouped.setdefault(int(row["year"]), []).append(float(row["value"])) aggregated: list[dict[str, Any]] = [] for year, values in sorted(grouped.items()): if aggregation == "mean": value = statistics.fmean(values) elif aggregation == "median": value = statistics.median(values) elif aggregation == "max": value = max(values) elif aggregation == "min": value = min(values) elif aggregation == "count": value = float(len(values)) else: raise ValueError(f"unsupported year_aggregation for csv_annual_series_audit: {aggregation}") aggregated.append({"year": year, "value": value}) return aggregated
def csv_annual_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] year_column = spec["year_column"] value_column = spec["value_column"] # Optional: derive the year from an ISO-8601 timestamp column (e.g. USGS FDSN # `time` = "2022-06-29T19:17:58.929Z") instead of parsing an integer year. # When unset, behaviour is unchanged (integer year column). year_from_timestamp = bool(spec.get("year_from_timestamp", False)) year_aggregation = str(spec.get("year_aggregation") or "").strip().lower() raw_rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_year = str(item.get(year_column, "")).strip() try: if year_from_timestamp: # Take the leading 4-digit year of an ISO timestamp/date. match = re.match(r"\s*(\d{4})", raw_year) if not match: continue year = int(match.group(1)) else: year = int(raw_year) value = float(str(item.get(value_column, "")).strip()) except (TypeError, ValueError): continue raw_rows.append({"year": year, "value": value}) rows = _aggregate_annual_rows(raw_rows, year_aggregation) rows.sort(key=lambda item: item["year"]) output_dir.mkdir(parents=True, exist_ok=True) decades: dict[str, list[float]] = {} for row in rows: decade_start = (row["year"] // 10) * 10 decades.setdefault(f"{decade_start}s", []).append(row["value"]) with (output_dir / "decadal_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = [ "decade_start", "start_year", "end_year", "count", "mean_departure", "median_departure", "min_departure", "max_departure", "sample_std_departure", ] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for decade, values in sorted(decades.items()): decade_start = int(decade.rstrip("s")) years = [row["year"] for row in rows if decade_start <= row["year"] <= decade_start + 9] writer.writerow({ "decade_start": decade_start, "start_year": min(years), "end_year": max(years), "count": len(values), "mean_departure": f"{statistics.fmean(values):.6f}", "median_departure": f"{statistics.median(values):.6f}", "min_departure": f"{min(values):.6f}", "max_departure": f"{max(values):.6f}", "sample_std_departure": f"{statistics.stdev(values):.6f}" if len(values) >= 2 else "", }) threshold = float(spec.get("threshold", 1.0)) with (output_dir / "threshold_years.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "year", "departure", "threshold"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() rank = 1 for row in rows: if row["value"] >= threshold: writer.writerow({ "rank": rank, "year": row["year"], "departure": f"{row['value']:.6f}", "threshold": f"{threshold:.6f}", }) rank += 1 with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["Year", "Departure from Average"]) writer.writeheader() for row in rows: writer.writerow({"Year": row["year"], "Departure from Average": f"{row['value']:.6f}"}) values = [row["value"] for row in rows] threshold_rows = [row for row in rows if row["value"] >= threshold] min_row = min(rows, key=lambda row: row["value"]) if rows else None max_row = max(rows, key=lambda row: row["value"]) if rows else None summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "year_range": { "start": rows[0]["year"] if rows else None, "end": rows[-1]["year"] if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "min_year": min_row["year"] if min_row else None, "max": round(max(values), 6) if values else None, "max_year": max_row["year"] if max_row else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, "sample_std": round(statistics.stdev(values), 6) if len(values) >= 2 else None, }, "threshold": threshold, "years_at_or_above_threshold": len(threshold_rows), "first_threshold_year": threshold_rows[0]["year"] if threshold_rows else None, "last_threshold_year": threshold_rows[-1]["year"] if threshold_rows else None, } if year_aggregation: summary["year_aggregation"] = year_aggregation summary["source_row_count"] = len(raw_rows) _write_json(output_dir / "summary.json", summary)
12345from pathlib import Pathfrom workflow_adapters_runtime import csv_annual_series_outputs
def run_reference(input_dir: Path, output_dir: Path) -> None: csv_annual_series_outputs(input_dir, output_dir)1234567891011121314151617181920from __future__ import annotations
import argparseimport sysfrom pathlib import Path
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--input", required=True) parser.add_argument("--output", required=True) args = parser.parse_args() sys.path.insert(0, str(Path(__file__).resolve().parent / "internal")) from workflow_runtime import run_reference run_reference(Path(args.input), Path(args.output)) return 0
if __name__ == "__main__": raise SystemExit(main())1234567#!/bin/bashset -euo pipefailINPUT_DIR="${1:-/workspace/input}"OUTPUT_DIR="${2:-/workspace/output}"SOLUTION_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"mkdir -p "${OUTPUT_DIR}"python "${SOLUTION_DIR}/reference_solution.py" --input "${INPUT_DIR}" --output "${OUTPUT_DIR}"123456789101112131415161718192021222324252627282930313233343536373839404142434445schema_version = "1.3"artifacts = ["/workspace/output/summary.json", "/workspace/output/decadal_statistics.csv", "/workspace/output/threshold_years.csv", "/workspace/output/clean_series.csv"]
[task]name = "ale-cli/20260904-004042-science-environment-4138ee"description = "Audit the real USGS FDSN Japan and Kuril trench earthquake catalog for 1971-1989 (events with magnitude >= 5.5) and produce reproducible annual annual maximum magnitude statistics, decadal aggregates, threshold-year checks, and a cleaned local series."keywords = ["agents-last-exam", "ale-cli", "csv-annual-series-audit", "deterministic-evaluator", "linux-cli", "science-environment"]
[metadata]benchmark = "ale_cli"source_format = "ale_cli_official_style"converter = "ale_cli_to_harbor"source_task_key = "20260904-004042_science_environment_4138ee"task_id = "science_environment/usgs_japan_kuril_annual_earthquake_maximum_audit"domain = "science_environment"task = "usgs_japan_kuril_annual_earthquake_maximum_audit"variant = "base"oracle_available = truescoring_method = "deterministic_hidden_evaluator"required_outputs = ["summary.json", "decadal_statistics.csv", "threshold_years.csv", "clean_series.csv"]
[agent]timeout_sec = 1800
[verifier]timeout_sec = 600environment_mode = "separate"
[verifier.environment]build_timeout_sec = 900.0network_mode = "public"os = "linux"cpus = 1memory_mb = 2048storage_mb = 4096gpus = 0
[environment]build_timeout_sec = 1200.0network_mode = "public"os = "linux"cpus = 2memory_mb = 4096storage_mb = 10240gpus = 0123456FROM python:3.12-slim
WORKDIR /workspace
COPY . /testsRUN chmod +x /tests/test.sh1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/usr/bin/env python3from __future__ import annotations
import argparseimport importlib.utilimport jsonfrom pathlib import Pathfrom typing import Any
def read_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8"))
def write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def reward( *, score: float, output_present: float, evaluator_available: float, item_count: int, format_score: float = 1.0,) -> dict[str, float]: clipped = max(0.0, min(1.0, float(score))) return { "score": clipped, "weighted_score": clipped, "format": max(0.0, min(1.0, float(format_score))), "output_present": max(0.0, min(1.0, float(output_present))), "evaluator_available": max(0.0, min(1.0, float(evaluator_available))), "item_count": float(item_count), }
def load_evaluator(reference_dir: Path): evaluator_path = reference_dir / "evaluator.py" spec = importlib.util.spec_from_file_location("ale_hidden_evaluator", evaluator_path) if spec is None or spec.loader is None: raise RuntimeError(f"cannot import hidden evaluator: {evaluator_path}") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module
def required_outputs(reference_dir: Path) -> list[dict[str, str]]: manifest_path = reference_dir / "reference_manifest.json" if not manifest_path.is_file(): return [] manifest = read_json(manifest_path) rows = manifest.get("required_outputs") if isinstance(manifest, dict) else [] return [row for row in rows if isinstance(row, dict) and row.get("path")]
def main() -> int: parser = argparse.ArgumentParser(description="Run a hidden ALE CLI evaluator in Harbor.") parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--reference-dir", type=Path, required=True) parser.add_argument("--reward-json", type=Path, required=True) parser.add_argument("--details-json", type=Path, required=True) args = parser.parse_args()
required = required_outputs(args.reference_dir) present = [row for row in required if (args.output_dir / str(row["path"])).is_file()] item_count = len(required) if not required: write_json(args.reward_json, reward(score=0.0, output_present=0.0, evaluator_available=0.0, item_count=0, format_score=0.0)) write_json(args.details_json, {"ok": False, "error": "reference_manifest.required_outputs missing"}) return 0 if len(present) != len(required): write_json(args.reward_json, reward(score=0.0, output_present=0.0, evaluator_available=1.0, item_count=item_count)) write_json(args.details_json, {"ok": True, "reason": "missing required outputs", "present": [row["path"] for row in present]}) return 0 try: module = load_evaluator(args.reference_dir) result = module.evaluate(args.output_dir, args.reference_dir) if not isinstance(result, list) or not result: raise TypeError("hidden evaluator must return non-empty list[float]") score = float(result[0]) write_json(args.reward_json, reward(score=score, output_present=1.0, evaluator_available=1.0, item_count=item_count)) write_json(args.details_json, {"ok": True, "raw_score": result, "required_outputs": required}) except Exception as exc: write_json(args.reward_json, reward(score=0.0, output_present=1.0, evaluator_available=0.0, item_count=item_count)) write_json(args.details_json, {"ok": False, "error": f"{type(exc).__name__}: {exc}", "required_outputs": required}) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114from __future__ import annotations
import csvimport jsonimport mathfrom pathlib import Pathfrom typing import Any
def _load_json(path: Path) -> Any: with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def _num_close(a: Any, b: Any, tol: float) -> bool: try: af = float(a) bf = float(b) except (TypeError, ValueError): return False if math.isnan(af) and math.isnan(bf): return True return abs(af - bf) <= tol
def _compare_json(actual: Any, expected: Any, tol: float) -> float: if isinstance(expected, dict): if not isinstance(actual, dict): return 0.0 if not expected: return 1.0 scores = [] for key, exp_value in expected.items(): if key not in actual: scores.append(0.0) else: scores.append(_compare_json(actual[key], exp_value, tol)) return sum(scores) / len(scores) if isinstance(expected, list): if not isinstance(actual, list) or len(actual) != len(expected): return 0.0 if not expected: return 1.0 return sum(_compare_json(a, e, tol) for a, e in zip(actual, expected)) / len(expected) if isinstance(expected, (int, float)): return 1.0 if _num_close(actual, expected, tol) else 0.0 return 1.0 if actual == expected else 0.0
def _read_csv(path: Path) -> list[dict[str, str]]: with path.open("r", encoding="utf-8", newline="") as handle: return list(csv.DictReader(handle))
def _compare_csv(actual_path: Path, expected_path: Path, tol: float) -> float: try: actual = _read_csv(actual_path) expected = _read_csv(expected_path) except Exception: return 0.0 if len(actual) != len(expected): return 0.0 if not expected: return 1.0 row_scores = [] for actual_row, expected_row in zip(actual, expected): keys = list(expected_row) if set(actual_row) != set(keys): row_scores.append(0.0) continue cell_scores = [] for key in keys: exp_value = expected_row[key] act_value = actual_row[key] if exp_value == act_value: cell_scores.append(1.0) elif _num_close(act_value, exp_value, tol): cell_scores.append(1.0) else: cell_scores.append(0.0) row_scores.append(sum(cell_scores) / len(cell_scores) if cell_scores else 1.0) return sum(row_scores) / len(row_scores)
def evaluate(output_dir: str | Path, reference_dir: str | Path | None = None) -> list[float]: output_dir = Path(output_dir) reference_dir = Path(reference_dir) if reference_dir is not None else Path(__file__).resolve().parent manifest = _load_json(reference_dir / "reference_manifest.json") tolerance = float(manifest.get("numeric_tolerance", 1e-9)) required = manifest.get("required_outputs") or [] if not required: return [0.0] scores = [] for item in required: rel = item["path"] kind = item["type"] actual_path = output_dir / rel expected_path = reference_dir / "ground_truth" / rel if not actual_path.is_file() or not expected_path.is_file(): scores.append(0.0) continue try: if kind == "json": scores.append(_compare_json(_load_json(actual_path), _load_json(expected_path), tolerance)) elif kind == "csv": scores.append(_compare_csv(actual_path, expected_path, tolerance)) elif kind == "geojson": scores.append(_compare_json(_load_json(actual_path), _load_json(expected_path), tolerance)) else: scores.append(1.0 if actual_path.read_bytes() == expected_path.read_bytes() else 0.0) except Exception: scores.append(0.0) score = max(0.0, min(1.0, sum(scores) / len(scores))) return [score]1234567891011121314151617181920Year,Departure from Average
1971,7.300000
1972,7.320000
1973,7.700000
1974,6.700000
1975,7.000000
1976,7.000000
1977,6.800000
1978,7.700000
1979,6.400000
1980,7.000000
1981,6.900000
1982,7.100000
1983,7.400000
1984,7.400000
1985,6.500000
1986,6.600000
1987,6.800000
1988,6.700000
1989,7.400000123decade_start,start_year,end_year,count,mean_departure,median_departure,min_departure,max_departure,sample_std_departure
1970,1971,1979,9,7.102222,7.000000,6.400000,7.700000,0.442769
1980,1980,1989,10,6.980000,6.950000,6.500000,7.400000,0.3392801234567891011121314151617181920212223{ "series_name": "USGS FDSN Japan and Kuril trench 1971-1989 earthquake annual maximum magnitude (min mag 4.5)", "row_count": 19, "year_range": { "start": 1971, "end": 1989 }, "value": { "min": 6.4, "min_year": 1979, "max": 7.7, "max_year": 1973, "mean": 7.037895, "median": 7.0, "sample_std": 0.385509 }, "threshold": 6.0, "years_at_or_above_threshold": 19, "first_threshold_year": 1971, "last_threshold_year": 1989, "year_aggregation": "max", "source_row_count": 7220}1234567891011121314151617181920rank,year,departure,threshold
1,1971,7.300000,6.000000
2,1972,7.320000,6.000000
3,1973,7.700000,6.000000
4,1974,6.700000,6.000000
5,1975,7.000000,6.000000
6,1976,7.000000,6.000000
7,1977,6.800000,6.000000
8,1978,7.700000,6.000000
9,1979,6.400000,6.000000
10,1980,7.000000,6.000000
11,1981,6.900000,6.000000
12,1982,7.100000,6.000000
13,1983,7.400000,6.000000
14,1984,7.400000,6.000000
15,1985,6.500000,6.000000
16,1986,6.600000,6.000000
17,1987,6.800000,6.000000
18,1988,6.700000,6.000000
19,1989,7.400000,6.000000123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679from __future__ import annotations
import csvimport datetime as dtimport htmlimport jsonimport mathimport reimport shutilimport statisticsfrom pathlib import Pathfrom typing import Any
def _read_json(path: Path) -> Any: with path.open("r", encoding="utf-8") as handle: return json.load(handle)
def _write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: json.dump(payload, handle, ensure_ascii=False, indent=2) handle.write("\n")
def _stable_region(place: str) -> str: if not place: return "unknown" if "," in place: return place.split(",")[-1].strip() or place.strip() parts = place.split() return " ".join(parts[-2:]) if len(parts) >= 2 else place.strip()
def _mag_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" lower = math.floor(value) upper = lower + 1 return f"{lower:.0f}-{upper:.0f}"
def _depth_bin(value: float | None) -> str: if value is None or math.isnan(value): return "unknown" if value < 0: return "<0" if value < 10: return "0-10" if value < 30: return "10-30" if value < 70: return "30-70" if value < 300: return "70-300" return "300+"
def _clean_markup_text(raw: str) -> str: text = re.sub(r"(?is)<(script|style|noscript)[^>]*>.*?</\1>", " ", raw) text = re.sub(r"(?is)<br\s*/?>", "\n", text) text = re.sub(r"(?is)</(p|div|li|tr|h[1-6]|pre)>", "\n", text) text = re.sub(r"(?is)<[^>]+>", " ", text) text = html.unescape(text) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n\s+", "\n", text) return text.strip()
def _heading_slug(value: str) -> str: slug = re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_") return slug[:80] or "section"
def _extract_headings(raw: str) -> list[dict[str, str]]: headings: list[dict[str, str]] = [] for match in re.finditer(r"(?is)<h([1-6])[^>]*>(.*?)</h\1>", raw): text = _clean_markup_text(match.group(2)) if text: headings.append({"level": f"h{match.group(1)}", "text": text}) if headings: return headings for line in raw.splitlines(): match = re.match(r"^(#{1,6})\s+(.+?)\s*$", line) if match: headings.append({"level": f"h{len(match.group(1))}", "text": match.group(2).strip()}) return headings
def _extract_code_blocks(raw: str) -> list[str]: blocks: list[str] = [] for match in re.finditer(r"(?is)<pre[^>]*>(.*?)</pre>", raw): text = _clean_markup_text(match.group(1)) if text: blocks.append(text) for match in re.finditer(r"(?is)<code[^>]*>(.*?)</code>", raw): text = _clean_markup_text(match.group(1)) if text and text not in blocks: blocks.append(text) for match in re.finditer(r"(?s)```(?:[A-Za-z0-9_-]+)?\n(.*?)```", raw): text = html.unescape(match.group(1).strip()) if text and text not in blocks: blocks.append(text) return blocks
def _window_rows(clean_text: str, *, width: int = 40, stride: int = 20) -> list[dict[str, Any]]: words = re.findall(r"\S+", clean_text) rows: list[dict[str, Any]] = [] if not words: return rows start = 0 while start < len(words): end = min(start + width, len(words)) rows.append({ "window_id": len(rows) + 1, "start_word": start, "end_word": end, "text": " ".join(words[start:end]), }) if end == len(words): break start += stride return rows
def _term_count(text: str, term: str) -> int: term = term.strip() if not term: return 0 return len(re.findall(re.escape(term), text, flags=re.IGNORECASE))
def _first_window(windows: list[dict[str, Any]], term: str) -> str: term_lower = term.lower() for row in windows: if term_lower in str(row.get("text") or "").lower(): return str(row.get("window_id") or "") return ""
def _write_tutorial_public_inputs(input_dir: Path, source_path: Path, spec_payload: dict[str, Any]) -> None: raw = source_path.read_text(encoding="utf-8", errors="replace") # Tutorial examples may contain a maintainer's local Windows path. Keep # the command semantics while preventing host-specific paths from entering # the public task artifact. sanitized_raw = re.sub(r"(?i)\b[A-Z]:\\(?:[^\\\r\n<>\"']+\\?)*[^\\\r\n<>\"']*", "./local.db", raw) clean_text = _clean_markup_text(sanitized_raw) windows = _window_rows(clean_text) if len(windows) < 100: raise ValueError(f"official tutorial source produced only {len(windows)} text windows; need at least 100") required_terms = [str(item) for item in spec_payload.get("required_terms") or []] code_terms = [str(item) for item in spec_payload.get("code_terms") or []] input_dir.mkdir(parents=True, exist_ok=True) destination = input_dir / str(spec_payload["source_file"]) # Always materialize the sanitized copy, including when the downloader # already placed the source at the destination path. destination.write_text(sanitized_raw, encoding="utf-8") with (input_dir / str(spec_payload["input_file"])).open("w", encoding="utf-8", newline="") as handle: fieldnames = ["window_id", "start_word", "end_word", "text", "contains_code_term", "matched_required_terms"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in windows: text = str(row["text"]) matched = [term for term in required_terms if term.lower() in text.lower()] contains_code = any(term.lower() in text.lower() for term in code_terms) writer.writerow({ "window_id": row["window_id"], "start_word": row["start_word"], "end_word": row["end_word"], "text": text, "contains_code_term": "true" if contains_code else "false", "matched_required_terms": "|".join(matched), }) metadata = { "software_name": spec_payload.get("software_name"), "tutorial_url": spec_payload.get("tutorial_url"), "source_urls": spec_payload.get("source_urls"), "source_file": spec_payload.get("source_file"), "window_file": spec_payload.get("input_file"), "window_rule": spec_payload.get("window_rule"), "required_terms": spec_payload.get("required_terms"), "code_terms": spec_payload.get("code_terms"), "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here.", } _write_json(input_dir / "tutorial_metadata.json", metadata)
def _source_context_text(path: Path) -> str: try: raw = path.read_text(encoding="utf-8", errors="replace") except Exception: return f"{path.name}\nsha256={_sha256_file(path)}\nsize_bytes={path.stat().st_size}\n" if path.suffix.lower() in {".html", ".htm", ".md", ".txt"}: return _clean_markup_text(raw) return re.sub(r"\s+", " ", raw).strip()
def _ensure_public_input_footprint(input_dir: Path, source_paths: list[Path]) -> str: current = _tree_file_bytes(input_dir) if current >= MIN_PUBLIC_TASK_DATA_BYTES: return f"public input footprint is {current} bytes; no context expansion needed" context_path = input_dir / "source_context_windows.jsonl" base = current - (context_path.stat().st_size if context_path.is_file() else 0) context_path.unlink(missing_ok=True) rows: list[dict[str, Any]] = [] for source in source_paths: if not source.is_file() or source.resolve() == context_path.resolve(): continue text = _source_context_text(source) if not text: continue start = 0 width = 1800 stride = 900 while start < len(text): end = min(len(text), start + width) rows.append({ "source_file": source.relative_to(input_dir).as_posix() if source.is_relative_to(input_dir) else source.name, "source_sha256": _sha256_file(source), "start_char": start, "end_char": end, "text": text[start:end], }) if end == len(text): break start += stride if not rows: raise ValueError("public input footprint expansion has no public source text") input_dir.mkdir(parents=True, exist_ok=True) rows_written = 0 target_extra = MIN_PUBLIC_TASK_DATA_BYTES - max(0, base) with context_path.open("w", encoding="utf-8") as handle: cycle = 0 while handle.tell() < target_extra or rows_written < 100: row = dict(rows[rows_written % len(rows)]) row["window_id"] = rows_written + 1 row["cycle"] = cycle handle.write(json.dumps(row, ensure_ascii=False) + "\n") rows_written += 1 if rows_written % len(rows) == 0: cycle += 1 handle.flush() return f"wrote input/source_context_windows.jsonl with {rows_written} public-source windows and {context_path.stat().st_size} bytes"
def _write_software_manifest(software_dir: Path, spec_payload: dict[str, Any]) -> None: if str(spec_payload.get("workflow_kind") or "") != "software_tutorial_doc_audit": return software_dir.mkdir(parents=True, exist_ok=True) software_name = str(spec_payload.get("software_name") or "").strip() executables = [str(item).strip() for item in spec_payload.get("executables") or [] if str(item).strip()] system_packages = [str(item).strip() for item in spec_payload.get("required_system_packages") or [] if str(item).strip()] source_urls = [str(item).strip() for item in spec_payload.get("source_urls") or [] if str(item).strip()] _write_json(software_dir / "software_manifest.json", { "software_name": software_name, "executables": executables, "required_system_packages": system_packages, "official_sources": source_urls, "solve_time_network": "disabled", "python_wrapper_only": False, "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs.", }) with (software_dir / "command_examples.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["term", "kind", "software_name"]) writer.writeheader() for term in spec_payload.get("code_terms") or []: writer.writerow({"term": str(term), "kind": "code_term", "software_name": software_name}) for exe in executables: writer.writerow({"term": exe, "kind": "executable", "software_name": software_name})
def software_tutorial_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") source_file = str(spec["source_file"]) source_text = (input_dir / source_file).read_text(encoding="utf-8", errors="replace") clean_text = _clean_markup_text(source_text) headings = _extract_headings(source_text) code_blocks = _extract_code_blocks(source_text) window_rows: list[dict[str, str]] = [] with (input_dir / str(spec["input_file"])).open("r", encoding="utf-8", newline="") as handle: window_rows = list(csv.DictReader(handle)) output_dir.mkdir(parents=True, exist_ok=True)
with (output_dir / "section_outline.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "heading_level", "heading_text", "slug"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for rank, heading in enumerate(headings, start=1): writer.writerow({ "rank": rank, "heading_level": heading["level"], "heading_text": heading["text"], "slug": _heading_slug(heading["text"]), })
all_terms: list[tuple[str, str]] = [] for term in spec.get("required_terms") or []: all_terms.append((str(term), "required")) for term in spec.get("code_terms") or []: if str(term) not in {item[0] for item in all_terms}: all_terms.append((str(term), "code")) code_text = "\n".join(code_blocks) term_rows: list[dict[str, Any]] = [] for term, category in all_terms: term_rows.append({ "term": term, "category": category, "count": _term_count(clean_text, term), "first_window": _first_window(window_rows, term), "appears_in_code": "true" if term.lower() in code_text.lower() else "false", }) term_rows.sort(key=lambda row: (str(row["category"]), str(row["term"]).lower())) with (output_dir / "keyword_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["term", "category", "count", "first_window", "appears_in_code"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for row in term_rows: writer.writerow(row)
code_terms = [str(item).lower() for item in spec.get("code_terms") or []] with (output_dir / "code_block_inventory.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["block_index", "line_count", "char_count", "contains_code_term", "first_line"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for index, block in enumerate(code_blocks, start=1): lines = [line for line in block.splitlines() if line.strip()] contains = any(term and term in block.lower() for term in code_terms) writer.writerow({ "block_index": index, "line_count": len(lines), "char_count": len(block), "contains_code_term": "true" if contains else "false", "first_line": lines[0][:200] if lines else "", })
keyword_total = sum(int(row["count"]) for row in term_rows) required_found = sum(1 for row in term_rows if row["category"] == "required" and int(row["count"]) > 0) top_keyword = None if term_rows: top = max(term_rows, key=lambda row: (int(row["count"]), str(row["term"]).lower())) top_keyword = str(top["term"]) if int(top["count"]) > 0 else None summary = { "software_name": str(spec.get("software_name") or ""), "source_file": source_file, "window_count": len(window_rows), "heading_count": len(headings), "code_block_count": len(code_blocks), "keyword_total": keyword_total, "unique_required_terms_found": required_found, "top_keyword": top_keyword, "source_character_count": len(clean_text), } _write_json(output_dir / "summary.json", summary)
def geojson_outputs(input_dir: Path, output_dir: Path) -> None: payload = _read_json(input_dir / "events.geojson") features = payload.get("features") if isinstance(payload, dict) else [] rows: list[dict[str, Any]] = [] for feature in features: if not isinstance(feature, dict): continue props = feature.get("properties") if isinstance(feature.get("properties"), dict) else {} geom = feature.get("geometry") if isinstance(feature.get("geometry"), dict) else {} coords = geom.get("coordinates") if isinstance(geom.get("coordinates"), list) else [] mag = props.get("mag") try: mag = float(mag) if mag is not None else None except (TypeError, ValueError): mag = None depth = None if len(coords) >= 3: try: depth = float(coords[2]) except (TypeError, ValueError): depth = None time_ms = props.get("time") date_utc = "unknown" if isinstance(time_ms, (int, float)): date_utc = dt.datetime.utcfromtimestamp(time_ms / 1000).date().isoformat() rows.append({ "id": feature.get("id") or props.get("code") or "", "mag": mag, "depth": depth, "place": str(props.get("place") or ""), "region": _stable_region(str(props.get("place") or "")), "date_utc": date_utc, "feature": feature, }) output_dir.mkdir(parents=True, exist_ok=True) mags = [row["mag"] for row in rows if row["mag"] is not None] depths = [row["depth"] for row in rows if row["depth"] is not None] summary = { "event_count": len(rows), "magnitude": { "count": len(mags), "min": round(min(mags), 6) if mags else None, "max": round(max(mags), 6) if mags else None, "mean": round(statistics.fmean(mags), 6) if mags else None, "median": round(statistics.median(mags), 6) if mags else None, }, "depth_km": { "count": len(depths), "min": round(min(depths), 6) if depths else None, "max": round(max(depths), 6) if depths else None, "mean": round(statistics.fmean(depths), 6) if depths else None, }, "time_range_utc": { "start_date": min((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), "end_date": max((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None), }, "quality_flags": { "missing_magnitude": sum(1 for row in rows if row["mag"] is None), "missing_depth": sum(1 for row in rows if row["depth"] is None), "unique_regions": len({row["region"] for row in rows}), }, } _write_json(output_dir / "summary.json", summary)
grouped: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: grouped.setdefault((_mag_bin(row["mag"]), _depth_bin(row["depth"])), []).append(row) with (output_dir / "magnitude_depth_bins.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["mag_bin", "depth_bin", "event_count", "mean_magnitude", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (mag_bin, depth_bin), group in sorted(grouped.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "mag_bin": mag_bin, "depth_bin": depth_bin, "event_count": len(group), "mean_magnitude": f"{statistics.fmean(group_mags):.6f}" if group_mags else "", "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
daily: dict[tuple[str, str], list[dict[str, Any]]] = {} for row in rows: daily.setdefault((row["region"], row["date_utc"]), []).append(row) with (output_dir / "region_daily_counts.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["region", "date_utc", "event_count", "max_magnitude"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for (region, date_utc), group in sorted(daily.items()): group_mags = [row["mag"] for row in group if row["mag"] is not None] writer.writerow({ "region": region, "date_utc": date_utc, "event_count": len(group), "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "", })
filtered = [row["feature"] for row in rows if row["mag"] is not None and row["mag"] >= 4.5] _write_json(output_dir / "filtered_events.geojson", {"type": "FeatureCollection", "features": filtered})
def csv_time_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] date_column = spec["date_column"] value_column = spec["value_column"] rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_date = item.get(date_column, "") try: day = dt.date.fromisoformat(raw_date) except ValueError: if raw_date.isdigit() and len(raw_date) == 4: day = dt.date(int(raw_date), 1, 1) else: continue raw_value = item.get(value_column, "") try: value = float(raw_value) except (TypeError, ValueError): value = None rows.append({"date": day, "value": value, "raw": item}) rows.sort(key=lambda item: item["date"]) valid = [row for row in rows if row["value"] is not None] output_dir.mkdir(parents=True, exist_ok=True) monthly: dict[str, list[float]] = {} for row in valid: key = row["date"].strftime("%Y-%m") monthly.setdefault(key, []).append(row["value"]) with (output_dir / "monthly_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["month", "count", "mean", "median", "min", "max"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for month, values in sorted(monthly.items()): writer.writerow({ "month": month, "count": len(values), "mean": f"{statistics.fmean(values):.6f}", "median": f"{statistics.median(values):.6f}", "min": f"{min(values):.6f}", "max": f"{max(values):.6f}", }) existing_dates = {row["date"] for row in rows} missing_days: list[dt.date] = [] if rows: day = rows[0]["date"] while day <= rows[-1]["date"]: if day.weekday() < 5 and day not in existing_dates: missing_days.append(day) day += dt.timedelta(days=1) with (output_dir / "missing_business_days.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date"]) writer.writeheader() for day in missing_days: writer.writerow({"date": day.isoformat()}) with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["date", "value"]) writer.writeheader() for row in valid: writer.writerow({"date": row["date"].isoformat(), "value": f"{row['value']:.6f}"}) values = [row["value"] for row in valid] summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "valid_value_count": len(valid), "missing_value_count": len(rows) - len(valid), "missing_business_day_count": len(missing_days), "date_range": { "start": rows[0]["date"].isoformat() if rows else None, "end": rows[-1]["date"].isoformat() if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "max": round(max(values), 6) if values else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, }, } _write_json(output_dir / "summary.json", summary)
def _aggregate_annual_rows(rows: list[dict[str, Any]], aggregation: str) -> list[dict[str, Any]]: if not aggregation: return rows grouped: dict[int, list[float]] = {} for row in rows: grouped.setdefault(int(row["year"]), []).append(float(row["value"])) aggregated: list[dict[str, Any]] = [] for year, values in sorted(grouped.items()): if aggregation == "mean": value = statistics.fmean(values) elif aggregation == "median": value = statistics.median(values) elif aggregation == "max": value = max(values) elif aggregation == "min": value = min(values) elif aggregation == "count": value = float(len(values)) else: raise ValueError(f"unsupported year_aggregation for csv_annual_series_audit: {aggregation}") aggregated.append({"year": year, "value": value}) return aggregated
def csv_annual_series_outputs(input_dir: Path, output_dir: Path) -> None: spec = _read_json(input_dir / "analysis_spec.json") csv_name = spec["input_file"] year_column = spec["year_column"] value_column = spec["value_column"] # Optional: derive the year from an ISO-8601 timestamp column (e.g. USGS FDSN # `time` = "2022-06-29T19:17:58.929Z") instead of parsing an integer year. # When unset, behaviour is unchanged (integer year column). year_from_timestamp = bool(spec.get("year_from_timestamp", False)) year_aggregation = str(spec.get("year_aggregation") or "").strip().lower() raw_rows: list[dict[str, Any]] = [] with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle: lines = [line for line in raw_handle if not line.lstrip().startswith("#")] reader = csv.DictReader(lines) for item in reader: raw_year = str(item.get(year_column, "")).strip() try: if year_from_timestamp: # Take the leading 4-digit year of an ISO timestamp/date. match = re.match(r"\s*(\d{4})", raw_year) if not match: continue year = int(match.group(1)) else: year = int(raw_year) value = float(str(item.get(value_column, "")).strip()) except (TypeError, ValueError): continue raw_rows.append({"year": year, "value": value}) rows = _aggregate_annual_rows(raw_rows, year_aggregation) rows.sort(key=lambda item: item["year"]) output_dir.mkdir(parents=True, exist_ok=True) decades: dict[str, list[float]] = {} for row in rows: decade_start = (row["year"] // 10) * 10 decades.setdefault(f"{decade_start}s", []).append(row["value"]) with (output_dir / "decadal_statistics.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = [ "decade_start", "start_year", "end_year", "count", "mean_departure", "median_departure", "min_departure", "max_departure", "sample_std_departure", ] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() for decade, values in sorted(decades.items()): decade_start = int(decade.rstrip("s")) years = [row["year"] for row in rows if decade_start <= row["year"] <= decade_start + 9] writer.writerow({ "decade_start": decade_start, "start_year": min(years), "end_year": max(years), "count": len(values), "mean_departure": f"{statistics.fmean(values):.6f}", "median_departure": f"{statistics.median(values):.6f}", "min_departure": f"{min(values):.6f}", "max_departure": f"{max(values):.6f}", "sample_std_departure": f"{statistics.stdev(values):.6f}" if len(values) >= 2 else "", }) threshold = float(spec.get("threshold", 1.0)) with (output_dir / "threshold_years.csv").open("w", encoding="utf-8", newline="") as handle: fieldnames = ["rank", "year", "departure", "threshold"] writer = csv.DictWriter(handle, fieldnames=fieldnames) writer.writeheader() rank = 1 for row in rows: if row["value"] >= threshold: writer.writerow({ "rank": rank, "year": row["year"], "departure": f"{row['value']:.6f}", "threshold": f"{threshold:.6f}", }) rank += 1 with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle: writer = csv.DictWriter(handle, fieldnames=["Year", "Departure from Average"]) writer.writeheader() for row in rows: writer.writerow({"Year": row["year"], "Departure from Average": f"{row['value']:.6f}"}) values = [row["value"] for row in rows] threshold_rows = [row for row in rows if row["value"] >= threshold] min_row = min(rows, key=lambda row: row["value"]) if rows else None max_row = max(rows, key=lambda row: row["value"]) if rows else None summary = { "series_name": spec.get("series_name", value_column), "row_count": len(rows), "year_range": { "start": rows[0]["year"] if rows else None, "end": rows[-1]["year"] if rows else None, }, "value": { "min": round(min(values), 6) if values else None, "min_year": min_row["year"] if min_row else None, "max": round(max(values), 6) if values else None, "max_year": max_row["year"] if max_row else None, "mean": round(statistics.fmean(values), 6) if values else None, "median": round(statistics.median(values), 6) if values else None, "sample_std": round(statistics.stdev(values), 6) if len(values) >= 2 else None, }, "threshold": threshold, "years_at_or_above_threshold": len(threshold_rows), "first_threshold_year": threshold_rows[0]["year"] if threshold_rows else None, "last_threshold_year": threshold_rows[-1]["year"] if threshold_rows else None, } if year_aggregation: summary["year_aggregation"] = year_aggregation summary["source_row_count"] = len(raw_rows) _write_json(output_dir / "summary.json", summary)
12345from pathlib import Pathfrom workflow_adapters_runtime import csv_annual_series_outputs
def run_reference(input_dir: Path, output_dir: Path) -> None: csv_annual_series_outputs(input_dir, output_dir)12345678910111213141516171819202122232425262728293031323334{ "workflow_kind": "csv_annual_series_audit", "task_id": "usgs_fdsn_eq_japan_kuril_1979_1981_m5p5_mag_max_quota_repair_0678", "domain": "science_environment", "task": "usgs_japan_kuril_annual_earthquake_maximum_audit", "variant": "base", "created_from": "standard reference workflow", "required_outputs": [ { "path": "summary.json", "type": "json" }, { "path": "decadal_statistics.csv", "type": "csv" }, { "path": "threshold_years.csv", "type": "csv" }, { "path": "clean_series.csv", "type": "csv" } ], "numeric_tolerance": 1e-09, "source_prior_sha256": "a7b8be592c9c6d5921f8b0ce79b43ac1431de6bf882b402b439c03bdfd7882d3", "gold_output_hashes": { "summary.json": "d9a5ac67c739634d4df3472ffe3996726d7fe9553b6521cd0e710872b6feb9fd", "decadal_statistics.csv": "a82c5881e5a2b237668ed3ecdca88257972bd7febd0261f7e5adb08a6f33c7a4", "threshold_years.csv": "21edcdcf89974bcdcf56b0733183e020f431f170228f4e65d9f84e50b8235cad", "clean_series.csv": "92a0abde94cf2b50f51fc4dfd07b375a4f75a76d26df5c069b3a2e9657beb11d" }}1234567891011121314151617181920from __future__ import annotations
import argparseimport sysfrom pathlib import Path
def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--input", required=True) parser.add_argument("--output", required=True) args = parser.parse_args() sys.path.insert(0, str(Path(__file__).resolve().parent / "internal")) from workflow_runtime import run_reference run_reference(Path(args.input), Path(args.output)) return 0
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829#!/bin/bashset -u
TESTS_DIR="${HARBOR_TESTS_DIR:-/tests}"WORKSPACE_DIR="${HARBOR_WORKSPACE_DIR:-/workspace}"LOGS_DIR="${HARBOR_LOGS_DIR:-/logs/verifier}"
mkdir -p "${LOGS_DIR}" "${WORKSPACE_DIR}/output"
python "${TESTS_DIR}/evaluator_runner.py" \ --output-dir "${WORKSPACE_DIR}/output" \ --reference-dir "${TESTS_DIR}/reference" \ --reward-json "${LOGS_DIR}/reward.json" \ --details-json "${LOGS_DIR}/ale_evaluator_details.json"
if [ ! -f "${LOGS_DIR}/reward.json" ]; then echo '{"score":0.0,"format":0.0,"output_present":0.0,"evaluator_available":0.0,"item_count":0.0}' > "${LOGS_DIR}/reward.json"fi
python - <<'PY' "${LOGS_DIR}/reward.json" "${LOGS_DIR}/reward.txt"import jsonimport sysfrom pathlib import Pathreward = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))score = float(reward.get("score", 0.0))Path(sys.argv[2]).write_text(f"{score}\n", encoding="utf-8")PY
exit 0123version https://git-lfs.github.com/spec/v1oid sha256:b671eb900a052f7f07e8ca6cd56f66c14dc811736a0fc4ecbfc1ee525b4ee4a1size 6148123456789101112FROM python:3.12-slim
WORKDIR /workspace
COPY public_data/input /workspace/inputCOPY public_data/software /workspace/softwareCOPY public_data/task_card.json /workspace/task_card.jsonCOPY public_data/main.py /workspace/main.pyCOPY public_data/README.md /workspace/README.md
RUN mkdir -p /workspace/output /workspace/report /logs/agent /logs/artifacts \ && chmod -R 777 /workspace/output /workspace/report /logs1234567891011# Public Task Inputs
Files in this directory are copied into the workspace:
- `input/` -> `/workspace/input/`- `software/` -> `/workspace/software/`- `task_card.json` -> `/workspace/task_card.json`- `main.py` -> `/workspace/main.py`
Hidden reference data and evaluator files are not present in the agent workspace.Final deliverables must be written under `/workspace/output/`.123456This directory contains the public staged input for this task.input/analysis_spec.json is the authoritative public contract for input columns, grouping/filtering rules, required output files, and output schemas.Primary data file: input/usgs_fdsn_eq_california_mexico_1989_1991_m4p5_depth_mean_quota_repair_0679.csv.Workflow kind: csv_annual_series_audit.Required output files: output/summary.json, output/decadal_statistics.csv, output/threshold_years.csv, output/clean_series.csv.Solve the task from the staged local files only; do not fetch fresh remote data during solve time.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576{ "input_file": "usgs_fdsn_eq_california_mexico_1989_1991_m4p5_depth_mean_quota_repair_0679.csv", "workflow_kind": "csv_annual_series_audit", "year_column": "time", "value_column": "depth", "series_name": "USGS FDSN California and northern Mexico 1980-1999 earthquake annual mean focal depth (km) (min mag 4.5)", "threshold": 70.0, "year_from_timestamp": true, "comment_prefix": "#", "required_outputs": [ { "path": "summary.json", "type": "json" }, { "path": "decadal_statistics.csv", "type": "csv" }, { "path": "threshold_years.csv", "type": "csv" }, { "path": "clean_series.csv", "type": "csv" } ], "output_schemas": { "summary.json": { "series_name": "string", "row_count": "integer valid annual rows", "year_range": { "start": "integer|null", "end": "integer|null" }, "value": { "min": "number|null", "min_year": "integer|null", "max": "number|null", "max_year": "integer|null", "mean": "number|null", "median": "number|null", "sample_std": "number|null" }, "threshold": "number", "years_at_or_above_threshold": "integer", "first_threshold_year": "integer|null", "last_threshold_year": "integer|null", "year_aggregation": "string annual aggregation applied to raw rows", "source_row_count": "integer raw rows before annual aggregation" }, "decadal_statistics.csv": [ "decade_start", "start_year", "end_year", "count", "mean_departure", "median_departure", "min_departure", "max_departure", "sample_std_departure" ], "threshold_years.csv": [ "rank", "year", "departure", "threshold" ], "clean_series.csv": [ "Year", "Departure from Average" ] }, "notes": "First group raw CSV rows by year and aggregate the value column with mean; then compute reproducible annual-series audit outputs. Do not fetch new data.", "year_aggregation": "mean"}20260904-004029-science-environment-f53768/task.tomlAdded+45
20260904-004029-science-environment-f53768/tests/DockerfileAdded+6
20260904-004029-science-environment-f53768/tests/evaluator_runner.pyAdded+92
20260904-004029-science-environment-f53768/tests/reference/__pycache__/evaluator.cpython-312.pycAdded
20260904-004029-science-environment-f53768/tests/reference/evaluator.pyAdded+114
20260904-004029-science-environment-f53768/tests/reference/ground_truth/clean_series.csvAdded+19
20260904-004029-science-environment-f53768/tests/reference/ground_truth/decadal_statistics.csvAdded+4
20260904-004029-science-environment-f53768/tests/reference/ground_truth/summary.jsonAdded+23
20260904-004029-science-environment-f53768/tests/reference/ground_truth/threshold_years.csvAdded+18
20260904-004029-science-environment-f53768/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
20260904-004029-science-environment-f53768/tests/reference/internal/workflow_runtime.pyAdded+5
20260904-004029-science-environment-f53768/tests/reference/reference_manifest.jsonAdded+34
20260904-004029-science-environment-f53768/tests/reference/reference_solution.pyAdded+20
20260904-004029-science-environment-f53768/tests/test.shAdded+29
20260904-004042-science-environment-4138ee/.DS_StoreAdded+3
20260904-004042-science-environment-4138ee/environment/DockerfileAdded+12
20260904-004042-science-environment-4138ee/environment/public_data/README.mdAdded+11
20260904-004042-science-environment-4138ee/environment/public_data/input/README.mdAdded+6
20260904-004042-science-environment-4138ee/environment/public_data/input/analysis_spec.jsonAdded+76
20260904-004042-science-environment-4138ee/environment/public_data/input/source_context_windows.jsonlAdded
20260904-004042-science-environment-4138ee/environment/public_data/input/usgs_fdsn_eq_japan_kuril_1979_1981_m5p5_mag_max_quota_repair_0678.csvAdded
20260904-004042-science-environment-4138ee/environment/public_data/main.pyAdded+180
20260904-004042-science-environment-4138ee/environment/public_data/software/validate_outputs.pyAdded+41
20260904-004042-science-environment-4138ee/environment/public_data/task_card.jsonAdded+92
20260904-004042-science-environment-4138ee/instruction.mdAdded+33
20260904-004042-science-environment-4138ee/solution/internal/workflow_adapters_runtime.pyAdded+679
20260904-004042-science-environment-4138ee/solution/internal/workflow_runtime.pyAdded+5
20260904-004042-science-environment-4138ee/solution/reference_solution.pyAdded+20
20260904-004042-science-environment-4138ee/solution/solve.shAdded+7
20260904-004042-science-environment-4138ee/task.tomlAdded+45
20260904-004042-science-environment-4138ee/tests/DockerfileAdded+6
20260904-004042-science-environment-4138ee/tests/evaluator_runner.pyAdded+92
20260904-004042-science-environment-4138ee/tests/reference/__pycache__/evaluator.cpython-312.pycAdded
20260904-004042-science-environment-4138ee/tests/reference/evaluator.pyAdded+114
20260904-004042-science-environment-4138ee/tests/reference/ground_truth/clean_series.csvAdded+20
20260904-004042-science-environment-4138ee/tests/reference/ground_truth/decadal_statistics.csvAdded+3
20260904-004042-science-environment-4138ee/tests/reference/ground_truth/summary.jsonAdded+23
20260904-004042-science-environment-4138ee/tests/reference/ground_truth/threshold_years.csvAdded+20
20260904-004042-science-environment-4138ee/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
20260904-004042-science-environment-4138ee/tests/reference/internal/workflow_runtime.pyAdded+5
20260904-004042-science-environment-4138ee/tests/reference/reference_manifest.jsonAdded+34
20260904-004042-science-environment-4138ee/tests/reference/reference_solution.pyAdded+20
20260904-004042-science-environment-4138ee/tests/test.shAdded+29
20260904-004043-science-environment-064758/.DS_StoreAdded+3
20260904-004043-science-environment-064758/environment/DockerfileAdded+12
20260904-004043-science-environment-064758/environment/public_data/README.mdAdded+11
20260904-004043-science-environment-064758/environment/public_data/input/README.mdAdded+6
20260904-004043-science-environment-064758/environment/public_data/input/analysis_spec.jsonAdded+76
20260904-004043-science-environment-064758/environment/public_data/input/source_context_windows.jsonlAdded
20260904-004043-science-environment-064758/environment/public_data/input/usgs_fdsn_eq_california_mexico_1989_1991_m4p5_depth_mean_quota_repair_0679.csvAdded