Upload folder using huggingface_hub (part 175)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- 20260907-002634-transport-safety-6f2c6a/tests/evaluator_runner.pyAdded+92
- 20260907-002634-transport-safety-6f2c6a/tests/reference/__pycache__/evaluator.cpython-312.pycAdded
- 20260907-002634-transport-safety-6f2c6a/tests/reference/evaluator.pyAdded+114
- 20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/code_block_inventory.csvAdded+30
- 20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/keyword_inventory.csvAdded+14
- 20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/section_outline.csvAdded+48
- 20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/summary.jsonAdded+11
- 20260907-002634-transport-safety-6f2c6a/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
- 20260907-002634-transport-safety-6f2c6a/tests/reference/internal/workflow_runtime.pyAdded+5
- 20260907-002634-transport-safety-6f2c6a/tests/reference/reference_manifest.jsonAdded+34
- 20260907-002634-transport-safety-6f2c6a/tests/reference/reference_solution.pyAdded+20
- 20260907-002634-transport-safety-6f2c6a/tests/test.shAdded+29
- 20260907-002650-transport-safety-0ac894/.DS_StoreAdded+3
- 20260907-002650-transport-safety-0ac894/environment/DockerfileAdded+12
- 20260907-002650-transport-safety-0ac894/environment/public_data/README.mdAdded+11
- 20260907-002650-transport-safety-0ac894/environment/public_data/input/README.mdAdded+6
- 20260907-002650-transport-safety-0ac894/environment/public_data/input/analysis_spec.jsonAdded+93
- 20260907-002650-transport-safety-0ac894/environment/public_data/input/source_context_windows.jsonlAdded
- 20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_metadata.jsonAdded+29
- 20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_source.htmlAdded+1215
- 20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_text_windows.csvAdded
- 20260907-002650-transport-safety-0ac894/environment/public_data/main.pyAdded+180
- 20260907-002650-transport-safety-0ac894/environment/public_data/software/command_examples.csvAdded+9
- 20260907-002650-transport-safety-0ac894/environment/public_data/software/software_manifest.jsonAdded+19
- 20260907-002650-transport-safety-0ac894/environment/public_data/software/validate_outputs.pyAdded+41
- 20260907-002650-transport-safety-0ac894/environment/public_data/task_card.jsonAdded+114
- 20260907-002650-transport-safety-0ac894/instruction.mdAdded+33
- 20260907-002650-transport-safety-0ac894/solution/internal/workflow_adapters_runtime.pyAdded+679
- 20260907-002650-transport-safety-0ac894/solution/internal/workflow_runtime.pyAdded+5
- 20260907-002650-transport-safety-0ac894/solution/reference_solution.pyAdded+20
- 20260907-002650-transport-safety-0ac894/solution/solve.shAdded+7
- 20260907-002650-transport-safety-0ac894/task.tomlAdded+45
- 20260907-002650-transport-safety-0ac894/tests/DockerfileAdded+6
- 20260907-002650-transport-safety-0ac894/tests/evaluator_runner.pyAdded+92
- 20260907-002650-transport-safety-0ac894/tests/reference/__pycache__/evaluator.cpython-312.pycAdded
- 20260907-002650-transport-safety-0ac894/tests/reference/evaluator.pyAdded+114
- 20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/code_block_inventory.csvAdded+30
- 20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/keyword_inventory.csvAdded+10
- 20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/section_outline.csvAdded+48
- 20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/summary.jsonAdded+11
- 20260907-002650-transport-safety-0ac894/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
- 20260907-002650-transport-safety-0ac894/tests/reference/internal/workflow_runtime.pyAdded+5
- 20260907-002650-transport-safety-0ac894/tests/reference/reference_manifest.jsonAdded+34
- 20260907-002650-transport-safety-0ac894/tests/reference/reference_solution.pyAdded+20
- 20260907-002650-transport-safety-0ac894/tests/test.shAdded+29
- 20260907-002702-transport-safety-26060d/.DS_StoreAdded+3
- 20260907-002702-transport-safety-26060d/environment/DockerfileAdded+12
- 20260907-002702-transport-safety-26060d/environment/public_data/README.mdAdded+11
- 20260907-002702-transport-safety-26060d/environment/public_data/input/README.mdAdded+6
- 20260907-002702-transport-safety-26060d/environment/public_data/input/analysis_spec.jsonAdded+93
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192#!/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]123456789101112131415161718192021222324252627282930block_index,line_count,char_count,contains_code_term,first_line
1,31,1824,true,---
2,1,50,false,If you also use connections and types the call is:
3,31,1715,true,"The options used here, including their abbreviations, are documented on"
4,27,6599,true,the straight brackets ('\[' and '\]')
5,167,12846,true,"As you may notice, only the first node named ""0"", which is the node in"
6,100,9194,true,"This will cause the nodes *id0*,*id23* and *id24* to be joined into a"
7,30,2425,false,"Within this example, we have used explicit definitions of edges. An"
8,2,90,false,"If you would like to disallow passenger cars and taxis, the following"
9,22,3547,false,The definition of a lane contains the following optional attributes:
10,21,1586,false,Defining this element for an edge will affect all lanes of the edge that
11,10,564,false,What happens here is the following: 30meters from its begin
12,10,585,false,There are several things to note:
13,16,1827,false,The definition of a split uses the following attributes:
14,11,633,true,Manual specification of roundabouts is a useful supplement for the
15,6,278,false,In the above input the inner-most lanes of edges *a* and *b* are
16,21,1195,true,It is also possible to remove all edges of a specific type (see below)
17,1,96,true,The according types file looks like this (see [SUMO edge type file](../SUMO_edge_type_file.md)):
18,8,429,true,"As you can see, we have joined the edges into three classes ""a"", ""b"","
19,40,3274,true,"the value of *vClass* must be a single class from [the list of possible vehicle classes](../Definition_of_Vehicles,_Vehicle_Types,_and_Routes.md#abstract_vehicle_class)."
20,14,1357,true,This tells [netconvert](../netconvert.md) not only that vehicles shall be
21,25,7111,true,"Here, a connection from the edge's ""*<FROM_EDGE_ID\>*"" lane with the number *<INT_1\>* is build to the lane *<INT_2\>* of the edge ""*<TO_EDGE_ID\>*"". Lanes are counted from the right (outer) to the le"
22,16,1609,true,The attributes are the same as for the
23,17,988,true,This will trigger all connections from edge with id `FROM_EDGE_ID` to be removed and re-guessed.
24,9,574,true,"As you may see in the next picture, the horizontal edges within the"
25,12,831,false,The built network looks like this:
26,17,1168,false,"As one may see, it was necessary to prohibit all connections from a"
27,45,3451,true,# Traffic Light Program Definition
28,27,3881,false,The attributes are described in the following.
29,7,1226,false,The attributes are described in the following.1234567891011121314term,category,count,first_window,appears_in_code
.net.xml,code,9,1,true
.rou.xml,code,0,,false
duarouter,code,0,,false
netconvert,code,49,3,true
netedit,code,7,101,true
sumo,code,44,1,true
edge,required,242,8,true
network,required,52,1,true
node,required,105,7,true
route,required,4,107,true
simulation,required,26,2,true
SUMO,required,44,1,true
vehicle,required,75,64,true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748rank,heading_level,heading_text,slug
1,h1,Source 1: PlainXML.md,source_1_plainxml_md
2,h1,Node Descriptions,node_descriptions
3,h2,Traffic lights,traffic_lights
4,h3,tlType,tltype
5,h3,tlLayout,tllayout
6,h2,Node types,node_types
7,h2,Right-of-way,right_of_way
8,h3,"rightOfWay=""default""",rightofway_default
9,h3,"rightOfWay=""mixedPriority""",rightofway_mixedpriority
10,h3,"rightOfWay=""edgePriority""",rightofway_edgepriority
11,h3,"rightOfWay=""allwayStop""",rightofway_allwaystop
12,h3,Special Cases,special_cases
13,h3,Understanding right-of-way rules in a Network,understanding_right_of_way_rules_in_a_network
14,h3,Modifying Right-of-Way,modifying_right_of_way
15,h2,Fringe,fringe
16,h2,Joining Nodes,joining_nodes
17,h3,Reasons for joining node clusters,reasons_for_joining_node_clusters
18,h3,Algorithm for joining node clusters,algorithm_for_joining_node_clusters
19,h3,Specifying and excluding explicit joins,specifying_and_excluding_explicit_joins
20,h3,Connections after joining nodes,connections_after_joining_nodes
21,h1,Edge Descriptions,edge_descriptions
22,h2,SpreadType,spreadtype
23,h2,"Road access permissions (allow, disallow)",road_access_permissions_allow_disallow
24,h2,Lane-specific Definitions,lane_specific_definitions
25,h3,lane change restrictions,lane_change_restrictions
26,h2,Stop Offsets,stop_offsets
27,h2,Road Segment Refining,road_segment_refining
28,h2,Roundabouts,roundabouts
29,h2,Neighboring opposite-direction Lanes,neighboring_opposite_direction_lanes
30,h2,Deleting edges or lanes,deleting_edges_or_lanes
31,h1,Type Descriptions,type_descriptions
32,h2,vehicle-class specific speed limits,vehicle_class_specific_speed_limits
33,h2,speed on junction,speed_on_junction
34,h1,Connection Descriptions,connection_descriptions
35,h2,Explicitly setting which Edge / Lane is connected to which,explicitly_setting_which_edge_lane_is_connected_to_which
36,h3,Edge-to-Edge connectivity,edge_to_edge_connectivity
37,h3,Lane-to-Lane connectivity,lane_to_lane_connectivity
38,h3,Deleting connections,deleting_connections
39,h3,Patching connections and guessing again,patching_connections_and_guessing_again
40,h3,Examples,examples
41,h2,Setting Connection Priorities,setting_connection_priorities
42,h2,Multiple connections from the same edge to the same target lane,multiple_connections_from_the_same_edge_to_the_same_target_lane
43,h1,Traffic Light Program Definition,traffic_light_program_definition
44,h2,traffic light definitions,traffic_light_definitions
45,h2,controlled connections,controlled_connections
46,h1,Pedestrian Crossings,pedestrian_crossings
47,h1,Walking Areas,walking_areas1234567891011{ "software_name": "SUMO", "source_file": "tutorial_source.html", "window_count": 425, "heading_count": 47, "code_block_count": 29, "keyword_total": 657, "unique_required_terms_found": 7, "top_keyword": "edge", "source_character_count": 56655}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 software_tutorial_outputs
def run_reference(input_dir: Path, output_dir: Path) -> None: software_tutorial_outputs(input_dir, output_dir)12345678910111213141516171819202122232425262728293031323334{ "workflow_kind": "software_tutorial_doc_audit", "task_id": "repair3_20260907_087_repair2_20260906_093_repair_20260906_software_0110", "domain": "transport_safety", "task": "sumo_plainxml_document_audit", "variant": "base", "created_from": "standard reference workflow", "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" } ], "numeric_tolerance": 1e-09, "source_prior_sha256": "e338ca2c987a612024504d976fa1bc9c500c8779e986043eca1a870f6ef9a2a0", "gold_output_hashes": { "summary.json": "ad19c14767717b9d4629e558fa65a06fcca1a98bfac9c9fed0fe8da6e5c7327a", "section_outline.csv": "2e5418f96aca2bcb5a3ea72bbbcddf959a0be5efa9736f865052f0bd46ba61ec", "keyword_inventory.csv": "dcaa39e02418fd64be64cc0ce2f308e83ee27824e59c72316430cdfac6987379", "code_block_inventory.csv": "db7636954eb57d7e16189292f25bcc9caa12bb176037d4734554f5193cfa807f" }}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:99db9dc5f3ad356ceb54cf28f45f3471fbd12d7c661084975a3120b9e928f425size 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293{ "input_file": "tutorial_text_windows.csv", "source_file": "tutorial_source.html", "workflow_kind": "software_tutorial_doc_audit", "software_name": "SUMO", "tutorial_url": "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md", "source_urls": [ "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md" ], "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": [ "network", "route", "edge", "node", "vehicle" ], "code_terms": [ "duarouter", "netedit", ".net.xml", ".rou.xml" ], "executables": [ "sumo", "netconvert", "duarouter", "netedit" ], "required_system_packages": [ "sumo", "sumo-tools" ], "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": "SUMO", "tutorial_url": "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md", "source_urls": [ "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md" ], "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": [ "network", "route", "edge", "node", "vehicle" ], "code_terms": [ "duarouter", "netedit", ".net.xml", ".rou.xml" ], "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215# Source 1: PlainXML.md
- URL: https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md- SHA256: afd8cecb140607cd783cd8efe6a610b521df3c8c4762047f07b7044c4080599d- Bytes: 78218
```markdown---title: PlainXML---
**SUMO**-Networks have two representations:
- A set of *plain-xml* files which describe the network topology and geometry- The *.net.xml* file which is loaded into the simulation. This contains lots of generated information such as structures within an intersection and right-of-way logic.
[netconvert](../netconvert.md) can [convert freely](../Networks/Export.md#plain) and without information lossbetween these two formats. Only the *plain-xml* format is meant to beedited by the users. In contrast, the *.net.xml* format has lots ofsubtle inter-dependencies between its elements and should never beedited by hand. The *plain-xml* format is described below.
It is possible to load a *net.xml* file along with *plain-xml* patchfiles into [netconvert](../netconvert.md) to modify some aspects ofan existing network.
To defined a network at least two files are needed: one file for nodesand another one for the streets between them. Please notice that herein,"node" and "junction" mean the same as well as "edge" and "street" do(see also [Glossary](../Other/Glossary.md)). Besides defining thenodes and edges, you can also join edge attributes by type and setexplicit connections between edges or lanes. We will describe how eachof these four file types should look like in the following chapters.Further information on road networks may be also found in the [SUMO Road Networks](../Networks/SUMO_Road_Networks.md) description.
After you have generated the files as described below - you need atleast the edges and the nodes-files, using type and/or a connectionsfile is optional - you should run [netconvert](../netconvert.md) tobuild the network. If you only use edges and nodes, stored in"MyEdges.edg.xml" and "MyNodes.nod.xml" respectively, the call shouldlook like:
```netconvert --node-files=MyNodes.nod.xml --edge-files=MyEdges.edg.xml \ --output-file=MySUMONet.net.xml```
If you also use connections and types the call is:
```netconvert --node-files=MyNodes.nod.xml --edge-files=MyEdges.edg.xml \ --connection-files=MyConnections.con.xml --type-files=MyTypes.typ.xml \ --output-file=MySUMONet.net.xml```
The options used here, including their abbreviations, are documented onthe [netconvert manual page](../netconvert.md#input).
Maybe your edge definitions are incomplete or buggy. If you still wantto import your network, you can try passing **--ignore-errors** to[netconvert](../netconvert.md). In this case, edges which are notdefined properly are omitted, but [netconvert](../netconvert.md)tries to build the network anyway. You may also flip the network aroundthe horizontal axis. Use option **--flip-y-axis** for this.
The structures of the files described in the following are alsoavailable as XML Schema Definitions:
- [nodes files](#node_descriptions): <https://sumo.dlr.de/xsd/nodes_file.xsd>- [edges files](#edge_descriptions): <https://sumo.dlr.de/xsd/edges_file.xsd>- [types files](#type_descriptions): <https://sumo.dlr.de/xsd/types_file.xsd>- [connections files](#connection_descriptions): <https://sumo.dlr.de/xsd/connections_file.xsd>- [tllogic files](#traffic_light_program_definition): <https://sumo.dlr.de/xsd/tllogic_file.xsd>
# Node Descriptions
| Node Descriptions | ||--------------------|---------------------------------|| Filename extension | .nod.xml || Type of content | Nodes (intersections/junctions) || Open format? | Yes || SUMO specific? | Yes || XML Schema | [nodes_file.xsd](https://sumo.dlr.de/xsd/nodes_file.xsd) |
Within the nodes-files, normally having the extension ".nod.xml" (see[Known Extensions](../Other/File_Extensions.md)), every node isdescribed in a single line which looks like this:
```xml <node id="<STRING>" x="<FLOAT>" y="<FLOAT>" [type="<TYPE>"]/>```
the straight brackets ('\[' and '\]')indicate that the parameter is optional. Each of these attributes has acertain meaning and value range:
| Attribute Name | Value Type | Description || --------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------- || **id** | id (string) | The name of the node || **x** | float | The x-position of the node on the plane in meters || **y** | float | The y-position of the node on the plane in meters || z | float | The z-position of the node on the plane in meters || type | enum ( "priority", "traffic_light", "right_before_left", "left_before_right", "unregulated", "priority_stop", "traffic_light_unregulated", "allway_stop", "rail_signal", "zipper", "traffic_light_right_on_red", "rail_crossing") | An optional type for the node || tlType | enum ( **"static"**, "actuated", "delay_based") | An optional type for the [traffic light algorithm](../Simulation/Traffic_Lights.md#type_actuated)| tlLayout | enum ( **"opposites"**, "incoming", "alternateOneWay") | An optional layout for the traffic light plan (see below)| tl | id (string) | An optional id for the traffic light program. Nodes with the same tl-value will be joined into a single program || radius | positive float | optional turning radius (for all corners) for that node in meters *(default 1.5)* || shape | List of positions; each position is encoded in x,y or x,y,z in meters (do not separate the numbers with a space\!). | A custom shape for that node. If less than two positions are given, netconvert will reset that node to use a computed shape. || keepClear | bool | Whether the [junction-blocking-heuristic](../Simulation/Intersections.md#junction_blocking) should be activated at this node *(default true)* || rightOfWay | string | Set algorithm for computing [\#Right-of-way](#right-of-way). Allowed values are *default*, *edgePriority*, *mixedPriority*, and *allwayStop* || fringe | string | Clarify whether this junction is on the [network fringe](#fringe). Allowed values are *default*, *outer* and *inner* || roundabout | string | Clarify whether this junction may be part of a roundabout. Allowed values are *default*, *1* and *0* || controlledInner | list of edge ids | Edges which shall be controlled by a joined TLS despite being incoming as well as outgoing to the jointly controlled nodes |
!!! note You may also use lon/lat values in place of x/y but you then need to add option **--proj.utm** in order to project your coordinates into the cartesian plane.
When writing your nodes-file, please do not forget to embed your nodedefinitions into an opening and a closing "tag". A complete file shouldlike the example below, which is the node file "cross3l.nod.xml" for theexamples "{{SUMO}}/data/examples/netbuild/types/cross_usingtypes/" and"{{SUMO}}/data/examples/netbuild/types/cross_notypes/" example.
```xml<nodes> <!-- The opening tag -->
<node id="0" x="0.0" y="0.0" type="traffic_light"/> <!-- def. of node "0" -->
<node id="1" x="-500.0" y="0.0" type="priority"/> <!-- def. of node "1" --> <node id="2" x="+500.0" y="0.0" type="priority"/> <!-- def. of node "2" --> <node id="3" x="0.0" y="-500.0" type="priority"/> <!-- def. of node "3" --> <node id="4" x="0.0" y="+500.0" type="priority"/> <!-- def. of node "4" -->
<node id="m1" x="-250.0" y="0.0" type="priority"/> <!-- def. of node "m1" --> <node id="m2" x="+250.0" y="0.0" type="priority"/> <!-- def. of node "m2" --> <node id="m3" x="0.0" y="-250.0" type="priority"/> <!-- def. of node "m3" --> <node id="m4" x="0.0" y="+250.0" type="priority"/> <!-- def. of node "m4" -->
</nodes> <!-- The closing tag -->```
As you may notice, only the first node named "0", which is the node inthe middle of the network, is a traffic light controlled junction. Allother nodes are uncontrolled. You may also notice, that each of bothends of a street needs an according node. This is not really necessaryas you may see soon, but it eases the understanding of the concept:every edge (street/road) is a connection between two nodes (junctions).
## Traffic lightsFor traffic light nodes, [netconvert](../netconvert.md) generates adefault traffic light program. The simulation can [load additional programs](../Simulation/Traffic_Lights.md) which may be usedinstead.
### tlTypeIf you leave out the tlType of the node, it is set to *static*. Thisdefault may be changed using the option **--tls.default-type** {{DT_STR}}.
- `static`: Each phase of the traffic light will last for a fixed duration- `actuated`: Green phases may be prolonged depending on traffic measurements from automatically added induction loops ("*Zeitlückensteuerung*")
!!! note You can load multiple node files at the same time by giving a comma-separated list of file names on the command line. In a configuration file you can use a space separated list as well.
### tlLayoutIf you leave out the tlLayout of the node, it is set to *opposites*. Thisdefault may be changed using the option **--tls.layout** {{DT_STR}}
- `opposites`: roads from opposite directions get the green light at the same time. Left turns (which conflict with the opposite stream) either have a green-with-conflict ('m') or get their own phase.- `incoming`: each incoming road gets its own green phase- `alternateOneWay`: This program is for a joined controller that regulates alternating one-way access from two or more sides of a work zone (or narrow road). each incoming road gets its own green phase and there is an all-red phase according to the size of the work zone for traffic to clear before the next direction starts up.
## Node types
If you leave out the type of the node, it is automatically guessed by[netconvert](../netconvert.md) but may not be the one you intended.The following types are possible, any other string is counted as anerror and will yield in a program stop:
- `priority`: Vehicles on a low-priority edge have to wait until vehicles on a high-priority edge have passed the junction.- `traffic_light`: The junction is controlled by a traffic light (priority rules are used to avoid collisions if conflicting links have green light at the same time).- `right_before_left`: Vehicles yield to traffic coming from the right. (This is automatically flipped when building [lefthand](../FAQ.md#can_sumo_simulate_lefthand_traffic) networks).- `left_before_right`: Vehicles yield to traffic coming from the left. (Only known to be needed for [Madagascar](https://www.countryreports.org/country/Madagascar/traffic.htm) where cars drive on the right but yield for the left side).- `unregulated`: The junction is completely unregulated - all vehicles may pass without braking; Collision detection on the intersection is disabled but collisions beyond the intersection will be detected and are likely to occur.- `traffic_light_unregulated`: The junction is controlled by a traffic light without any further rules. This may cause collision if unsafe signal plans are used. Note, that collisions within the intersection will never be detected.- `priority_stop`: This works like a *priority*-junction but vehicles on minor links always have to stop before passing.- `allway_stop`: This junction works like an [*All-way stop*](https://en.wikipedia.org/wiki/All-way_stop).- `rail_signal`: This junction is controlled by a [rail signal](../Simulation/Railways.md#rail_signals). This type of junction/control is only useful for rails.- `zipper`: This junction connects edges where the number of lanes decreases and traffic needs to merge [zipper-style (late merging)](https://en.wikipedia.org/wiki/Merge_%28traffic%29).- `rail_crossing`: This junction models a rail road crossing. It will allow trains to pass unimpeded and will restrict vehicles via traffic signals when a train is approaching.- `traffic_light_right_on_red`: The junction is controlled by a traffic light as for type *traffic_light*. Additionally, right-turning vehicles may drive in any phase whenever it is safe to do so (after stopping once). This behavior is known as [right-turn-on-red](https://en.wikipedia.org/wiki/Right_turn_on_red).- `dead_end`: There are no connections at this node. This type is assigned automatically. Using this as input will trigger guessing the type.
## Right-of-way
The right-of-way computation at each intersection is based on the `type` ofthe node. For the types *priority* and *priority_stop*, theright-of-way also depends on the `importance` of the incoming and outgoingedges as explained in the following. Generally, the traffic directionwith the edges of highest importance will get the right of way.
!!! note Right-of-way computation also influences connection-guessing and the generated traffic light program.
### rightOfWay="default"This mode is the default and it is useful if the *priority*attribute of the edges cannot be relied on to determine right-of-way allby itself. It sorts edges according to attributes *priority*, *speed* and*laneNumber*. The two incoming edges with the highest position aredetermined and will receive right-of-way. All other edges will beclassified as minor.
### rightOfWay="mixedPriority"This behaves like "default".Setting this value is only useful when configuring the switched-off behavior ofintersections controlled by traffic lights of type [NEMA](../Simulation/NEMA.md).In this case it corresponds to main roads having priority (yellow blinking) and side roads having to stop (red blinking).
### rightOfWay="edgePriority"This mode is useful for customizingright-of-way by tuning edge *priority* attributes. The relationshipbetween streams of different incoming-edge priority will be solelydetermined by edge priority. For equal-priority values, turningdirections are also evaluated.
### rightOfWay="allwayStop"This mode is only used for configuring the behavior of traffic light junctions when switching the [traffic light off](../Simulation/Traffic_Lights.md#switching_tls_off).When this mode is used, the junction will behave like [type](#node_types) `allway_stop` in the 'off' state.This is used as the default for nodes controlled by traffic lights of type [NEMA](../Simulation/NEMA.md).
### Special Cases
- To model a turning priority road, all incoming and outgoing edgesthat make up this road must have a a higher priority value than thenon-prioritized road edges.- For [roundabouts](#roundabouts), the edges within theroundabout always get the right of way over the edges incoming fromthe outside.- When [two lanes from the same edge approach the same target lane](#multiple_connections_from_the_same_edge_to_the_same_target_lane),the right of way depends on the node type: - If the type is *zipper*, then both lanes will react symmetrically to each other and vehicles perform [zipper merging](https://en.wikipedia.org/wiki/Merge_%28traffic%29). - Otherwise, the left lane will have priority while the right lane will yield.
### Understanding right-of-way rules in a Network
The right-of-way rules are indicated in [sumo-gui by the colored bars at the end of each lane and by the colors of the connection arrows](../sumo-gui.md#right_of_way) when customizing the view with*junctions-\>show lane to lane connections*.
The right-of-way relationship between any two connections ca be shown in[netedit using right-of-way mode](../Netedit/editModesNetwork.md#prohibitions).
If a vehicle is braking in the simulation, the responsible foe vehicle(if any) can also be [identified directly](../sumo-gui.md#right_of_way).
!!! caution Never attempt to modify the junction logic within a ***.net.xml*** file manually as there are subtle inter-dependencies with other data structures in the network. Nevertheless, it may be useful to [look into the .net.xml to understand right-of-way](../Networks/SUMO_Road_Networks.md#requests)
### Modifying Right-of-Way
The right-of-way can be customized by specifying [additional prohibitions](#setting_connection_priorities) and byspecifying the [connection attribute](#explicitly_setting_which_edge_lane_is_connected_to_which)`pass="true"`.
Since version 1.1.0, the algorithm for computing right-of-way from theedge priorities can be switched between two modes using `<node>`-attribute*rightOfWay*.
## Fringe
For route generation it may be relevant to know whether a particular junction or edge is at boundary of a network where other roads (that exist in the real world) were cut off. This can specified using the 'fringe' attribute:
- default: this junction is not part of the fringe- outer: this junction is connected to additional edges in the real world. It is part of the outer boundary of the network- inner: this junction is connected to additional edges in the real world. It lies within the network but other roads (i.e. with a lower road class) were removed from the simulation
The fringe attribute can be determined automatically for the outer fringe based on the pareto frontier by setting netconvert option **--fringe.guess**. It is also set automatically by [netgenerate](../netgenerate.md) when option **--attach-length** is used. Editing the attribute in [netedit](../Netedit/index.md) is also supported.
The 'fringe' attribute is used by [randomTrips.py](../Tools/Trip.md#randomtripspy) when setting option **--fringe-junctions**.
## Joining Nodes
Sometimes your network may contain nodes which are very close togetherforming a big cluster. This happens frequently when [Importing Networks from OpenStreetMap](../Networks/Import/OpenStreetMap.md).[netconvert](../netconvert.md) supports the option **--junctions.join** to find suchclusters and join them into a big and well shaped junction. Junctions can also be joined manually with [netedit](../Netedit/index.md#processing_menu_options).It is even possible to [undo joins](../Netedit/elementsNetwork.md#junctions) that were computed automatically.The new junction will get the id *cluster_id0_id1*. If there are more nodes in the cluster than given by **--max-join-ids** (default 4)the id will be abbreviated to something like *cluster_id0_id1_id2_id3_#5more* (for a 9 node cluster).
### Reasons for joining node clustersWithin an intersection, special rules of traffic do apply. When modelling an intersection by a cluster of nodes, the edges within the cluster are regular roads where these rules cannot be applied.- To prevent jamming cross-traffic, vehicles should only enter an intersection space if they are not prevented from leaving by a downstream jam- Vehicles that turn left from opposite directions may turn ahead of each other (without intersecting trajectories). In an unjoined cluster long vehicles easily block each other when turning left from opposite directions.
Further Issues:- Trajectories of left-turning traffic are invalid in an unjoined cluster. Instead of cutting the corner in a smooth curve, the trajectory would consist of two mostly straight legs with a sharp turn in the middle.- Proper modelling of left-turn dynamics requires extra traffic light signals within the cluster to reflect the changing priorities on the second leg of a left turn (which is also the first leg of a straight movement).- Automatically generated traffic light plans work much better at a single intersection
### Algorithm for joining node clustersYou can control the joining algorithm by supplying the option **--junctions.join-dist** {{DT_FLOAT}} which sets asearch distance for finding clusters *(default 10m)*. The search forjoinable node clusters works like this:
1. junction shapes are computed for all nodes2. the length of the edges between the junction shapes is compared against **join-dist**3. nodes within the given distance are transitively added to a candidate cluster4. nodes with only a single connection to the cluster (nodes at the outside) are removed5. clusters which are to complex are simplified or filtered out (a warning with an explanation is issued for each case) - if a cluster has parallel incoming edges (in the same direction of travel) it is filtered out. The threshold for being considered parallel can be controlled with option **--junctions.join.parallel-threshold** (default 30 degrees). 7. each cluster is turned into a joined node
### Specifying and excluding explicit joins
More fine grained control over joining can be achieved by using elements `<join>` and `<joinExclude>` within a nodes-file
```xml<nodes> <join nodes="id0 id23 id24"/> <joinExclude nodes="id13 id17"/></nodes>```
This will cause the nodes *id0*,*id23* and *id24* to be joined into asingle junction. It will also prevent the nodes *id13* and *id17* frombeing joined. The **joinExclude**-tag is only useful together with theoption **--junctions.join** but the **join**-tag can also be used all by itself.
Element `<joinExclude>` only supports attribute `nodes` and works in the same way as option **--junctions.join-exclude id,[id\]+**.The supported attributes for element `<join>` are described below.
| Attribute Name | Value Type | Description || --------------- | ----------------------------------------- | ------------------------------------------------------------------------- || **nodes* | id list (string) | The ids of nodes to join || reset | bool (default: *false*) | Whether all connections at the created node should be re-guessed || <any [node node attriutes](#node_descriptions)> | Sets attributes on the new node (i.e. its `id` or `type`) |
### Connections after joining nodes
The connections at joined junctions depend on the loaded connection definitions and on further attributes and options
- if no connections are loaded, the connections will be guessed for the joined junction (this applies to most junctions imported from OSM where explicit connection data is often missing)- if any connections are loaded, they connections at the joined node will be re-created to match the loaded connectivity - unless option `<join>`-attribute `reset="true"` or option **--junctions.join-reset** is set in which guess all connections will be guessed again
!!! noteRe-guessing loaded connections is useful when joining junctions while merging networks.
# Edge Descriptions
| Edge Descriptions | ||--------------------|-----------------------|| Filename extension | .edg.xml || Type of content | Edges (roads/streets) || Open format? | Yes || SUMO specific? | Yes || XML Schema | [edges_file.xsd](https://sumo.dlr.de/xsd/edges_file.xsd) |
Within the edges file, each description of a single edge looks likethis: `<edge id="<STRING>" from="<NODE_ID>" to="<NODE_ID>" [type="<STRING>"] [numLanes="<INT>"] [speed="<FLOAT>"] [priority="<UINT>"] [length="<FLOAT>"] [shape="<2D-POSITION>[ <2D-POSITION>]*"] [spreadType="center"] [allow="<VEHICLE_CLASS>[ <VEHICLE_CLASS>]*"] [disallow="<VEHICLE_CLASS>[ <VEHICLE_CLASS>]*"]/>`.
The origin and the destination nodes are defined using their IDs(`from="<NODE_ID>" to="<NODE_ID>"`). Eachedge is unidirectional and starts at the"`from`"-node and ends at the"`to`"-node. If a name of one of the nodes cannot be dereferenced (because they have not been defined within the nodesfile) an error is generated. To avoid the stop of further netconversionin such cases, you may start [netconvert](../netconvert.md) withthe option **--ignore-errors**.
For each edge, some further attributes should be supplied, being thenumber of lanes the edge has (`numLanes`), themaximum speed allowed on the edge `speed`.Furthermore, the `priority` may be definedoptionally.
All edge values - beside the length in fact - may either be given foreach edge using according attributes or you can omit them by giving theedge a "`type`". In this case, you should alsowrite a [SUMO edge type file](#type_descriptions). A typewith this name should of course be within the used type file, otherwisean error is reported. Even if you supply a type, you can still overridethe type's values by supplying any of the parameter`allow`, `disallow`,`numLanes`,`priority` and`speed`. You may also leave the edge parametercompletely unset. In this case, default-values will be used and the edgewill have a single lane, a default (unset) priority and the maximumallowed speed on this edge will be 13.9m/s being around 50km/h. Thelength of this edge will be computed as the distance between thestarting and the end point.
As an edge may have a more complicated geometry, you may supply theedge's shape within the `shape` attribute. Ifthe length of the edge is not given otherwise, the distances of theshape elements will be summed. The information`spreadType="center"` forces[netconvert](../netconvert.md) to spread lanes to both sides of theconnection between the begin node and the end node or from the list oflines making up the shape. If not given, lanes are spread to right, asdefault.
Let's list an edge's attributes again:
| Attribute Name | Value Type | Description || -------------- | ------------------------------------- | -------------------------------------------------------------- || **id** | id (string) | The id of the edge (must be unique) || from | referenced node id | The name of a node within the nodes-file the edge shall start at || to | referenced node id | The name of a node within the nodes-file the edge shall end at || type | referenced type id | The name of a type within the [SUMO edge type file](../SUMO_edge_type_file.md) || numLanes | int | The number of lanes of the edge; must be an integer value || speed | float | The maximum speed allowed on the edge in m/s; must be a floating point number (see also "Using Edges' maximum Speed Definitions in km/h") || priority | int | The priority of the edge. Used for [\#Right-of-way](#right-of-way)-computation || length | float | The length of the edge in meter || shape | List of positions; each position is encoded in x,y or x,y,z in meters (do not separate the numbers with a space\!). | If the shape is given it should start and end with the positions of the from-node and to-node. Alternatively it can also start and end with the position where the edge leaves or enters the junction shape. This gives some control over the final junction shape. When using the option **--plain.extend-edge-shape** it is sufficient to supply inner geometry points and extend the shape with the starting and ending node positions automatically || spreadType | enum ( "right", "center", "roadCenter") | The description of how to compute lane geometry from edge geometry. See [SpreadType](#spreadtype) || allow | list of vehicle classes | List of permitted vehicle classes (see [access permissions](#road_access_permissions_allow_disallow))|| disallow | list of vehicle classes | List of forbidden vehicle classes (see [access permissions](#road_access_permissions_allow_disallow))|| width | float | lane width for all lanes of this edge in meters (used for visualization) || name | string | street name (need not be unique, used for visualization) || endOffset | float \>= 0 | Move the stop line back from the intersection by the given amount (effectively shortening the edge and locally enlarging the intersection) || sidewalkWidth | float \>= 0 | Adds a sidewalk with the given width (defaults to -1 which adds nothing). || bikeLaneWidth | float \>= 0 | Adds a bicycle lane with the given width (defaults to -1 which adds nothing). || distance | float | [Kilometrage](../Simulation/Distances.md#defining_and_using_linear_coordinates) at the start of this edge. If the value is positive, kilometrage increases in driving direction; if the value is negative, kilometrage decreases. Kilometrage along the edge is computed as abs(*distance* + *offsetFromStart*). || bidi | id | Declares the opposite-direction edge that should form a pair of bidi-edges with this edge || routingType | id | Used together with [preference](../Simulation/Routing.md#routing_by_travel_time_and_routingtype) to set custom edge preferences for routing |
The priority plays a role during the computation of the way-giving rulesof a node. Normally, the allowed speed on the edge and the edge's numberof lanes are used to compute which edge has a greater priority on ajunction. Using the priority attribute, you may increase the priority ofthe edge making more lanes yielding in it or making vehicles coming fromthis edge into the junction not wait.
Also the definitions of edges must be embedded into an opening and aclosing tag and for the example"{{SUMO}}/data/examples/netbuild/types/cross_notypes/" the whole edges-filelooks like this ("cross3l.edg.xml"):
```xml<edges>
<edge id="1fi" from="1" to="m1" priority="2" numLanes="2" speed="11.11"/> <edge id="1si" from="m1" to="0" priority="3" numLanes="3" speed="13.89"/> <edge id="1o" from="0" to="1" priority="1" numLanes="1" speed="11.11"/>
<edge id="2fi" from="2" to="m2" priority="2" numLanes="2" speed="11.11"/> <edge id="2si" from="m2" to="0" priority="3" numLanes="3" speed="13.89"/> <edge id="2o" from="0" to="2" priority="1" numLanes="1" speed="11.11"/>
<edge id="3fi" from="3" to="m3" priority="2" numLanes="2" speed="11.11"/> <edge id="3si" from="m3" to="0" priority="3" numLanes="3" speed="13.89"/> <edge id="3o" from="0" to="3" priority="1" numLanes="1" speed="11.11"/>
<edge id="4fi" from="4" to="m4" priority="2" numLanes="2" speed="11.11"/> <edge id="4si" from="m4" to="0" priority="3" numLanes="3" speed="13.89"/> <edge id="4o" from="0" to="4" priority="1" numLanes="1" speed="11.11"/>
</edges>```
Within this example, we have used explicit definitions of edges. Anexample for using types is described in the chapter [Type Descriptions](#type_descriptions).
!!! caution There are some constraints about the streets' ids. They must not contain any of the following characters: '_' (underline - used for lane ids), '[' and ']' (used for enumerations), ' ' (space - used as list divider), '*' (star, used as wildcard), ':' (used as marker for internal lanes).
## SpreadTypeEach edge has a geometry definition (which defaults to the straight-line between from-junction and to-junction position).The spreadType defines how to compute the lane geometry from the edge geometry:
- **right** (default): The edge geometry is interpreted as the left side of the edge and lanes flare out to the right. This works well if edges in opposite directions have the same (or rather reversed) geometry.- **center**: The edge geometry is interpreted as the middle of the directional edge and lanes flare out symmetrically to both sides. This is appropriate for one-way edges- **roadCenter**: The edge geometry is interpreted as the middle of a bi-directional road. This works well when both directional edges have a different lane number.
## Road access permissions (allow, disallow)
[access permissions](../Simulation/VehiclePermissions.md) are animportant tool for building multimodal scenarios. Either one of theattributes `allow` or `disallow` may be used to configure this according to the followingsemantics:
- neither *allow* nor *disallow* given: no access restrictions.- *allow* given: Allow only the list of specified vehicle classes(i.e. `allow="bus bicycle"` allows only busses and bicycles)- *disallow* given: Allow all classes except the list of specifiedones (i.e. allows everything but pedestrians) - the special value *all* may be used to disallow everything (`disallow="all"`) to denote green verges or other kinds of spacing between lanes.
## Lane-specific Definitions
You may allow/forbid explicit vehicle classes to use a lane. Theinformation which vehicle classes are allowed on a lane may be specifiedwithin an edges descriptions file by embedding the list of lanestogether with vehicle classes allowed/forbidden on them into theseedge's lanes. Assume you want to allow only buses to use the leftmostlane of edge "2si" from the example above. Simply change this edge'sdefinition into:
```xml... previous definitions ... <edge id="2si" from="m2" to="0" priority="3" numLanes="3" speed="13.89"> <lane index="2" allow="bus"/> </edge>... further definitions ...```
If you would like to disallow passenger cars and taxis, the followingsnippet would do it:
```xml... previous definitions ... <edge id="2si" from="m2" to="0" priority="3" numLanes="3" speed="13.89"> <lane index="2" disallow="passenger taxi"/> </edge>... further definitions ...```
The definition of a lane contains the following optional attributes:
| Attribute Name | Value Type | Description || -------------- | ------------------------------------------------- | ---------------------------------------------------------------------------- || **index** | int | The enumeration index of the lane (0 is the rightmost lane, <NUMBER_LANES\>-1 is the leftmost one) || allow | list of vehicle classes | List of permitted vehicle classes (see [access permissions](#road_access_permissions_allow_disallow)) || disallow | list of vehicle classes | List of forbidden vehicle classes (see [access permissions](#road_access_permissions_allow_disallow)) || changeLeft | list of vehicle classes | List of vehicle classes that may change left from this lane || changeRight | list of vehicle classes | List of vehicle classes that may change right from this lane || speed | float | speed in meters per second || width | float | width in meters (used for visualization) || endOffset | float \>= 0 | Move the stop line back from the intersection by the given amount (effectively shortening the lane and locally enlarging the intersection) || shape | List of positions; each position is encoded in x,y or x,y,z in meters (do not separate the numbers with a space\!). | A custom shape for this lane.<br><br>**Note:** The lane lengths will be averaged in the generated network. Lane-changing will ignore gaps between lanes.| type | string | a custom type description for this lane (only informational) || acceleration | bool | whether this lane is a motorway acceleration lane (default *false*) |
See "Vehicle Classes" for further information about [allowed vehicle classes](../Definition_of_Vehicles,_Vehicle_Types,_and_Routes.md#abstract_vehicle_class)and their usage.
### lane change restrictionsWhen defining lane change restrictions with `changeLeft` and `changeRight`, the vehicle class "emergency" should typically be allowed since emergency vehicles can ignore non-physical restrictions in most cases.
The strongest restriction is the value "ignoring". Note, that vehicles of class "ignoring" cannot be restricted from lane changing with `changeLeft` and `changeRight`. (only creating separate parallel edges will work).
## Stop Offsets
Each edge or lane may carry a `stopOffset` child element to specify an additionalstopping offset for vehicles of certain classes. This can be used to define a [bike box](https://en.wikipedia.org/wiki/Advanced_stop_line).
```xml<edge id="<ID>"> <stopOffset value="<distance in m.>" vClasses="<space-separated list of vClasses>" /> <lane id="<ID>" index="<INDEX>" ... > <stopOffset value="<distance in m.>" exceptions="<space-separated list of vClasses>" /> </lane> ...</edge>```
Defining this element for an edge will affect all lanes of the edge thatdo not hold an own `stopOffset` element. Note that there is the possibility todefine either all vehicle classes, that are affected by the stop offset(attribute `vClasses`), or those, which are not affected (attribute `exceptions`). You may notuse both attributes in conjunction. The distance at which the specifiedvehicle classes are required to stop from the lane end is specified bythe `value`-attribute.
| Name | Type | Description || -------------- | ---------------- | ------------------------------------------------------------------- || **value** | value (double) | The stop offset as positive value in meters. || **vClasses** | list of vClasses | Specifies, for which vehicle classes the stopOffset applies. || **exceptions** | list of vClasses | Specifies, for which vehicle classes the stopOffset does not apply. |
For specification of vehicle classes see[here](../Definition_of_Vehicles,_Vehicle_Types,_and_Routes.md#abstract_vehicle_class).
## Road Segment Refining
Normally, each edge has a certain number of lanes and a fixed speed;road widenings and speed reductions are defined using consequent edges.Though, in some cases, it is more comfortable to set up a single edgeand change the number of its lanes or the speed along its length.
This is possible using "split" - a subelement of an XML-edge definitionafter 02.09.2009. A split may be given as following:
```xml... previous definitions ... <edge id="2si" from="m2" to="0" priority="3" numLanes="3" speed="13.89"> <split pos="30" lanes="0 1" speed="10"/> </edge>... further definitions ...```
What happens here is the following: 30meters from its begin(`pos="30"`) the edge is split, inserting anode named <EDGE_ID\>.<POSITION\>. Until this node, the edge includes alllanes. After this node, only the lanes given in the`lanes` attribute are inserted and their speedis reduced. This yields in two edges which replace the initial one andthe second edge contains only two lanes with a maximum speed of 10m/s.
The most common usage example is the other way round: lanes must beadded, not removed along a road. The following snippet shows the byexample:
```xml... previous definitions ... <edge id="2si" from="m2" to="0" priority="3" numLanes="3" speed="13.89"> <split pos="0" lanes="0 1"/> <split pos="30" lanes="0 1 2"/> </edge>... further definitions ...```
There are several things to note:
- In the road definition, we use the maximum lane number (3)- We add an "split" at position 0; in this case, no node is built, but the lane number is applied to the edge directly.- If we add a split with a position only, it resets lane number and speed to the default values for the edge (so in the example above we could have left out the lanes attribute in the second split).
It is also possible to add a common split in both directions of a road.With the example below, one new node is created which splits the forwardand backward edge:
```xml <edge id="123"> <split id="newNode" pos="150"/> </edge>```
```xml <edge id="-123"> <split id="newNode" pos="-150"/> </edge>```
The definition of a split uses the following attributes:
| Attribute Name | Value Type | Description || ------------------------------------------ | ----------------------- | --------------------------------- || **pos** | float | The position along the edge at which the split shall be done (in m); if a negative position is given, the split is inserted counting from the end of the edge || lanes | list of lane ids (ints) | Information which lanes should exist after the split || speed | float | The speed in m/s after the split position || id | id (string) | The id of the newly created node. IDs of existing nodes may also be used. (by default the id is generated from the edge id and *pos* || idBefore | id (string) | The id of the edge before the split (defaults to the original id) || idAfter | id (string) | The id of the edge after the split (defaults to <origID.pos\>) || offset | float | Extra sideways shift to be applied to the edge after the split || type, tl, tlType, shape, radius, keepClear | | see [\#Node_Descriptions](#node_descriptions) |
## Roundabouts
Edges may be part of a roundabout. This influences the right of waycomputation and disables turn-arounds for edges entering the roundaboutfrom outside. A roundabout is specified within an *.edg.xml*-file in thefollowing way:
```xml<edges> ... <!--Edge Definitions -->
<roundabout edges="<EDGE_ID> <EDGE_ID> [<EDGE_ID>..]"/>
</edges>```
Manual specification of roundabouts is a useful supplement for theexisting roundabout heuristic (activated via option **--roundabouts.guess**). Guessedroundabouts are written as part of the *plain-xml* output (option **--plain-output-prefix**).This output can then be customized by the user and fed back into[netconvert](../netconvert.md).
## Neighboring opposite-direction Lanes
To enable[opposite-direction-driving](../Simulation/OppositeDirectionDriving.md),the adjacency information for opposite direction lanes must be defined.This can be done explicitly by using the `<neigh>` element in an *.edg.xml* fileas follows:
```xml<edges> <edge id="a" from="X" to="Y" numLanes="2"> <neigh lane="b_0"/> </edge>
<edge id="b" from="Y" to="X"> <neigh lane="a_1"/> </edge></edges>```
In the above input the inner-most lanes of edges *a* and *b* aredeclared as adjacent.
## Deleting edges or lanes
In order to delete an edge or lane which comes from a different sourceor a preprocessed net one can give the edge id and the optional index inthe following way:
```xml<edges> <delete id="a"/> <!-- deletes the edge "a" --> <delete id="a" index="0"/> <!-- deletes the first lane of edge "a" --></edges>```
It is also possible to remove all edges of a specific type (see below)by giving the attribute remove="true" to the type.
# Type Descriptions
| **Edge Type Descriptions** | ||--------------------|----------------|| Filename extension | .typ.xml || Type of content | Edge Types || Open format? | Yes || SUMO specific? | Yes || XML Schema | [types_file.xsd](https://sumo.dlr.de/xsd/types_file.xsd) |
As mentioned, [edge types](../SUMO_edge_type_file.md) are meant tobe used to ease the definition of edges. Each description of an edgeshould include information about the number of lanes, the maximum speedallowed on this edge and optionally this edge's priority and its allowedand disallowed vehicle classes. See [SUMO edge type file](../SUMO_edge_type_file.md) for a complete description of edgetypes and the format of those files.
The attributes of a type are of course exactly the same as for edgesthemselves. The information about the nodes the edge starts and ends atis not given within the types' descriptions. They can only be set withinthe edge's attributes. Here's an example on referencing types in edgedefinitions:
```xml<edges>
<edge id="1fi" from="1" to="m1" type="b"/> <edge id="1si" from="m1" to="0" type="a"/> <edge id="1o" from="0" to="1" type="c"/>
<edge id="2fi" from="2" to="m2" type="b"/> <edge id="2si" from="m2" to="0" type="a"/> <edge id="2o" from="0" to="2" type="c"/>
<edge id="3fi" from="3" to="m3" type="b"/> <edge id="3si" from="m3" to="0" type="a"/> <edge id="3o" from="0" to="3" type="c"/>
<edge id="4fi" from="4" to="m4" type="b"/> <edge id="4si" from="m4" to="0" type="a"/> <edge id="4o" from="0" to="4" type="c"/>
</edges>```
The according types file looks like this (see [SUMO edge type file](../SUMO_edge_type_file.md)):
```xml<types>
<type id="a" priority="3" numLanes="3" speed="13.889"/> <type id="b" priority="2" numLanes="2" speed="11.111"/> <type id="c" priority="1" numLanes="1" speed="11.111"/>
</types>```
As you can see, we have joined the edges into three classes "a", "b",and "c" and have generated a description for each of these classes.Doing this, the generated net is similar to the one generated using thesettings described above (example"{{SUMO}}/docs/examples/netconvert/types/cross_notypes/" ).
## vehicle-class specific speed limits
Using `<type>` definitions it is possible to implement vClass specific speedlimits:
```xml<type id="a" priority="3" numLanes="3" speed="38.89"> <restriction vClass="truck" speed="27.89"/></type>```
the value of *vClass* must be a single class from [the list of possible vehicle classes](../Definition_of_Vehicles,_Vehicle_Types,_and_Routes.md#abstract_vehicle_class).
An example use of vehicle-class specific speed limits would be trucks onGerman motorways which are not permitted to exceed 100km/h even wherepassenger cars have a higher speed limit. While this could also bemodeled by setting a lower `maxSpeed` for trucks, that approach would preclude theuse of `speedDev` and `speedFactor` to easily model the variation of speeds around the legalspeed limit.
!!! note vClass-specific speed limit restrictions can also be loaded directly into [sumo](../sumo.md) from an additional file (only type attribute 'id' is needed)
## speed on junction
If a connection defines the 'type' attribute, this can be used to load restrictions directly. Otherwise, the type and restrictions are inferred from the edge types before and after the intersection as follows:
If a vclass-specific speed restriction exists for the edge type before and after a junction, the speed restriction is also applied to the (junction-)internal edge. By default, the average value of the restricted speeds before and after the junction will be used.If the network was built with option **--junctions.higher-speed**, the maximum of both speeds is used on the junction instead.
# Connection Descriptions
| **Connection Descriptions** | ||--------------------|----------------------|| Filename extension | .con.xml || Type of content | Connections || Open format? | Yes || SUMO specific? | Yes || XML Schema | [connections_file.xsd](https://sumo.dlr.de/xsd/connections_file.xsd) |
"Connections" describe how a node's incoming and outgoing edges areconnected (for example to prohibit left-turns at some junctions). Yourcan specify connections on the edge level or you can declare in indetail which incoming lane shall be connected to which outgoing lanes.If you leave some connections unspecified[netconvert](../netconvert.md) automatically computes the missinginformation based on heuristics.
!!! note It is possible to connect two incoming lanes to the same outgoing lane. In many cases (i.e. motorway on-ramps) this should be avoided because the expected vehicle behavior is to change the lane as soon as possible rather than driving to the end of the lane). Netconvert will generate these "double connections" when a bicycle lane ends and bikes must move onto the road. SUMO vehicles are aware of the conflicts set up this way and [this can sometimes be a useful tool for network modelling](../Simulation/Motorways.md#combined_on-off-ramps).
## Explicitly setting which Edge / Lane is connected to which
Though guessed if not given, definitions of connections between edges orlanes may be manually set up and given to[netconvert](../netconvert.md) using connection files. Theconnection file specifies which edges outgoing from a junction may bereached by a certain edge incoming into this junction and optionallyalso which lanes shall be used on both sides.
### Edge-to-Edge connectivity
If you only want to describe which edges may be reached from a certainedge, the definition is:
```<connection from="<FROM_EDGE_ID>" to="<T0_EDGE_ID>"/>```
This tells [netconvert](../netconvert.md) not only that vehicles shall beallowed to drive from the edge named *<FROM_EDGE_ID\>* to the edge named*<TO_EDGE_ID\>*, but also prohibits all movements to other edges from*<FROM_EDGE_ID\>*, unless they are specified within this file. Let'srepeat the parameters:
| Attribute Name | Value Type | Description || -------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------ || **from** | referenced edge id | The name of the edge the vehicles leave || to | referenced edge id | The name of the edge the vehicles may reach when leaving "from". If omitted or set to "" the incoming edge will have no connections. |
When using the kind of input, [netconvert](../netconvert.md) willcompute which lanes shall be used if any of the connected edges has morethan one lane. To obtain more control, additional attributes may be given as described below.
### Lane-to-Lane connectivity
To declare connections fully (and avoid any kind of guessing), use the following:
```<connection from="<FROM_EDGE_ID>" to="<T0_EDGE_ID>" fromLane="<INT_1>" toLane="<INT_2>"/>```
Here, a connection from the edge's "*<FROM_EDGE_ID\>*" lane with the number *<INT_1\>* is build to the lane *<INT_2\>* of the edge "*<TO_EDGE_ID\>*". Lanes are counted from the right (outer) to the left (inner) side of the road beginning with 0. This style must be used when further connection attributes (such as permissions) shall be declared.
| Attribute Name | Value Type | Default | Description || -------------- | -------------------------------------- | ------- | ----------------------------------------------------------------------- || **from** | referenced edge id | | The name of the edge the vehicles leave || to | referenced edge id | | The name of the edge the vehicles may reach when leaving "from" || fromLane | *<INT\>* | | the lane index of the incoming lane (numbers starting with 0) || toLane | *<INT\>* | | the lane index of the outgoing lane (numbers starting with 0) || pass | bool | false | if set, vehicles which pass this (lane-2-lane) connection) will not wait || keepClear | bool | true | if set to *false*, vehicles which pass this (lane-2-lane) connection) will not worry about [blocking the intersection](../Simulation/Intersections.md#junction_blocking). || contPos | float | \-1 | if set to 0, no [internal junction](../Networks/SUMO_Road_Networks.md#internal_junctions) will be built for this connection. If set to a positive value, an internal junction will be built at this position (in m) from the start of the internal lane for this connection. || visibility | float | 4.5 | specifies the distance to the connection \[in m.\] below which an approaching vehicle has full sight of any other approaching vehicles on the connection's foe lanes (i.e. vehicle can accelerate if none are present). Note, that a too low visibility (<=0.1m.) will prevent vehicles from crossing a minor link. For 'zipper'-links, this attribute controls the point at which zipper-merging behavior starts (default 100m). For major links (right-of-way) the attribute has no effect. || speed | float | \-1 | specifies the maximum speed while moving across the intersection using this connection (in m/s). By default the mean speed of the edge before and after the connection is used. With the default value, the speed is set to the average of the incoming and outgoing lane or to a radius based limit if option **--junctions.limit-turn-speed** is set. || shape | List of positions; each position is encoded in x,y or x,y,z in meters (do not separate the numbers with a space\!). | | specifies a custom shape for the internal lane(s) for this connection. By default an interpolated cubic spline is used. || uncontrolled | bool | false | if set to *true*, This connection will not be TLS-controlled despite its node being controlled. || allow | list of vehicle classes | | set custom permissions independent of from-lane and to-lane permissions. || disallow | list of vehicle classes | | set custom permissions independent of from-lane and to-lane permissions. || changeLeft | list of vehicle classes | List of vehicle classes that may change left from this lane || changeRight | list of vehicle classes | List of vehicle classes that may change right from this lane || length | float | | set a [custom length](../Simulation/Distances.md#length-geometry-mismatch) for this connection || indirect | bool | false | declare an indirect (two-step) turning movement (affects geometry and right-of-way) || type | string | | set custom edgeType for applying [vClass-specific speed limits](#vehicle-class_specific_speed_limits) |
### Deleting connections
[netconvert](../netconvert.md) may be used to patch existing sumo networks (*.net.xml* files) and changing connections is one of the supported use cases.If you only wish to **remove** a connection it may be convenient to usethe following xml definition:
```<delete from="<FROM_EDGE_ID>" to="<T0_EDGE_ID>"/>```
The attributes are the same as for thesimple connection element:
| Attribute Name | Value Type | Description || -------------- | ------------------ | ---------------------------------------------------------- || **from** | referenced edge id | The source edge id of the connection to be removed || **to** | referenced edge id | The destination edge id of the connection to be removed || fromLane | referenced lane no | The source lane index of the connection to be removed || toLane | referenced lane no | The destination lane index of the connection to be removed |
!!! note Note that in basic format (that is, without **fromLane** and **toLane** attributes) the definition deletes **all** connections from given incoming edge to the given outgoing edge. When **fromLane** and **toLane** attributes are provided, only the connection from given lane to given lane is removed.
### Patching connections and guessing again
By default there are two modes when processing connections.
1. when loading from *plain-xml*, any missing information is guessed (and this typically causes connections to be added)2. when loading from a *.net.xml*, everything existing is kept by default and nothing is guessed. Any changes to connections must be enacted by explicitly adding or removing connections (as described above).
It may be convenient to trigger re-guessing of connections for selected edges (i.e. after loading and edge-patch to change lane numbers).For this, the following definition may be used:
```<connection from="<FROM_EDGE_ID>" reset="true"/>```
This will trigger all connections from edge with id `FROM_EDGE_ID` to be removed and re-guessed.
### Examples
There are two examples within the distribution. Both use the nodes andedges descriptions from the example located in"{{SUMO}}/docs/examples/netconvert/types/cross_notypes/". The junction in thecenter of this example looks like shown within the next figure. We willnow call it the "unconstrained network" because all connections andturnarounds are computed using the default values.
Unconstrained Network
The example{{SUMO}}/docs/examples/netconvert/connections/cross3l_edge2edge_conns/" showswhat happens when one uses connections to limit the number of reachableedges. To do this we built a connections file where we say that thehorizontal edges ("1si" and "2si") have only connections to the edgesright to them and the edge in straight direction. The file looks likethis:
```xml<connections>
<connection from="1si" to="3o"/> <connection from="1si" to="2o"/>
<connection from="2si" to="4o"/> <connection from="2si" to="1o"/>
</connections>```
As you may see in the next picture, the horizontal edges within theresult network contain no left-moving connections.
Network with explicit edge-2-edge connections
In the second example located in{{SUMO}}/docs/examples/netconvert/connections/cross3l_lane2lane_conns" weadditionally describe which lanes shall be connected. The accordingconnections file says that the connections going straight shall be startat the second lane of the incoming edges:
```xml<connections>
<connection from="1si" to="3o" fromLane="0" toLane="0"/> <connection from="1si" to="2o" fromLane="2" toLane="0"/>
<connection from="2si" to="4o" fromLane="0" toLane="0"/> <connection from="2si" to="1o" fromLane="2" toLane="0"/>
</connections>```
The built network looks like this:
Network with explicit lane-2-lane connections
!!! caution Please do not use both types of connection declarations (those with an lane attribute and those without) for the same from-edge! The behavior is not verified and tested for these settings.
## Setting Connection Priorities
Since version 0.9.6 you can also let vehicles passing a connectionbetween two edges wait for another stream. Let's take another look at"Network with explicit edge-2-edge connections" above. Here, allright-moving vehicles may drive. The following definition within theconnections file lets vehicles on vertical edges moving right wait forthose which move straight on horizontal edges:
```xml<connections>
<!-- The next four connection definitions are same as in "Network with explicit edge-2-edge connections" --> <connection from="1si" to="3o"/> <connection from="1si" to="2o"/>
<connection from="2si" to="4o"/> <connection from="2si" to="1o"/>
<!-- now, let's prohibit the vertical connections by the horizontal --> <!-- prohibit moving right from top to left by straight from right to left --> <prohibition prohibitor="2si->1o" prohibited="4si->1o"/> <!-- prohibit moving straight from top to bottom by straight from right to left --> <prohibition prohibitor="2si->1o" prohibited="4si->3o"/> <!-- prohibit moving left from top to right by straight from right to left --> <prohibition prohibitor="2si->1o" prohibited="4si->2o"/>
<!-- prohibit moving right from bottom to right by straight from left to right --> <prohibition prohibitor="1si->2o" prohibited="3si->2o"/> <!-- prohibit moving straight from bottom to top by straight from left to right --> <prohibition prohibitor="1si->2o" prohibited="3si->4o"/> <!-- prohibit moving left from bottom to right by straight from left to right --> <prohibition prohibitor="1si->2o" prohibited="3si->1o"/>
</connections>```
As one may see, it was necessary to prohibit all connections from avertical edge by the counter-clockwise straight connection on ahorizontal edge because otherwise the vehicles on the horizontal edgewant to wait due to right-before-left - rule. The network looks likethis:
Network with explicit prohibitions
The syntax of a prohibition-tag is: `<prohibition prohibitor="<PROHIBITING_FROM_EDGE_ID>-><PROHIBITING_TO_EDGE_ID>" prohibited="<PROHIBITED_FROM_EDGE_ID>-><PROHIBITED_TO_EDGE_ID>"/>`.This means we define two connections (edge-to-edge), the prohibiting one(prohibitor) and the prohibited (prohibited). Each connection is definedby a from-edge and a to-edge, divided by "-\>".
## Multiple connections from the same edge to the same target lane
From version 0.25.0 on, specifying conflicting connections from the sameedge will cause a priority order to be established among them, allowingfor a collision-free simulation. By default, the right-most lane willhave the right of way but this can be customized by using attribute*pass* as shown below:
```xml<connections> <connection from="WC" to="CE" fromLane="0" toLane="0"/> <connection from="WC" to="CE" fromLane="1" toLane="0" pass="true"/></connections>```
# Traffic Light Program Definition
| ** Traffic light Descriptions** | ||--------------------|--------------------------|| Filename extension | .tll.xml || Type of content | traffic light definition || Open format? | Yes || SUMO specific? | Yes || XML Schema | [tllogic_file.xsd](https://sumo.dlr.de/xsd/tllogic_file.xsd) |
This file describes traffic lights, signal plans and defines whichconnections they control. It consists of two types of elements describedbelow. Files of this type must be loaded in[netconvert](../netconvert.md) using the option **--tllogic-files** {{DT_FILE}}.
## traffic light definitions
`<tlLogic ...>`-elements follow the same format as described in[Simulation/Traffic_Lights](../Simulation/Traffic_Lights.md). Byusing them in [netconvert](../netconvert.md), multiple programs(even for the same intersection) may be embedded in the *.net.xml* fileinstead of loading them into SUMO.
!!! caution Embedding [WAUTs (scheduled switching between programs)](../Simulation/Traffic_Lights.md#defining_program_switch_times_and_procedure) in the network via [netconvert](../netconvert.md) is currently not supported. These definitions must be loaded as [additional-file](../sumo.md#format_of_additional_files) at the start of the simulation.
## controlled connections
`<connection .../>`-elements are an extension of[\#Connection_Descriptions](#connection_descriptions) andare used to define the relationship between a signal plan and thecontrolled connections.
This may be used to simplify signal plans by implementing signal groups.In this case multiple connections are defined by the same index of thesignal plan. It can also be used to define traffic light controllerswhich control multiple intersections.
| Attribute Name | Value Type | Description || -------------- | ------------------ | ---------------------------------------------------------------------------------- || **from** | referenced edge id | The name of the edge the vehicles leave || **to** | referenced edge id | The name of the edge the vehicles may reach when leaving "from" || **fromLane** | int | the lane index of the incoming lane (numbers starting with 0) || **toLane** | int | the lane index of the outgoing lane (numbers starting with 0) || **tl** | string | id of the traffic light which controls this connection || **linkIndex** | int | the index in the *state*-attribute of the `<phase>`-elements which controls this connection || linkIndex2 | int | the index in the *state*-attribute of the `<phase>`-elements which controls the internal junction link (by default this is uncontrolled) |
You can easily get examples for this type of file by loading a*sumo.net.xml* in [netconvert](../netconvert.md) and using option **--plain-output-prefix**.
# Pedestrian Crossings
When building a network for [pedestrian simulation](../Simulation/Pedestrians.md), pedestrian crossings atintersections can be specified explicitly. This is done using elementswithin a[*connection-file*](#connection_descriptions).
```xml<crossing node="C" edges="edge1 edge2" priority="true"/>```
The attributes are described in the following.
| Attribute Name | Value Type | Description || -------------- | ---------------------------------------------- | ------------------------------------------------------------------ || **node** | id (string) | The name of the node at which this crossing is located || **edges** | ids (list of strings) | The (road) edges which are crossed || priority | bool | Whether the pedestrians have priority over the vehicles (automatically set to true at tls-controlled intersections). || width | real (m) | The width of the crossings. || shape | List of positions; each position is encoded in x,y or x,y,z in meters (do not separate the numbers with a space\!). | specifies a custom shape for this crossing. By default it is straight.<br><br>**Caution:** The shape must be defined in counter-clockwise direction around the intersection. || linkIndex | int | specifies a custom index within the signal plan (for the forward direction) || linkIndex2 | int | specifies a custom index within the signal plan (for the backward direction) || discard | bool | Whether the crossing with the given edges shall be discarded. If discard is set to *true* omitting the *edges* attribute results in discarding all crossings. |
Pedestrians may only cross the street at a crossing. Crossings may havepriority which means, pedestrians are free to walk withoutconsiderations for vehicular traffic. This can be used to model thebehavior at controlled intersections and at marked pedestrian crossings(at least for some countries such as Germany). At uncontrolledintersections pedestrians may only cross when there is a suitable gap inroad traffic.
!!! note When two edges that define a bidirectional road are separated (i.e. by a green verge) it is permitted to define a separate crossing for each of the edges. This will result in a so called *split crossing* with an in-between walkingArea.
# Walking Areas
When building a network for [pedestrian simulation](../Simulation/Pedestrians.md) walking areas aregenerated automatically. These network elements are used to connectmultiple side walks and pedestrian crossings (typically one in eachcorner of an intersection). The shape of a walking area can be specifiedexplicitly. This is done using `walkingArea` element within a[*connection-file*](#connection_descriptions).
```xml<walkingArea node="C" edges="SC" shape="115.88,88.57 120.38,88.57 120.38,86.87 120.37,83.87 119.86,80.83 118.46,78.53 115.46,78.50 113.74,78.55 113.73,83.05"/>```
The attributes are described in the following.
| Attribute Name | Value Type | Description || -------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------- || **node** | id (string) | The name of the node at which this walking area is located || **edges** | ids (list of strings) | The (road) edges which uniquely define the walking area. Usually a single edge with a side walk that connects to the walking area is sufficient. In case the walking area does not connect to any side walks but rather connects two pedestrian crossings, the edges that are being crossed by both crossings must be used. || **shape** | List of positions; each position is encoded in x,y or x,y,z in meters (do not separate the numbers with a space\!). | specifies a custom shape for this walking area.| width | double | custom width for waiting/walking on this walking area |```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", "transport_safety/sumo_plainxml_document_inventory_audit"), "taskPrompt": "Task card has not been rendered yet; this fallback exists for stage-03 hook smoke only.", "metadata": { "domain": "transport_safety", "task": "sumo_plainxml_document_inventory_audit", "variant": "base", "domain_name": "transport_safety", "task_name": "sumo_plainxml_document_inventory_audit", "variant_name": "base", "requires_task_data": True, "task_dir": "/media/user/data/agenthle/transport_safety/sumo_plainxml_document_inventory_audit/base", "input_dir": "/media/user/data/agenthle/transport_safety/sumo_plainxml_document_inventory_audit/base/input", "software_dir": "/media/user/data/agenthle/transport_safety/sumo_plainxml_document_inventory_audit/base/software", "remote_output_dir": "/media/user/data/agenthle/transport_safety/sumo_plainxml_document_inventory_audit/base/output", "reference_dir": "/media/user/data/agenthle/transport_safety/sumo_plainxml_document_inventory_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]123456789term,kind,software_name
duarouter,code_term,SUMO
netedit,code_term,SUMO
.net.xml,code_term,SUMO
.rou.xml,code_term,SUMO
sumo,executable,SUMO
netconvert,executable,SUMO
duarouter,executable,SUMO
netedit,executable,SUMO12345678910111213141516171819{ "software_name": "SUMO", "executables": [ "sumo", "netconvert", "duarouter", "netedit" ], "required_system_packages": [ "sumo", "sumo-tools" ], "official_sources": [ "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md" ], "solve_time_network": "disabled", "python_wrapper_only": false, "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs."}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())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114{ "taskId": "transport_safety/sumo_plainxml_document_inventory_audit__20260907-002650_transport_safety_0ac894", "title": "Repair3 20260907 088 Repair2 20260906 094 Repair 20260906 Software 0108", "summary": "Audit a staged offline SUMO traffic-simulation quick-start tutorial and produce reproducible section, keyword, and command inventories from local files (keyword-subset experiment 26: 5 terms) (ALE-100 software diversity variant 28) (independent source snapshot 28). (repair batch 20260906; independent official source) (targeted repair round 2). (targeted repair round 3).", "category": "transport_safety", "taxonomy": { "domain_id": "1", "domain_code": "engineering", "subdomain_id": "1.10", "subdomain_code": "urban_planning", "subdomain_name": "Urban & Spatial Planning", "classifier": { "source": "public software metadata mapping", "rationale": "Subdomain selected from public task metadata." } }, "taskPrompt": "Use a Linux command-line workflow to audit the staged offline official tutorial corpus for SUMO. The source document is input/tutorial_source.html, and input/tutorial_text_windows.csv contains deterministic text windows derived from it. Your job is to reconstruct the section outline, keyword inventory, code-block inventory, and summary statistics from the local files. 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 software_tutorial_doc_audit. The primary staged data file is input/tutorial_text_windows.csv. Produce exactly these required deliverables: output/summary.json, output/section_outline.csv, output/keyword_inventory.csv, output/code_block_inventory.csv. The output schemas are:\n- output/summary.json: JSON keys and nested shape {\"code_block_count\": \"integer\", \"heading_count\": \"integer\", \"keyword_total\": \"integer\", \"software_name\": \"string\", \"source_character_count\": \"integer\", \"source_file\": \"string\", \"top_keyword\": \"string|null\", \"unique_required_terms_found\": \"integer\", \"window_count\": \"integer\"}\n- output/section_outline.csv: CSV header exactly rank, heading_level, heading_text, slug\n- output/keyword_inventory.csv: CSV header exactly term, category, count, first_window, appears_in_code\n- output/code_block_inventory.csv: CSV header exactly block_index, line_count, char_count, contains_code_term, first_line\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/tutorial_text_windows.csv and compute results from the staged local data.", "Create output/summary.json as json exactly as specified by analysis_spec.json.", "Create output/section_outline.csv as csv exactly as specified by analysis_spec.json.", "Create output/keyword_inventory.csv as csv exactly as specified by analysis_spec.json.", "Create output/code_block_inventory.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": "tutorial_metadata.json", "format": "JSON", "path": "input/tutorial_metadata.json", "description": "Agent-visible staged input file for this task." }, { "name": "tutorial_source.html", "format": "HTML", "path": "input/tutorial_source.html", "description": "Agent-visible staged input file for this task." }, { "name": "tutorial_text_windows.csv", "format": "CSV", "path": "input/tutorial_text_windows.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": "section_outline.csv", "format": "CSV", "path": "output/section_outline.csv", "description": "Required agent output file evaluated against hidden reference data." }, { "name": "keyword_inventory.csv", "format": "CSV", "path": "output/keyword_inventory.csv", "description": "Required agent output file evaluated against hidden reference data." }, { "name": "code_block_inventory.csv", "format": "CSV", "path": "output/code_block_inventory.csv", "description": "Required agent output file evaluated against hidden reference data." } ], "software": [ "SUMO", "sumo", "netconvert", "duarouter", "netedit", "Python 3.11", "standard Unix shell", "software/command_examples.csv", "software/software_manifest.json", "software/validate_outputs.py" ], "requiredSystemPackages": [ "sumo", "sumo-tools" ], "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# Repair3 20260907 088 Repair2 20260906 094 Repair 20260906 Software 0108
Audit a staged offline SUMO traffic-simulation quick-start tutorial and produce reproducible section, keyword, and command inventories from local files (keyword-subset experiment 26: 5 terms) (ALE-100 software diversity variant 28) (independent source snapshot 28). (repair batch 20260906; independent official source) (targeted repair round 2). (targeted repair round 3).
## Task
Use a Linux command-line workflow to audit the staged offline official tutorial corpus for SUMO. The source document is input/tutorial_source.html, and input/tutorial_text_windows.csv contains deterministic text windows derived from it. Your job is to reconstruct the section outline, keyword inventory, code-block inventory, and summary statistics from the local files. 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 software_tutorial_doc_audit. The primary staged data file is input/tutorial_text_windows.csv. Produce exactly these required deliverables: output/summary.json, output/section_outline.csv, output/keyword_inventory.csv, output/code_block_inventory.csv. The output schemas are:- output/summary.json: JSON keys and nested shape {"code_block_count": "integer", "heading_count": "integer", "keyword_total": "integer", "software_name": "string", "source_character_count": "integer", "source_file": "string", "top_keyword": "string|null", "unique_required_terms_found": "integer", "window_count": "integer"}- output/section_outline.csv: CSV header exactly rank, heading_level, heading_text, slug- output/keyword_inventory.csv: CSV header exactly term, category, count, first_window, appears_in_code- output/code_block_inventory.csv: CSV header exactly block_index, line_count, char_count, contains_code_term, first_lineCompute 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/section_outline.csv` (csv)- `/workspace/output/keyword_inventory.csv` (csv)- `/workspace/output/code_block_inventory.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 software_tutorial_outputs
def run_reference(input_dir: Path, output_dir: Path) -> None: software_tutorial_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/section_outline.csv", "/workspace/output/keyword_inventory.csv", "/workspace/output/code_block_inventory.csv"]
[task]name = "ale-cli/20260907-002650-transport-safety-0ac894"description = "Audit a staged offline SUMO traffic-simulation quick-start tutorial and produce reproducible section, keyword, and command inventories from local files (keyword-subset experiment 26: 5 terms) (ALE-100 software diversity variant 28) (independent source snapshot 28). (repair batch 20260906; independen"keywords = ["agents-last-exam", "ale-cli", "deterministic-evaluator", "linux-cli", "software-tutorial-doc-audit", "transport-safety"]
[metadata]benchmark = "ale_cli"source_format = "ale_cli_official_style"converter = "ale_cli_to_harbor"source_task_key = "20260907-002650_transport_safety_0ac894"task_id = "transport_safety/sumo_plainxml_document_inventory_audit__20260907-002650_transport_safety_0ac894"domain = "transport_safety"task = "sumo_plainxml_document_inventory_audit"variant = "base"oracle_available = truescoring_method = "deterministic_hidden_evaluator"required_outputs = ["summary.json", "section_outline.csv", "keyword_inventory.csv", "code_block_inventory.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]123456789101112131415161718192021222324252627282930block_index,line_count,char_count,contains_code_term,first_line
1,31,1824,true,---
2,1,50,false,If you also use connections and types the call is:
3,31,1715,false,"The options used here, including their abbreviations, are documented on"
4,27,6599,false,the straight brackets ('\[' and '\]')
5,167,12846,true,"As you may notice, only the first node named ""0"", which is the node in"
6,100,9194,false,"This will cause the nodes *id0*,*id23* and *id24* to be joined into a"
7,30,2425,false,"Within this example, we have used explicit definitions of edges. An"
8,2,90,false,"If you would like to disallow passenger cars and taxis, the following"
9,22,3547,false,The definition of a lane contains the following optional attributes:
10,21,1586,false,Defining this element for an edge will affect all lanes of the edge that
11,10,564,false,What happens here is the following: 30meters from its begin
12,10,585,false,There are several things to note:
13,16,1827,false,The definition of a split uses the following attributes:
14,11,633,false,Manual specification of roundabouts is a useful supplement for the
15,6,278,false,In the above input the inner-most lanes of edges *a* and *b* are
16,21,1195,false,It is also possible to remove all edges of a specific type (see below)
17,1,96,false,The according types file looks like this (see [SUMO edge type file](../SUMO_edge_type_file.md)):
18,8,429,false,"As you can see, we have joined the edges into three classes ""a"", ""b"","
19,40,3274,false,"the value of *vClass* must be a single class from [the list of possible vehicle classes](../Definition_of_Vehicles,_Vehicle_Types,_and_Routes.md#abstract_vehicle_class)."
20,14,1357,false,This tells [netconvert](../netconvert.md) not only that vehicles shall be
21,25,7111,true,"Here, a connection from the edge's ""*<FROM_EDGE_ID\>*"" lane with the number *<INT_1\>* is build to the lane *<INT_2\>* of the edge ""*<TO_EDGE_ID\>*"". Lanes are counted from the right (outer) to the le"
22,16,1609,true,The attributes are the same as for the
23,17,988,false,This will trigger all connections from edge with id `FROM_EDGE_ID` to be removed and re-guessed.
24,9,574,false,"As you may see in the next picture, the horizontal edges within the"
25,12,831,false,The built network looks like this:
26,17,1168,false,"As one may see, it was necessary to prohibit all connections from a"
27,45,3451,true,# Traffic Light Program Definition
28,27,3881,false,The attributes are described in the following.
29,7,1226,false,The attributes are described in the following.12345678910term,category,count,first_window,appears_in_code
.net.xml,code,9,1,true
.rou.xml,code,0,,false
duarouter,code,0,,false
netedit,code,7,101,true
edge,required,242,8,true
network,required,52,1,true
node,required,105,7,true
route,required,4,107,true
vehicle,required,75,64,true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748rank,heading_level,heading_text,slug
1,h1,Source 1: PlainXML.md,source_1_plainxml_md
2,h1,Node Descriptions,node_descriptions
3,h2,Traffic lights,traffic_lights
4,h3,tlType,tltype
5,h3,tlLayout,tllayout
6,h2,Node types,node_types
7,h2,Right-of-way,right_of_way
8,h3,"rightOfWay=""default""",rightofway_default
9,h3,"rightOfWay=""mixedPriority""",rightofway_mixedpriority
10,h3,"rightOfWay=""edgePriority""",rightofway_edgepriority
11,h3,"rightOfWay=""allwayStop""",rightofway_allwaystop
12,h3,Special Cases,special_cases
13,h3,Understanding right-of-way rules in a Network,understanding_right_of_way_rules_in_a_network
14,h3,Modifying Right-of-Way,modifying_right_of_way
15,h2,Fringe,fringe
16,h2,Joining Nodes,joining_nodes
17,h3,Reasons for joining node clusters,reasons_for_joining_node_clusters
18,h3,Algorithm for joining node clusters,algorithm_for_joining_node_clusters
19,h3,Specifying and excluding explicit joins,specifying_and_excluding_explicit_joins
20,h3,Connections after joining nodes,connections_after_joining_nodes
21,h1,Edge Descriptions,edge_descriptions
22,h2,SpreadType,spreadtype
23,h2,"Road access permissions (allow, disallow)",road_access_permissions_allow_disallow
24,h2,Lane-specific Definitions,lane_specific_definitions
25,h3,lane change restrictions,lane_change_restrictions
26,h2,Stop Offsets,stop_offsets
27,h2,Road Segment Refining,road_segment_refining
28,h2,Roundabouts,roundabouts
29,h2,Neighboring opposite-direction Lanes,neighboring_opposite_direction_lanes
30,h2,Deleting edges or lanes,deleting_edges_or_lanes
31,h1,Type Descriptions,type_descriptions
32,h2,vehicle-class specific speed limits,vehicle_class_specific_speed_limits
33,h2,speed on junction,speed_on_junction
34,h1,Connection Descriptions,connection_descriptions
35,h2,Explicitly setting which Edge / Lane is connected to which,explicitly_setting_which_edge_lane_is_connected_to_which
36,h3,Edge-to-Edge connectivity,edge_to_edge_connectivity
37,h3,Lane-to-Lane connectivity,lane_to_lane_connectivity
38,h3,Deleting connections,deleting_connections
39,h3,Patching connections and guessing again,patching_connections_and_guessing_again
40,h3,Examples,examples
41,h2,Setting Connection Priorities,setting_connection_priorities
42,h2,Multiple connections from the same edge to the same target lane,multiple_connections_from_the_same_edge_to_the_same_target_lane
43,h1,Traffic Light Program Definition,traffic_light_program_definition
44,h2,traffic light definitions,traffic_light_definitions
45,h2,controlled connections,controlled_connections
46,h1,Pedestrian Crossings,pedestrian_crossings
47,h1,Walking Areas,walking_areas1234567891011{ "software_name": "SUMO", "source_file": "tutorial_source.html", "window_count": 425, "heading_count": 47, "code_block_count": 29, "keyword_total": 494, "unique_required_terms_found": 5, "top_keyword": "edge", "source_character_count": 56655}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 software_tutorial_outputs
def run_reference(input_dir: Path, output_dir: Path) -> None: software_tutorial_outputs(input_dir, output_dir)12345678910111213141516171819202122232425262728293031323334{ "workflow_kind": "software_tutorial_doc_audit", "task_id": "repair3_20260907_088_repair2_20260906_094_repair_20260906_software_0108", "domain": "transport_safety", "task": "sumo_plainxml_document_inventory_audit", "variant": "base", "created_from": "standard reference workflow", "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" } ], "numeric_tolerance": 1e-09, "source_prior_sha256": "e338ca2c987a612024504d976fa1bc9c500c8779e986043eca1a870f6ef9a2a0", "gold_output_hashes": { "summary.json": "7c3ea2038e4c09fc61bff98483d80a65c9455dd83b288bd4260feaaea58a5233", "section_outline.csv": "2e5418f96aca2bcb5a3ea72bbbcddf959a0be5efa9736f865052f0bd46ba61ec", "keyword_inventory.csv": "21e285cec25a9b9dec2918ee1339d261f1df2b71f4e6c9384e64492c903e6ed0", "code_block_inventory.csv": "7d8b5401cca2b6495d9d19f52e244164132bbb49d79a9a76752069be1d064e85" }}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:23728b1425152eb65ed68df85c78dd546f7d692f222cdfe03e89721aa6b72972size 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293{ "input_file": "tutorial_text_windows.csv", "source_file": "tutorial_source.html", "workflow_kind": "software_tutorial_doc_audit", "software_name": "SUMO", "tutorial_url": "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md", "source_urls": [ "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md" ], "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": [ "SUMO", "network", "route", "edge", "vehicle" ], "code_terms": [ "sumo", "netconvert", "duarouter", "netedit" ], "executables": [ "sumo", "netconvert", "duarouter", "netedit" ], "required_system_packages": [ "sumo", "sumo-tools" ], "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."}20260907-002634-transport-safety-6f2c6a/tests/evaluator_runner.pyAdded+92
20260907-002634-transport-safety-6f2c6a/tests/reference/__pycache__/evaluator.cpython-312.pycAdded
20260907-002634-transport-safety-6f2c6a/tests/reference/evaluator.pyAdded+114
20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/code_block_inventory.csvAdded+30
20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/keyword_inventory.csvAdded+14
20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/section_outline.csvAdded+48
20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/summary.jsonAdded+11
20260907-002634-transport-safety-6f2c6a/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
20260907-002634-transport-safety-6f2c6a/tests/reference/internal/workflow_runtime.pyAdded+5
20260907-002634-transport-safety-6f2c6a/tests/reference/reference_manifest.jsonAdded+34
20260907-002634-transport-safety-6f2c6a/tests/reference/reference_solution.pyAdded+20
20260907-002634-transport-safety-6f2c6a/tests/test.shAdded+29
20260907-002650-transport-safety-0ac894/.DS_StoreAdded+3
20260907-002650-transport-safety-0ac894/environment/DockerfileAdded+12
20260907-002650-transport-safety-0ac894/environment/public_data/README.mdAdded+11
20260907-002650-transport-safety-0ac894/environment/public_data/input/README.mdAdded+6
20260907-002650-transport-safety-0ac894/environment/public_data/input/analysis_spec.jsonAdded+93
20260907-002650-transport-safety-0ac894/environment/public_data/input/source_context_windows.jsonlAdded
20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_metadata.jsonAdded+29
20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_source.htmlAdded+1215
20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_text_windows.csvAdded
20260907-002650-transport-safety-0ac894/environment/public_data/main.pyAdded+180
20260907-002650-transport-safety-0ac894/environment/public_data/software/command_examples.csvAdded+9
20260907-002650-transport-safety-0ac894/environment/public_data/software/software_manifest.jsonAdded+19
20260907-002650-transport-safety-0ac894/environment/public_data/software/validate_outputs.pyAdded+41
20260907-002650-transport-safety-0ac894/environment/public_data/task_card.jsonAdded+114
20260907-002650-transport-safety-0ac894/instruction.mdAdded+33
20260907-002650-transport-safety-0ac894/solution/internal/workflow_adapters_runtime.pyAdded+679
20260907-002650-transport-safety-0ac894/solution/internal/workflow_runtime.pyAdded+5
20260907-002650-transport-safety-0ac894/solution/reference_solution.pyAdded+20
20260907-002650-transport-safety-0ac894/solution/solve.shAdded+7
20260907-002650-transport-safety-0ac894/task.tomlAdded+45
20260907-002650-transport-safety-0ac894/tests/DockerfileAdded+6
20260907-002650-transport-safety-0ac894/tests/evaluator_runner.pyAdded+92
20260907-002650-transport-safety-0ac894/tests/reference/__pycache__/evaluator.cpython-312.pycAdded
20260907-002650-transport-safety-0ac894/tests/reference/evaluator.pyAdded+114
20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/code_block_inventory.csvAdded+30
20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/keyword_inventory.csvAdded+10
20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/section_outline.csvAdded+48
20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/summary.jsonAdded+11
20260907-002650-transport-safety-0ac894/tests/reference/internal/workflow_adapters_runtime.pyAdded+679
20260907-002650-transport-safety-0ac894/tests/reference/internal/workflow_runtime.pyAdded+5
20260907-002650-transport-safety-0ac894/tests/reference/reference_manifest.jsonAdded+34
20260907-002650-transport-safety-0ac894/tests/reference/reference_solution.pyAdded+20
20260907-002650-transport-safety-0ac894/tests/test.shAdded+29
20260907-002702-transport-safety-26060d/.DS_StoreAdded+3
20260907-002702-transport-safety-26060d/environment/DockerfileAdded+12
20260907-002702-transport-safety-26060d/environment/public_data/README.mdAdded+11
20260907-002702-transport-safety-26060d/environment/public_data/input/README.mdAdded+6
20260907-002702-transport-safety-26060d/environment/public_data/input/analysis_spec.jsonAdded+93