Upload folder using huggingface_hub (part 152)
Browse filesFiles changed (20)
- 20260906-225059-science-environment-e9df60/tests/reference/evaluator.pyAdded+114
- 20260906-225059-science-environment-e9df60/tests/reference/ground_truth/clean_series.csvAdded+6
- 20260906-225059-science-environment-e9df60/tests/reference/ground_truth/decadal_statistics.csvAdded+2
- 20260906-225059-science-environment-e9df60/tests/reference/ground_truth/summary.jsonAdded+23
- 20260906-225059-science-environment-e9df60/tests/reference/ground_truth/threshold_years.csvAdded+6
- 20260906-225059-science-environment-e9df60/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
- 20260906-225059-science-environment-e9df60/tests/reference/internal/workflow_runtime.pyAdded+5
- 20260906-225059-science-environment-e9df60/tests/reference/reference_manifest.jsonAdded+34
- 20260906-225059-science-environment-e9df60/tests/reference/reference_solution.pyAdded+20
- 20260906-225059-science-environment-e9df60/tests/test.shAdded+29
- 20260906-225459-computing-math-8a0117/.DS_StoreAdded+3
- 20260906-225459-computing-math-8a0117/environment/DockerfileAdded+12
- 20260906-225459-computing-math-8a0117/environment/public_data/README.mdAdded+11
- 20260906-225459-computing-math-8a0117/environment/public_data/input/README.mdAdded+6
- 20260906-225459-computing-math-8a0117/environment/public_data/input/analysis_spec.jsonAdded+90
- 20260906-225459-computing-math-8a0117/environment/public_data/input/source_context_windows.jsonlAdded
- 20260906-225459-computing-math-8a0117/environment/public_data/input/tutorial_metadata.jsonAdded+29
- 20260906-225459-computing-math-8a0117/environment/public_data/input/tutorial_source.htmlAdded
- 20260906-225459-computing-math-8a0117/environment/public_data/input/tutorial_text_windows.csvAdded
- 20260906-225459-computing-math-8a0117/environment/public_data/main.pyAdded+180
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]123456Year,Departure from Average
1985,73.270323
1986,88.672381
1987,81.799398
1988,90.228165
1989,94.66381312decade_start,start_year,end_year,count,mean_departure,median_departure,min_departure,max_departure,sample_std_departure
1980,1985,1989,5,85.726816,88.672381,73.270323,94.663813,8.3575901234567891011121314151617181920212223{ "series_name": "USGS FDSN Andes subduction zone 1985-1989 earthquake annual mean focal depth (km) (min mag 4.5)", "row_count": 5, "year_range": { "start": 1985, "end": 1989 }, "value": { "min": 73.270323, "min_year": 1985, "max": 94.663813, "max_year": 1989, "mean": 85.726816, "median": 88.672381, "sample_std": 8.35759 }, "threshold": 70.0, "years_at_or_above_threshold": 5, "first_threshold_year": 1985, "last_threshold_year": 1989, "year_aggregation": "mean", "source_row_count": 1685}123456rank,year,departure,threshold
1,1985,73.270323,70.000000
2,1986,88.672381,70.000000
3,1987,81.799398,70.000000
4,1988,90.228165,70.000000
5,1989,94.663813,70.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": "repair2_20260906_001_repair_20260906_fdsn_0058_usgs_fdsn_eq_andes_1985_1989_m4p5_depth_mean", "domain": "science_environment", "task": "usgs_andes_annual_focal_depth_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": "fd6ee98563ab26db5fb82d900c57809ed2eb235aff283ca01dc07bbd8abf15c4", "gold_output_hashes": { "summary.json": "2d873c8cbdb6676a5626ce462107033b4fb635cbc1ae7785fb5354dbf6b08567", "decadal_statistics.csv": "d9e87bfe09875105a2e597ae03627e46a7c9e45fa0c07401a0f777b618eb2b9b", "threshold_years.csv": "7e6370e930a9b0f2694cdf6ef0482e08bd17ad0ec5241560248c0f63bdd885e1", "clean_series.csv": "eda8adfcc45dfe4261641bd561146754c8bb9fb99f1a9426098cd8a9a5571144" }}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:d70527e65cb1492c4ccf4f41e8e90f357f856f474bc6a7448311892e27ac2a30size 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/tutorial_text_windows.csv.Workflow kind: software_tutorial_doc_audit.Required output files: output/summary.json, output/section_outline.csv, output/keyword_inventory.csv, output/code_block_inventory.csv.Solve the task from the staged local files only; do not fetch fresh remote data during solve time.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990{ "input_file": "tutorial_text_windows.csv", "source_file": "tutorial_source.html", "workflow_kind": "software_tutorial_doc_audit", "software_name": "R", "tutorial_url": "https://cran.r-project.org/web/views/TimeSeries.html", "source_urls": [ "https://cran.r-project.org/web/views/TimeSeries.html" ], "window_rule": { "cleaning": "Strip HTML/script/style tags, decode entities, collapse whitespace, and preserve document text order.", "window_size_words": 40, "stride_words": 20, "minimum_windows": 100 }, "heading_rule": "Extract h1-h6 headings from HTML; if no HTML headings are present, use Markdown # headings.", "keyword_rule": "Count case-insensitive occurrences of required_terms and code_terms in the cleaned tutorial text.", "required_terms": [ "R", "vector", "data frame", "function", "factor" ], "code_terms": [ "plot", "lm(", "summary", "<-" ], "executables": [ "R", "Rscript" ], "required_system_packages": [ "r-base" ], "required_outputs": [ { "path": "summary.json", "type": "json" }, { "path": "section_outline.csv", "type": "csv" }, { "path": "keyword_inventory.csv", "type": "csv" }, { "path": "code_block_inventory.csv", "type": "csv" } ], "output_schemas": { "summary.json": { "software_name": "string", "source_file": "string", "window_count": "integer", "heading_count": "integer", "code_block_count": "integer", "keyword_total": "integer", "unique_required_terms_found": "integer", "top_keyword": "string|null", "source_character_count": "integer" }, "section_outline.csv": [ "rank", "heading_level", "heading_text", "slug" ], "keyword_inventory.csv": [ "term", "category", "count", "first_window", "appears_in_code" ], "code_block_inventory.csv": [ "block_index", "line_count", "char_count", "contains_code_term", "first_line" ] }, "notes": "Audit the staged offline official tutorial corpus. Do not fetch fresh documentation. All counts must be derived from the staged source file and tutorial_text_windows.csv."}1234567891011121314151617181920212223242526272829{ "software_name": "R", "tutorial_url": "https://cran.r-project.org/web/views/TimeSeries.html", "source_urls": [ "https://cran.r-project.org/web/views/TimeSeries.html" ], "source_file": "tutorial_source.html", "window_file": "tutorial_text_windows.csv", "window_rule": { "cleaning": "Strip HTML/script/style tags, decode entities, collapse whitespace, and preserve document text order.", "window_size_words": 40, "stride_words": 20, "minimum_windows": 100 }, "required_terms": [ "R", "vector", "data frame", "function", "factor" ], "code_terms": [ "plot", "lm(", "summary", "<-" ], "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here."}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", "computing_math/audit_offline_cran_time_series_documentation"), "taskPrompt": "Task card has not been rendered yet; this fallback exists for stage-03 hook smoke only.", "metadata": { "domain": "computing_math", "task": "audit_offline_cran_time_series_documentation", "variant": "base", "domain_name": "computing_math", "task_name": "audit_offline_cran_time_series_documentation", "variant_name": "base", "requires_task_data": True, "task_dir": "/media/user/data/agenthle/computing_math/audit_offline_cran_time_series_documentation/base", "input_dir": "/media/user/data/agenthle/computing_math/audit_offline_cran_time_series_documentation/base/input", "software_dir": "/media/user/data/agenthle/computing_math/audit_offline_cran_time_series_documentation/base/software", "remote_output_dir": "/media/user/data/agenthle/computing_math/audit_offline_cran_time_series_documentation/base/output", "reference_dir": "/media/user/data/agenthle/computing_math/audit_offline_cran_time_series_documentation/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]20260906-225059-science-environment-e9df60/tests/reference/evaluator.pyAdded+114
20260906-225059-science-environment-e9df60/tests/reference/ground_truth/clean_series.csvAdded+6
20260906-225059-science-environment-e9df60/tests/reference/ground_truth/decadal_statistics.csvAdded+2
20260906-225059-science-environment-e9df60/tests/reference/ground_truth/summary.jsonAdded+23
20260906-225059-science-environment-e9df60/tests/reference/ground_truth/threshold_years.csvAdded+6
20260906-225059-science-environment-e9df60/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
20260906-225059-science-environment-e9df60/tests/reference/internal/workflow_runtime.pyAdded+5
20260906-225059-science-environment-e9df60/tests/reference/reference_manifest.jsonAdded+34
20260906-225059-science-environment-e9df60/tests/reference/reference_solution.pyAdded+20
20260906-225059-science-environment-e9df60/tests/test.shAdded+29
20260906-225459-computing-math-8a0117/.DS_StoreAdded+3
20260906-225459-computing-math-8a0117/environment/DockerfileAdded+12
20260906-225459-computing-math-8a0117/environment/public_data/README.mdAdded+11
20260906-225459-computing-math-8a0117/environment/public_data/input/README.mdAdded+6
20260906-225459-computing-math-8a0117/environment/public_data/input/analysis_spec.jsonAdded+90
20260906-225459-computing-math-8a0117/environment/public_data/input/source_context_windows.jsonlAdded
20260906-225459-computing-math-8a0117/environment/public_data/input/tutorial_metadata.jsonAdded+29
20260906-225459-computing-math-8a0117/environment/public_data/input/tutorial_source.htmlAdded
20260906-225459-computing-math-8a0117/environment/public_data/input/tutorial_text_windows.csvAdded
20260906-225459-computing-math-8a0117/environment/public_data/main.pyAdded+180