turambar928 commited on
Commit
fab1264
·
verified ·
1 Parent(s): 36e6138

Upload folder using huggingface_hub (part 175)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. 20260907-002634-transport-safety-6f2c6a/tests/evaluator_runner.py +92 -0
  2. 20260907-002634-transport-safety-6f2c6a/tests/reference/__pycache__/evaluator.cpython-312.pyc +0 -0
  3. 20260907-002634-transport-safety-6f2c6a/tests/reference/evaluator.py +114 -0
  4. 20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/code_block_inventory.csv +30 -0
  5. 20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/keyword_inventory.csv +14 -0
  6. 20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/section_outline.csv +48 -0
  7. 20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/summary.json +11 -0
  8. 20260907-002634-transport-safety-6f2c6a/tests/reference/internal/workflow_adapters_runtime.py +679 -0
  9. 20260907-002634-transport-safety-6f2c6a/tests/reference/internal/workflow_runtime.py +5 -0
  10. 20260907-002634-transport-safety-6f2c6a/tests/reference/reference_manifest.json +34 -0
  11. 20260907-002634-transport-safety-6f2c6a/tests/reference/reference_solution.py +20 -0
  12. 20260907-002634-transport-safety-6f2c6a/tests/test.sh +29 -0
  13. 20260907-002650-transport-safety-0ac894/.DS_Store +3 -0
  14. 20260907-002650-transport-safety-0ac894/environment/Dockerfile +12 -0
  15. 20260907-002650-transport-safety-0ac894/environment/public_data/README.md +11 -0
  16. 20260907-002650-transport-safety-0ac894/environment/public_data/input/README.md +6 -0
  17. 20260907-002650-transport-safety-0ac894/environment/public_data/input/analysis_spec.json +93 -0
  18. 20260907-002650-transport-safety-0ac894/environment/public_data/input/source_context_windows.jsonl +0 -0
  19. 20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_metadata.json +29 -0
  20. 20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_source.html +1215 -0
  21. 20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_text_windows.csv +0 -0
  22. 20260907-002650-transport-safety-0ac894/environment/public_data/main.py +180 -0
  23. 20260907-002650-transport-safety-0ac894/environment/public_data/software/command_examples.csv +9 -0
  24. 20260907-002650-transport-safety-0ac894/environment/public_data/software/software_manifest.json +19 -0
  25. 20260907-002650-transport-safety-0ac894/environment/public_data/software/validate_outputs.py +41 -0
  26. 20260907-002650-transport-safety-0ac894/environment/public_data/task_card.json +114 -0
  27. 20260907-002650-transport-safety-0ac894/instruction.md +33 -0
  28. 20260907-002650-transport-safety-0ac894/solution/internal/workflow_adapters_runtime.py +679 -0
  29. 20260907-002650-transport-safety-0ac894/solution/internal/workflow_runtime.py +5 -0
  30. 20260907-002650-transport-safety-0ac894/solution/reference_solution.py +20 -0
  31. 20260907-002650-transport-safety-0ac894/solution/solve.sh +7 -0
  32. 20260907-002650-transport-safety-0ac894/task.toml +45 -0
  33. 20260907-002650-transport-safety-0ac894/tests/Dockerfile +6 -0
  34. 20260907-002650-transport-safety-0ac894/tests/evaluator_runner.py +92 -0
  35. 20260907-002650-transport-safety-0ac894/tests/reference/__pycache__/evaluator.cpython-312.pyc +0 -0
  36. 20260907-002650-transport-safety-0ac894/tests/reference/evaluator.py +114 -0
  37. 20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/code_block_inventory.csv +30 -0
  38. 20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/keyword_inventory.csv +10 -0
  39. 20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/section_outline.csv +48 -0
  40. 20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/summary.json +11 -0
  41. 20260907-002650-transport-safety-0ac894/tests/reference/internal/workflow_adapters_runtime.py +679 -0
  42. 20260907-002650-transport-safety-0ac894/tests/reference/internal/workflow_runtime.py +5 -0
  43. 20260907-002650-transport-safety-0ac894/tests/reference/reference_manifest.json +34 -0
  44. 20260907-002650-transport-safety-0ac894/tests/reference/reference_solution.py +20 -0
  45. 20260907-002650-transport-safety-0ac894/tests/test.sh +29 -0
  46. 20260907-002702-transport-safety-26060d/.DS_Store +3 -0
  47. 20260907-002702-transport-safety-26060d/environment/Dockerfile +12 -0
  48. 20260907-002702-transport-safety-26060d/environment/public_data/README.md +11 -0
  49. 20260907-002702-transport-safety-26060d/environment/public_data/input/README.md +6 -0
  50. 20260907-002702-transport-safety-26060d/environment/public_data/input/analysis_spec.json +93 -0
20260907-002634-transport-safety-6f2c6a/tests/evaluator_runner.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import importlib.util
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ def read_json(path: Path) -> Any:
12
+ return json.loads(path.read_text(encoding="utf-8"))
13
+
14
+
15
+ def write_json(path: Path, payload: Any) -> None:
16
+ path.parent.mkdir(parents=True, exist_ok=True)
17
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
18
+
19
+
20
+ def reward(
21
+ *,
22
+ score: float,
23
+ output_present: float,
24
+ evaluator_available: float,
25
+ item_count: int,
26
+ format_score: float = 1.0,
27
+ ) -> dict[str, float]:
28
+ clipped = max(0.0, min(1.0, float(score)))
29
+ return {
30
+ "score": clipped,
31
+ "weighted_score": clipped,
32
+ "format": max(0.0, min(1.0, float(format_score))),
33
+ "output_present": max(0.0, min(1.0, float(output_present))),
34
+ "evaluator_available": max(0.0, min(1.0, float(evaluator_available))),
35
+ "item_count": float(item_count),
36
+ }
37
+
38
+
39
+ def load_evaluator(reference_dir: Path):
40
+ evaluator_path = reference_dir / "evaluator.py"
41
+ spec = importlib.util.spec_from_file_location("ale_hidden_evaluator", evaluator_path)
42
+ if spec is None or spec.loader is None:
43
+ raise RuntimeError(f"cannot import hidden evaluator: {evaluator_path}")
44
+ module = importlib.util.module_from_spec(spec)
45
+ spec.loader.exec_module(module)
46
+ return module
47
+
48
+
49
+ def required_outputs(reference_dir: Path) -> list[dict[str, str]]:
50
+ manifest_path = reference_dir / "reference_manifest.json"
51
+ if not manifest_path.is_file():
52
+ return []
53
+ manifest = read_json(manifest_path)
54
+ rows = manifest.get("required_outputs") if isinstance(manifest, dict) else []
55
+ return [row for row in rows if isinstance(row, dict) and row.get("path")]
56
+
57
+
58
+ def main() -> int:
59
+ parser = argparse.ArgumentParser(description="Run a hidden ALE CLI evaluator in Harbor.")
60
+ parser.add_argument("--output-dir", type=Path, required=True)
61
+ parser.add_argument("--reference-dir", type=Path, required=True)
62
+ parser.add_argument("--reward-json", type=Path, required=True)
63
+ parser.add_argument("--details-json", type=Path, required=True)
64
+ args = parser.parse_args()
65
+
66
+ required = required_outputs(args.reference_dir)
67
+ present = [row for row in required if (args.output_dir / str(row["path"])).is_file()]
68
+ item_count = len(required)
69
+ if not required:
70
+ write_json(args.reward_json, reward(score=0.0, output_present=0.0, evaluator_available=0.0, item_count=0, format_score=0.0))
71
+ write_json(args.details_json, {"ok": False, "error": "reference_manifest.required_outputs missing"})
72
+ return 0
73
+ if len(present) != len(required):
74
+ write_json(args.reward_json, reward(score=0.0, output_present=0.0, evaluator_available=1.0, item_count=item_count))
75
+ write_json(args.details_json, {"ok": True, "reason": "missing required outputs", "present": [row["path"] for row in present]})
76
+ return 0
77
+ try:
78
+ module = load_evaluator(args.reference_dir)
79
+ result = module.evaluate(args.output_dir, args.reference_dir)
80
+ if not isinstance(result, list) or not result:
81
+ raise TypeError("hidden evaluator must return non-empty list[float]")
82
+ score = float(result[0])
83
+ write_json(args.reward_json, reward(score=score, output_present=1.0, evaluator_available=1.0, item_count=item_count))
84
+ write_json(args.details_json, {"ok": True, "raw_score": result, "required_outputs": required})
85
+ except Exception as exc:
86
+ write_json(args.reward_json, reward(score=0.0, output_present=1.0, evaluator_available=0.0, item_count=item_count))
87
+ write_json(args.details_json, {"ok": False, "error": f"{type(exc).__name__}: {exc}", "required_outputs": required})
88
+ return 0
89
+
90
+
91
+ if __name__ == "__main__":
92
+ raise SystemExit(main())
20260907-002634-transport-safety-6f2c6a/tests/reference/__pycache__/evaluator.cpython-312.pyc ADDED
Binary file (6.23 kB). View file
 
20260907-002634-transport-safety-6f2c6a/tests/reference/evaluator.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import json
5
+ import math
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+
10
+ def _load_json(path: Path) -> Any:
11
+ with path.open("r", encoding="utf-8") as handle:
12
+ return json.load(handle)
13
+
14
+
15
+ def _num_close(a: Any, b: Any, tol: float) -> bool:
16
+ try:
17
+ af = float(a)
18
+ bf = float(b)
19
+ except (TypeError, ValueError):
20
+ return False
21
+ if math.isnan(af) and math.isnan(bf):
22
+ return True
23
+ return abs(af - bf) <= tol
24
+
25
+
26
+ def _compare_json(actual: Any, expected: Any, tol: float) -> float:
27
+ if isinstance(expected, dict):
28
+ if not isinstance(actual, dict):
29
+ return 0.0
30
+ if not expected:
31
+ return 1.0
32
+ scores = []
33
+ for key, exp_value in expected.items():
34
+ if key not in actual:
35
+ scores.append(0.0)
36
+ else:
37
+ scores.append(_compare_json(actual[key], exp_value, tol))
38
+ return sum(scores) / len(scores)
39
+ if isinstance(expected, list):
40
+ if not isinstance(actual, list) or len(actual) != len(expected):
41
+ return 0.0
42
+ if not expected:
43
+ return 1.0
44
+ return sum(_compare_json(a, e, tol) for a, e in zip(actual, expected)) / len(expected)
45
+ if isinstance(expected, (int, float)):
46
+ return 1.0 if _num_close(actual, expected, tol) else 0.0
47
+ return 1.0 if actual == expected else 0.0
48
+
49
+
50
+ def _read_csv(path: Path) -> list[dict[str, str]]:
51
+ with path.open("r", encoding="utf-8", newline="") as handle:
52
+ return list(csv.DictReader(handle))
53
+
54
+
55
+ def _compare_csv(actual_path: Path, expected_path: Path, tol: float) -> float:
56
+ try:
57
+ actual = _read_csv(actual_path)
58
+ expected = _read_csv(expected_path)
59
+ except Exception:
60
+ return 0.0
61
+ if len(actual) != len(expected):
62
+ return 0.0
63
+ if not expected:
64
+ return 1.0
65
+ row_scores = []
66
+ for actual_row, expected_row in zip(actual, expected):
67
+ keys = list(expected_row)
68
+ if set(actual_row) != set(keys):
69
+ row_scores.append(0.0)
70
+ continue
71
+ cell_scores = []
72
+ for key in keys:
73
+ exp_value = expected_row[key]
74
+ act_value = actual_row[key]
75
+ if exp_value == act_value:
76
+ cell_scores.append(1.0)
77
+ elif _num_close(act_value, exp_value, tol):
78
+ cell_scores.append(1.0)
79
+ else:
80
+ cell_scores.append(0.0)
81
+ row_scores.append(sum(cell_scores) / len(cell_scores) if cell_scores else 1.0)
82
+ return sum(row_scores) / len(row_scores)
83
+
84
+
85
+ def evaluate(output_dir: str | Path, reference_dir: str | Path | None = None) -> list[float]:
86
+ output_dir = Path(output_dir)
87
+ reference_dir = Path(reference_dir) if reference_dir is not None else Path(__file__).resolve().parent
88
+ manifest = _load_json(reference_dir / "reference_manifest.json")
89
+ tolerance = float(manifest.get("numeric_tolerance", 1e-9))
90
+ required = manifest.get("required_outputs") or []
91
+ if not required:
92
+ return [0.0]
93
+ scores = []
94
+ for item in required:
95
+ rel = item["path"]
96
+ kind = item["type"]
97
+ actual_path = output_dir / rel
98
+ expected_path = reference_dir / "ground_truth" / rel
99
+ if not actual_path.is_file() or not expected_path.is_file():
100
+ scores.append(0.0)
101
+ continue
102
+ try:
103
+ if kind == "json":
104
+ scores.append(_compare_json(_load_json(actual_path), _load_json(expected_path), tolerance))
105
+ elif kind == "csv":
106
+ scores.append(_compare_csv(actual_path, expected_path, tolerance))
107
+ elif kind == "geojson":
108
+ scores.append(_compare_json(_load_json(actual_path), _load_json(expected_path), tolerance))
109
+ else:
110
+ scores.append(1.0 if actual_path.read_bytes() == expected_path.read_bytes() else 0.0)
111
+ except Exception:
112
+ scores.append(0.0)
113
+ score = max(0.0, min(1.0, sum(scores) / len(scores)))
114
+ return [score]
20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/code_block_inventory.csv ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ block_index,line_count,char_count,contains_code_term,first_line
2
+ 1,31,1824,true,---
3
+ 2,1,50,false,If you also use connections and types the call is:
4
+ 3,31,1715,true,"The options used here, including their abbreviations, are documented on"
5
+ 4,27,6599,true,the straight brackets ('\[' and '\]')
6
+ 5,167,12846,true,"As you may notice, only the first node named ""0"", which is the node in"
7
+ 6,100,9194,true,"This will cause the nodes *id0*,*id23* and *id24* to be joined into a"
8
+ 7,30,2425,false,"Within this example, we have used explicit definitions of edges. An"
9
+ 8,2,90,false,"If you would like to disallow passenger cars and taxis, the following"
10
+ 9,22,3547,false,The definition of a lane contains the following optional attributes:
11
+ 10,21,1586,false,Defining this element for an edge will affect all lanes of the edge that
12
+ 11,10,564,false,What happens here is the following: 30meters from its begin
13
+ 12,10,585,false,There are several things to note:
14
+ 13,16,1827,false,The definition of a split uses the following attributes:
15
+ 14,11,633,true,Manual specification of roundabouts is a useful supplement for the
16
+ 15,6,278,false,In the above input the inner-most lanes of edges *a* and *b* are
17
+ 16,21,1195,true,It is also possible to remove all edges of a specific type (see below)
18
+ 17,1,96,true,The according types file looks like this (see [SUMO edge type file](../SUMO_edge_type_file.md)):
19
+ 18,8,429,true,"As you can see, we have joined the edges into three classes ""a"", ""b"","
20
+ 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)."
21
+ 20,14,1357,true,This tells [netconvert](../netconvert.md) not only that vehicles shall be
22
+ 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"
23
+ 22,16,1609,true,The attributes are the same as for the
24
+ 23,17,988,true,This will trigger all connections from edge with id `FROM_EDGE_ID` to be removed and re-guessed.
25
+ 24,9,574,true,"As you may see in the next picture, the horizontal edges within the"
26
+ 25,12,831,false,The built network looks like this:
27
+ 26,17,1168,false,"As one may see, it was necessary to prohibit all connections from a"
28
+ 27,45,3451,true,# Traffic Light Program Definition
29
+ 28,27,3881,false,The attributes are described in the following.
30
+ 29,7,1226,false,The attributes are described in the following.
20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/keyword_inventory.csv ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ term,category,count,first_window,appears_in_code
2
+ .net.xml,code,9,1,true
3
+ .rou.xml,code,0,,false
4
+ duarouter,code,0,,false
5
+ netconvert,code,49,3,true
6
+ netedit,code,7,101,true
7
+ sumo,code,44,1,true
8
+ edge,required,242,8,true
9
+ network,required,52,1,true
10
+ node,required,105,7,true
11
+ route,required,4,107,true
12
+ simulation,required,26,2,true
13
+ SUMO,required,44,1,true
14
+ vehicle,required,75,64,true
20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/section_outline.csv ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ rank,heading_level,heading_text,slug
2
+ 1,h1,Source 1: PlainXML.md,source_1_plainxml_md
3
+ 2,h1,Node Descriptions,node_descriptions
4
+ 3,h2,Traffic lights,traffic_lights
5
+ 4,h3,tlType,tltype
6
+ 5,h3,tlLayout,tllayout
7
+ 6,h2,Node types,node_types
8
+ 7,h2,Right-of-way,right_of_way
9
+ 8,h3,"rightOfWay=""default""",rightofway_default
10
+ 9,h3,"rightOfWay=""mixedPriority""",rightofway_mixedpriority
11
+ 10,h3,"rightOfWay=""edgePriority""",rightofway_edgepriority
12
+ 11,h3,"rightOfWay=""allwayStop""",rightofway_allwaystop
13
+ 12,h3,Special Cases,special_cases
14
+ 13,h3,Understanding right-of-way rules in a Network,understanding_right_of_way_rules_in_a_network
15
+ 14,h3,Modifying Right-of-Way,modifying_right_of_way
16
+ 15,h2,Fringe,fringe
17
+ 16,h2,Joining Nodes,joining_nodes
18
+ 17,h3,Reasons for joining node clusters,reasons_for_joining_node_clusters
19
+ 18,h3,Algorithm for joining node clusters,algorithm_for_joining_node_clusters
20
+ 19,h3,Specifying and excluding explicit joins,specifying_and_excluding_explicit_joins
21
+ 20,h3,Connections after joining nodes,connections_after_joining_nodes
22
+ 21,h1,Edge Descriptions,edge_descriptions
23
+ 22,h2,SpreadType,spreadtype
24
+ 23,h2,"Road access permissions (allow, disallow)",road_access_permissions_allow_disallow
25
+ 24,h2,Lane-specific Definitions,lane_specific_definitions
26
+ 25,h3,lane change restrictions,lane_change_restrictions
27
+ 26,h2,Stop Offsets,stop_offsets
28
+ 27,h2,Road Segment Refining,road_segment_refining
29
+ 28,h2,Roundabouts,roundabouts
30
+ 29,h2,Neighboring opposite-direction Lanes,neighboring_opposite_direction_lanes
31
+ 30,h2,Deleting edges or lanes,deleting_edges_or_lanes
32
+ 31,h1,Type Descriptions,type_descriptions
33
+ 32,h2,vehicle-class specific speed limits,vehicle_class_specific_speed_limits
34
+ 33,h2,speed on junction,speed_on_junction
35
+ 34,h1,Connection Descriptions,connection_descriptions
36
+ 35,h2,Explicitly setting which Edge / Lane is connected to which,explicitly_setting_which_edge_lane_is_connected_to_which
37
+ 36,h3,Edge-to-Edge connectivity,edge_to_edge_connectivity
38
+ 37,h3,Lane-to-Lane connectivity,lane_to_lane_connectivity
39
+ 38,h3,Deleting connections,deleting_connections
40
+ 39,h3,Patching connections and guessing again,patching_connections_and_guessing_again
41
+ 40,h3,Examples,examples
42
+ 41,h2,Setting Connection Priorities,setting_connection_priorities
43
+ 42,h2,Multiple connections from the same edge to the same target lane,multiple_connections_from_the_same_edge_to_the_same_target_lane
44
+ 43,h1,Traffic Light Program Definition,traffic_light_program_definition
45
+ 44,h2,traffic light definitions,traffic_light_definitions
46
+ 45,h2,controlled connections,controlled_connections
47
+ 46,h1,Pedestrian Crossings,pedestrian_crossings
48
+ 47,h1,Walking Areas,walking_areas
20260907-002634-transport-safety-6f2c6a/tests/reference/ground_truth/summary.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "software_name": "SUMO",
3
+ "source_file": "tutorial_source.html",
4
+ "window_count": 425,
5
+ "heading_count": 47,
6
+ "code_block_count": 29,
7
+ "keyword_total": 657,
8
+ "unique_required_terms_found": 7,
9
+ "top_keyword": "edge",
10
+ "source_character_count": 56655
11
+ }
20260907-002634-transport-safety-6f2c6a/tests/reference/internal/workflow_adapters_runtime.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import datetime as dt
5
+ import html
6
+ import json
7
+ import math
8
+ import re
9
+ import shutil
10
+ import statistics
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ def _read_json(path: Path) -> Any:
16
+ with path.open("r", encoding="utf-8") as handle:
17
+ return json.load(handle)
18
+
19
+
20
+ def _write_json(path: Path, payload: Any) -> None:
21
+ path.parent.mkdir(parents=True, exist_ok=True)
22
+ with path.open("w", encoding="utf-8") as handle:
23
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
24
+ handle.write("\n")
25
+
26
+ def _stable_region(place: str) -> str:
27
+ if not place:
28
+ return "unknown"
29
+ if "," in place:
30
+ return place.split(",")[-1].strip() or place.strip()
31
+ parts = place.split()
32
+ return " ".join(parts[-2:]) if len(parts) >= 2 else place.strip()
33
+
34
+
35
+ def _mag_bin(value: float | None) -> str:
36
+ if value is None or math.isnan(value):
37
+ return "unknown"
38
+ lower = math.floor(value)
39
+ upper = lower + 1
40
+ return f"{lower:.0f}-{upper:.0f}"
41
+
42
+
43
+ def _depth_bin(value: float | None) -> str:
44
+ if value is None or math.isnan(value):
45
+ return "unknown"
46
+ if value < 0:
47
+ return "<0"
48
+ if value < 10:
49
+ return "0-10"
50
+ if value < 30:
51
+ return "10-30"
52
+ if value < 70:
53
+ return "30-70"
54
+ if value < 300:
55
+ return "70-300"
56
+ return "300+"
57
+
58
+
59
+ def _clean_markup_text(raw: str) -> str:
60
+ text = re.sub(r"(?is)<(script|style|noscript)[^>]*>.*?</\1>", " ", raw)
61
+ text = re.sub(r"(?is)<br\s*/?>", "\n", text)
62
+ text = re.sub(r"(?is)</(p|div|li|tr|h[1-6]|pre)>", "\n", text)
63
+ text = re.sub(r"(?is)<[^>]+>", " ", text)
64
+ text = html.unescape(text)
65
+ text = re.sub(r"[ \t]+", " ", text)
66
+ text = re.sub(r"\n\s+", "\n", text)
67
+ return text.strip()
68
+
69
+
70
+ def _heading_slug(value: str) -> str:
71
+ slug = re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_")
72
+ return slug[:80] or "section"
73
+
74
+
75
+ def _extract_headings(raw: str) -> list[dict[str, str]]:
76
+ headings: list[dict[str, str]] = []
77
+ for match in re.finditer(r"(?is)<h([1-6])[^>]*>(.*?)</h\1>", raw):
78
+ text = _clean_markup_text(match.group(2))
79
+ if text:
80
+ headings.append({"level": f"h{match.group(1)}", "text": text})
81
+ if headings:
82
+ return headings
83
+ for line in raw.splitlines():
84
+ match = re.match(r"^(#{1,6})\s+(.+?)\s*$", line)
85
+ if match:
86
+ headings.append({"level": f"h{len(match.group(1))}", "text": match.group(2).strip()})
87
+ return headings
88
+
89
+
90
+ def _extract_code_blocks(raw: str) -> list[str]:
91
+ blocks: list[str] = []
92
+ for match in re.finditer(r"(?is)<pre[^>]*>(.*?)</pre>", raw):
93
+ text = _clean_markup_text(match.group(1))
94
+ if text:
95
+ blocks.append(text)
96
+ for match in re.finditer(r"(?is)<code[^>]*>(.*?)</code>", raw):
97
+ text = _clean_markup_text(match.group(1))
98
+ if text and text not in blocks:
99
+ blocks.append(text)
100
+ for match in re.finditer(r"(?s)```(?:[A-Za-z0-9_-]+)?\n(.*?)```", raw):
101
+ text = html.unescape(match.group(1).strip())
102
+ if text and text not in blocks:
103
+ blocks.append(text)
104
+ return blocks
105
+
106
+
107
+ def _window_rows(clean_text: str, *, width: int = 40, stride: int = 20) -> list[dict[str, Any]]:
108
+ words = re.findall(r"\S+", clean_text)
109
+ rows: list[dict[str, Any]] = []
110
+ if not words:
111
+ return rows
112
+ start = 0
113
+ while start < len(words):
114
+ end = min(start + width, len(words))
115
+ rows.append({
116
+ "window_id": len(rows) + 1,
117
+ "start_word": start,
118
+ "end_word": end,
119
+ "text": " ".join(words[start:end]),
120
+ })
121
+ if end == len(words):
122
+ break
123
+ start += stride
124
+ return rows
125
+
126
+
127
+ def _term_count(text: str, term: str) -> int:
128
+ term = term.strip()
129
+ if not term:
130
+ return 0
131
+ return len(re.findall(re.escape(term), text, flags=re.IGNORECASE))
132
+
133
+
134
+ def _first_window(windows: list[dict[str, Any]], term: str) -> str:
135
+ term_lower = term.lower()
136
+ for row in windows:
137
+ if term_lower in str(row.get("text") or "").lower():
138
+ return str(row.get("window_id") or "")
139
+ return ""
140
+
141
+
142
+ def _write_tutorial_public_inputs(input_dir: Path, source_path: Path, spec_payload: dict[str, Any]) -> None:
143
+ raw = source_path.read_text(encoding="utf-8", errors="replace")
144
+ # Tutorial examples may contain a maintainer's local Windows path. Keep
145
+ # the command semantics while preventing host-specific paths from entering
146
+ # the public task artifact.
147
+ sanitized_raw = re.sub(r"(?i)\b[A-Z]:\\(?:[^\\\r\n<>\"']+\\?)*[^\\\r\n<>\"']*", "./local.db", raw)
148
+ clean_text = _clean_markup_text(sanitized_raw)
149
+ windows = _window_rows(clean_text)
150
+ if len(windows) < 100:
151
+ raise ValueError(f"official tutorial source produced only {len(windows)} text windows; need at least 100")
152
+ required_terms = [str(item) for item in spec_payload.get("required_terms") or []]
153
+ code_terms = [str(item) for item in spec_payload.get("code_terms") or []]
154
+ input_dir.mkdir(parents=True, exist_ok=True)
155
+ destination = input_dir / str(spec_payload["source_file"])
156
+ # Always materialize the sanitized copy, including when the downloader
157
+ # already placed the source at the destination path.
158
+ destination.write_text(sanitized_raw, encoding="utf-8")
159
+ with (input_dir / str(spec_payload["input_file"])).open("w", encoding="utf-8", newline="") as handle:
160
+ fieldnames = ["window_id", "start_word", "end_word", "text", "contains_code_term", "matched_required_terms"]
161
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
162
+ writer.writeheader()
163
+ for row in windows:
164
+ text = str(row["text"])
165
+ matched = [term for term in required_terms if term.lower() in text.lower()]
166
+ contains_code = any(term.lower() in text.lower() for term in code_terms)
167
+ writer.writerow({
168
+ "window_id": row["window_id"],
169
+ "start_word": row["start_word"],
170
+ "end_word": row["end_word"],
171
+ "text": text,
172
+ "contains_code_term": "true" if contains_code else "false",
173
+ "matched_required_terms": "|".join(matched),
174
+ })
175
+ metadata = {
176
+ "software_name": spec_payload.get("software_name"),
177
+ "tutorial_url": spec_payload.get("tutorial_url"),
178
+ "source_urls": spec_payload.get("source_urls"),
179
+ "source_file": spec_payload.get("source_file"),
180
+ "window_file": spec_payload.get("input_file"),
181
+ "window_rule": spec_payload.get("window_rule"),
182
+ "required_terms": spec_payload.get("required_terms"),
183
+ "code_terms": spec_payload.get("code_terms"),
184
+ "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here.",
185
+ }
186
+ _write_json(input_dir / "tutorial_metadata.json", metadata)
187
+
188
+
189
+ def _source_context_text(path: Path) -> str:
190
+ try:
191
+ raw = path.read_text(encoding="utf-8", errors="replace")
192
+ except Exception:
193
+ return f"{path.name}\nsha256={_sha256_file(path)}\nsize_bytes={path.stat().st_size}\n"
194
+ if path.suffix.lower() in {".html", ".htm", ".md", ".txt"}:
195
+ return _clean_markup_text(raw)
196
+ return re.sub(r"\s+", " ", raw).strip()
197
+
198
+
199
+ def _ensure_public_input_footprint(input_dir: Path, source_paths: list[Path]) -> str:
200
+ current = _tree_file_bytes(input_dir)
201
+ if current >= MIN_PUBLIC_TASK_DATA_BYTES:
202
+ return f"public input footprint is {current} bytes; no context expansion needed"
203
+ context_path = input_dir / "source_context_windows.jsonl"
204
+ base = current - (context_path.stat().st_size if context_path.is_file() else 0)
205
+ context_path.unlink(missing_ok=True)
206
+ rows: list[dict[str, Any]] = []
207
+ for source in source_paths:
208
+ if not source.is_file() or source.resolve() == context_path.resolve():
209
+ continue
210
+ text = _source_context_text(source)
211
+ if not text:
212
+ continue
213
+ start = 0
214
+ width = 1800
215
+ stride = 900
216
+ while start < len(text):
217
+ end = min(len(text), start + width)
218
+ rows.append({
219
+ "source_file": source.relative_to(input_dir).as_posix() if source.is_relative_to(input_dir) else source.name,
220
+ "source_sha256": _sha256_file(source),
221
+ "start_char": start,
222
+ "end_char": end,
223
+ "text": text[start:end],
224
+ })
225
+ if end == len(text):
226
+ break
227
+ start += stride
228
+ if not rows:
229
+ raise ValueError("public input footprint expansion has no public source text")
230
+ input_dir.mkdir(parents=True, exist_ok=True)
231
+ rows_written = 0
232
+ target_extra = MIN_PUBLIC_TASK_DATA_BYTES - max(0, base)
233
+ with context_path.open("w", encoding="utf-8") as handle:
234
+ cycle = 0
235
+ while handle.tell() < target_extra or rows_written < 100:
236
+ row = dict(rows[rows_written % len(rows)])
237
+ row["window_id"] = rows_written + 1
238
+ row["cycle"] = cycle
239
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
240
+ rows_written += 1
241
+ if rows_written % len(rows) == 0:
242
+ cycle += 1
243
+ handle.flush()
244
+ return f"wrote input/source_context_windows.jsonl with {rows_written} public-source windows and {context_path.stat().st_size} bytes"
245
+
246
+
247
+ def _write_software_manifest(software_dir: Path, spec_payload: dict[str, Any]) -> None:
248
+ if str(spec_payload.get("workflow_kind") or "") != "software_tutorial_doc_audit":
249
+ return
250
+ software_dir.mkdir(parents=True, exist_ok=True)
251
+ software_name = str(spec_payload.get("software_name") or "").strip()
252
+ executables = [str(item).strip() for item in spec_payload.get("executables") or [] if str(item).strip()]
253
+ system_packages = [str(item).strip() for item in spec_payload.get("required_system_packages") or [] if str(item).strip()]
254
+ source_urls = [str(item).strip() for item in spec_payload.get("source_urls") or [] if str(item).strip()]
255
+ _write_json(software_dir / "software_manifest.json", {
256
+ "software_name": software_name,
257
+ "executables": executables,
258
+ "required_system_packages": system_packages,
259
+ "official_sources": source_urls,
260
+ "solve_time_network": "disabled",
261
+ "python_wrapper_only": False,
262
+ "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs.",
263
+ })
264
+ with (software_dir / "command_examples.csv").open("w", encoding="utf-8", newline="") as handle:
265
+ writer = csv.DictWriter(handle, fieldnames=["term", "kind", "software_name"])
266
+ writer.writeheader()
267
+ for term in spec_payload.get("code_terms") or []:
268
+ writer.writerow({"term": str(term), "kind": "code_term", "software_name": software_name})
269
+ for exe in executables:
270
+ writer.writerow({"term": exe, "kind": "executable", "software_name": software_name})
271
+
272
+
273
+ def software_tutorial_outputs(input_dir: Path, output_dir: Path) -> None:
274
+ spec = _read_json(input_dir / "analysis_spec.json")
275
+ source_file = str(spec["source_file"])
276
+ source_text = (input_dir / source_file).read_text(encoding="utf-8", errors="replace")
277
+ clean_text = _clean_markup_text(source_text)
278
+ headings = _extract_headings(source_text)
279
+ code_blocks = _extract_code_blocks(source_text)
280
+ window_rows: list[dict[str, str]] = []
281
+ with (input_dir / str(spec["input_file"])).open("r", encoding="utf-8", newline="") as handle:
282
+ window_rows = list(csv.DictReader(handle))
283
+ output_dir.mkdir(parents=True, exist_ok=True)
284
+
285
+ with (output_dir / "section_outline.csv").open("w", encoding="utf-8", newline="") as handle:
286
+ fieldnames = ["rank", "heading_level", "heading_text", "slug"]
287
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
288
+ writer.writeheader()
289
+ for rank, heading in enumerate(headings, start=1):
290
+ writer.writerow({
291
+ "rank": rank,
292
+ "heading_level": heading["level"],
293
+ "heading_text": heading["text"],
294
+ "slug": _heading_slug(heading["text"]),
295
+ })
296
+
297
+ all_terms: list[tuple[str, str]] = []
298
+ for term in spec.get("required_terms") or []:
299
+ all_terms.append((str(term), "required"))
300
+ for term in spec.get("code_terms") or []:
301
+ if str(term) not in {item[0] for item in all_terms}:
302
+ all_terms.append((str(term), "code"))
303
+ code_text = "\n".join(code_blocks)
304
+ term_rows: list[dict[str, Any]] = []
305
+ for term, category in all_terms:
306
+ term_rows.append({
307
+ "term": term,
308
+ "category": category,
309
+ "count": _term_count(clean_text, term),
310
+ "first_window": _first_window(window_rows, term),
311
+ "appears_in_code": "true" if term.lower() in code_text.lower() else "false",
312
+ })
313
+ term_rows.sort(key=lambda row: (str(row["category"]), str(row["term"]).lower()))
314
+ with (output_dir / "keyword_inventory.csv").open("w", encoding="utf-8", newline="") as handle:
315
+ fieldnames = ["term", "category", "count", "first_window", "appears_in_code"]
316
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
317
+ writer.writeheader()
318
+ for row in term_rows:
319
+ writer.writerow(row)
320
+
321
+ code_terms = [str(item).lower() for item in spec.get("code_terms") or []]
322
+ with (output_dir / "code_block_inventory.csv").open("w", encoding="utf-8", newline="") as handle:
323
+ fieldnames = ["block_index", "line_count", "char_count", "contains_code_term", "first_line"]
324
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
325
+ writer.writeheader()
326
+ for index, block in enumerate(code_blocks, start=1):
327
+ lines = [line for line in block.splitlines() if line.strip()]
328
+ contains = any(term and term in block.lower() for term in code_terms)
329
+ writer.writerow({
330
+ "block_index": index,
331
+ "line_count": len(lines),
332
+ "char_count": len(block),
333
+ "contains_code_term": "true" if contains else "false",
334
+ "first_line": lines[0][:200] if lines else "",
335
+ })
336
+
337
+ keyword_total = sum(int(row["count"]) for row in term_rows)
338
+ required_found = sum(1 for row in term_rows if row["category"] == "required" and int(row["count"]) > 0)
339
+ top_keyword = None
340
+ if term_rows:
341
+ top = max(term_rows, key=lambda row: (int(row["count"]), str(row["term"]).lower()))
342
+ top_keyword = str(top["term"]) if int(top["count"]) > 0 else None
343
+ summary = {
344
+ "software_name": str(spec.get("software_name") or ""),
345
+ "source_file": source_file,
346
+ "window_count": len(window_rows),
347
+ "heading_count": len(headings),
348
+ "code_block_count": len(code_blocks),
349
+ "keyword_total": keyword_total,
350
+ "unique_required_terms_found": required_found,
351
+ "top_keyword": top_keyword,
352
+ "source_character_count": len(clean_text),
353
+ }
354
+ _write_json(output_dir / "summary.json", summary)
355
+
356
+
357
+ def geojson_outputs(input_dir: Path, output_dir: Path) -> None:
358
+ payload = _read_json(input_dir / "events.geojson")
359
+ features = payload.get("features") if isinstance(payload, dict) else []
360
+ rows: list[dict[str, Any]] = []
361
+ for feature in features:
362
+ if not isinstance(feature, dict):
363
+ continue
364
+ props = feature.get("properties") if isinstance(feature.get("properties"), dict) else {}
365
+ geom = feature.get("geometry") if isinstance(feature.get("geometry"), dict) else {}
366
+ coords = geom.get("coordinates") if isinstance(geom.get("coordinates"), list) else []
367
+ mag = props.get("mag")
368
+ try:
369
+ mag = float(mag) if mag is not None else None
370
+ except (TypeError, ValueError):
371
+ mag = None
372
+ depth = None
373
+ if len(coords) >= 3:
374
+ try:
375
+ depth = float(coords[2])
376
+ except (TypeError, ValueError):
377
+ depth = None
378
+ time_ms = props.get("time")
379
+ date_utc = "unknown"
380
+ if isinstance(time_ms, (int, float)):
381
+ date_utc = dt.datetime.utcfromtimestamp(time_ms / 1000).date().isoformat()
382
+ rows.append({
383
+ "id": feature.get("id") or props.get("code") or "",
384
+ "mag": mag,
385
+ "depth": depth,
386
+ "place": str(props.get("place") or ""),
387
+ "region": _stable_region(str(props.get("place") or "")),
388
+ "date_utc": date_utc,
389
+ "feature": feature,
390
+ })
391
+ output_dir.mkdir(parents=True, exist_ok=True)
392
+ mags = [row["mag"] for row in rows if row["mag"] is not None]
393
+ depths = [row["depth"] for row in rows if row["depth"] is not None]
394
+ summary = {
395
+ "event_count": len(rows),
396
+ "magnitude": {
397
+ "count": len(mags),
398
+ "min": round(min(mags), 6) if mags else None,
399
+ "max": round(max(mags), 6) if mags else None,
400
+ "mean": round(statistics.fmean(mags), 6) if mags else None,
401
+ "median": round(statistics.median(mags), 6) if mags else None,
402
+ },
403
+ "depth_km": {
404
+ "count": len(depths),
405
+ "min": round(min(depths), 6) if depths else None,
406
+ "max": round(max(depths), 6) if depths else None,
407
+ "mean": round(statistics.fmean(depths), 6) if depths else None,
408
+ },
409
+ "time_range_utc": {
410
+ "start_date": min((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None),
411
+ "end_date": max((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None),
412
+ },
413
+ "quality_flags": {
414
+ "missing_magnitude": sum(1 for row in rows if row["mag"] is None),
415
+ "missing_depth": sum(1 for row in rows if row["depth"] is None),
416
+ "unique_regions": len({row["region"] for row in rows}),
417
+ },
418
+ }
419
+ _write_json(output_dir / "summary.json", summary)
420
+
421
+ grouped: dict[tuple[str, str], list[dict[str, Any]]] = {}
422
+ for row in rows:
423
+ grouped.setdefault((_mag_bin(row["mag"]), _depth_bin(row["depth"])), []).append(row)
424
+ with (output_dir / "magnitude_depth_bins.csv").open("w", encoding="utf-8", newline="") as handle:
425
+ fieldnames = ["mag_bin", "depth_bin", "event_count", "mean_magnitude", "max_magnitude"]
426
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
427
+ writer.writeheader()
428
+ for (mag_bin, depth_bin), group in sorted(grouped.items()):
429
+ group_mags = [row["mag"] for row in group if row["mag"] is not None]
430
+ writer.writerow({
431
+ "mag_bin": mag_bin,
432
+ "depth_bin": depth_bin,
433
+ "event_count": len(group),
434
+ "mean_magnitude": f"{statistics.fmean(group_mags):.6f}" if group_mags else "",
435
+ "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "",
436
+ })
437
+
438
+ daily: dict[tuple[str, str], list[dict[str, Any]]] = {}
439
+ for row in rows:
440
+ daily.setdefault((row["region"], row["date_utc"]), []).append(row)
441
+ with (output_dir / "region_daily_counts.csv").open("w", encoding="utf-8", newline="") as handle:
442
+ fieldnames = ["region", "date_utc", "event_count", "max_magnitude"]
443
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
444
+ writer.writeheader()
445
+ for (region, date_utc), group in sorted(daily.items()):
446
+ group_mags = [row["mag"] for row in group if row["mag"] is not None]
447
+ writer.writerow({
448
+ "region": region,
449
+ "date_utc": date_utc,
450
+ "event_count": len(group),
451
+ "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "",
452
+ })
453
+
454
+ filtered = [row["feature"] for row in rows if row["mag"] is not None and row["mag"] >= 4.5]
455
+ _write_json(output_dir / "filtered_events.geojson", {"type": "FeatureCollection", "features": filtered})
456
+
457
+
458
+ def csv_time_series_outputs(input_dir: Path, output_dir: Path) -> None:
459
+ spec = _read_json(input_dir / "analysis_spec.json")
460
+ csv_name = spec["input_file"]
461
+ date_column = spec["date_column"]
462
+ value_column = spec["value_column"]
463
+ rows: list[dict[str, Any]] = []
464
+ with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle:
465
+ lines = [line for line in raw_handle if not line.lstrip().startswith("#")]
466
+ reader = csv.DictReader(lines)
467
+ for item in reader:
468
+ raw_date = item.get(date_column, "")
469
+ try:
470
+ day = dt.date.fromisoformat(raw_date)
471
+ except ValueError:
472
+ if raw_date.isdigit() and len(raw_date) == 4:
473
+ day = dt.date(int(raw_date), 1, 1)
474
+ else:
475
+ continue
476
+ raw_value = item.get(value_column, "")
477
+ try:
478
+ value = float(raw_value)
479
+ except (TypeError, ValueError):
480
+ value = None
481
+ rows.append({"date": day, "value": value, "raw": item})
482
+ rows.sort(key=lambda item: item["date"])
483
+ valid = [row for row in rows if row["value"] is not None]
484
+ output_dir.mkdir(parents=True, exist_ok=True)
485
+ monthly: dict[str, list[float]] = {}
486
+ for row in valid:
487
+ key = row["date"].strftime("%Y-%m")
488
+ monthly.setdefault(key, []).append(row["value"])
489
+ with (output_dir / "monthly_statistics.csv").open("w", encoding="utf-8", newline="") as handle:
490
+ fieldnames = ["month", "count", "mean", "median", "min", "max"]
491
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
492
+ writer.writeheader()
493
+ for month, values in sorted(monthly.items()):
494
+ writer.writerow({
495
+ "month": month,
496
+ "count": len(values),
497
+ "mean": f"{statistics.fmean(values):.6f}",
498
+ "median": f"{statistics.median(values):.6f}",
499
+ "min": f"{min(values):.6f}",
500
+ "max": f"{max(values):.6f}",
501
+ })
502
+ existing_dates = {row["date"] for row in rows}
503
+ missing_days: list[dt.date] = []
504
+ if rows:
505
+ day = rows[0]["date"]
506
+ while day <= rows[-1]["date"]:
507
+ if day.weekday() < 5 and day not in existing_dates:
508
+ missing_days.append(day)
509
+ day += dt.timedelta(days=1)
510
+ with (output_dir / "missing_business_days.csv").open("w", encoding="utf-8", newline="") as handle:
511
+ writer = csv.DictWriter(handle, fieldnames=["date"])
512
+ writer.writeheader()
513
+ for day in missing_days:
514
+ writer.writerow({"date": day.isoformat()})
515
+ with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle:
516
+ writer = csv.DictWriter(handle, fieldnames=["date", "value"])
517
+ writer.writeheader()
518
+ for row in valid:
519
+ writer.writerow({"date": row["date"].isoformat(), "value": f"{row['value']:.6f}"})
520
+ values = [row["value"] for row in valid]
521
+ summary = {
522
+ "series_name": spec.get("series_name", value_column),
523
+ "row_count": len(rows),
524
+ "valid_value_count": len(valid),
525
+ "missing_value_count": len(rows) - len(valid),
526
+ "missing_business_day_count": len(missing_days),
527
+ "date_range": {
528
+ "start": rows[0]["date"].isoformat() if rows else None,
529
+ "end": rows[-1]["date"].isoformat() if rows else None,
530
+ },
531
+ "value": {
532
+ "min": round(min(values), 6) if values else None,
533
+ "max": round(max(values), 6) if values else None,
534
+ "mean": round(statistics.fmean(values), 6) if values else None,
535
+ "median": round(statistics.median(values), 6) if values else None,
536
+ },
537
+ }
538
+ _write_json(output_dir / "summary.json", summary)
539
+
540
+
541
+ def _aggregate_annual_rows(rows: list[dict[str, Any]], aggregation: str) -> list[dict[str, Any]]:
542
+ if not aggregation:
543
+ return rows
544
+ grouped: dict[int, list[float]] = {}
545
+ for row in rows:
546
+ grouped.setdefault(int(row["year"]), []).append(float(row["value"]))
547
+ aggregated: list[dict[str, Any]] = []
548
+ for year, values in sorted(grouped.items()):
549
+ if aggregation == "mean":
550
+ value = statistics.fmean(values)
551
+ elif aggregation == "median":
552
+ value = statistics.median(values)
553
+ elif aggregation == "max":
554
+ value = max(values)
555
+ elif aggregation == "min":
556
+ value = min(values)
557
+ elif aggregation == "count":
558
+ value = float(len(values))
559
+ else:
560
+ raise ValueError(f"unsupported year_aggregation for csv_annual_series_audit: {aggregation}")
561
+ aggregated.append({"year": year, "value": value})
562
+ return aggregated
563
+
564
+
565
+ def csv_annual_series_outputs(input_dir: Path, output_dir: Path) -> None:
566
+ spec = _read_json(input_dir / "analysis_spec.json")
567
+ csv_name = spec["input_file"]
568
+ year_column = spec["year_column"]
569
+ value_column = spec["value_column"]
570
+ # Optional: derive the year from an ISO-8601 timestamp column (e.g. USGS FDSN
571
+ # `time` = "2022-06-29T19:17:58.929Z") instead of parsing an integer year.
572
+ # When unset, behaviour is unchanged (integer year column).
573
+ year_from_timestamp = bool(spec.get("year_from_timestamp", False))
574
+ year_aggregation = str(spec.get("year_aggregation") or "").strip().lower()
575
+ raw_rows: list[dict[str, Any]] = []
576
+ with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle:
577
+ lines = [line for line in raw_handle if not line.lstrip().startswith("#")]
578
+ reader = csv.DictReader(lines)
579
+ for item in reader:
580
+ raw_year = str(item.get(year_column, "")).strip()
581
+ try:
582
+ if year_from_timestamp:
583
+ # Take the leading 4-digit year of an ISO timestamp/date.
584
+ match = re.match(r"\s*(\d{4})", raw_year)
585
+ if not match:
586
+ continue
587
+ year = int(match.group(1))
588
+ else:
589
+ year = int(raw_year)
590
+ value = float(str(item.get(value_column, "")).strip())
591
+ except (TypeError, ValueError):
592
+ continue
593
+ raw_rows.append({"year": year, "value": value})
594
+ rows = _aggregate_annual_rows(raw_rows, year_aggregation)
595
+ rows.sort(key=lambda item: item["year"])
596
+ output_dir.mkdir(parents=True, exist_ok=True)
597
+ decades: dict[str, list[float]] = {}
598
+ for row in rows:
599
+ decade_start = (row["year"] // 10) * 10
600
+ decades.setdefault(f"{decade_start}s", []).append(row["value"])
601
+ with (output_dir / "decadal_statistics.csv").open("w", encoding="utf-8", newline="") as handle:
602
+ fieldnames = [
603
+ "decade_start",
604
+ "start_year",
605
+ "end_year",
606
+ "count",
607
+ "mean_departure",
608
+ "median_departure",
609
+ "min_departure",
610
+ "max_departure",
611
+ "sample_std_departure",
612
+ ]
613
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
614
+ writer.writeheader()
615
+ for decade, values in sorted(decades.items()):
616
+ decade_start = int(decade.rstrip("s"))
617
+ years = [row["year"] for row in rows if decade_start <= row["year"] <= decade_start + 9]
618
+ writer.writerow({
619
+ "decade_start": decade_start,
620
+ "start_year": min(years),
621
+ "end_year": max(years),
622
+ "count": len(values),
623
+ "mean_departure": f"{statistics.fmean(values):.6f}",
624
+ "median_departure": f"{statistics.median(values):.6f}",
625
+ "min_departure": f"{min(values):.6f}",
626
+ "max_departure": f"{max(values):.6f}",
627
+ "sample_std_departure": f"{statistics.stdev(values):.6f}" if len(values) >= 2 else "",
628
+ })
629
+ threshold = float(spec.get("threshold", 1.0))
630
+ with (output_dir / "threshold_years.csv").open("w", encoding="utf-8", newline="") as handle:
631
+ fieldnames = ["rank", "year", "departure", "threshold"]
632
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
633
+ writer.writeheader()
634
+ rank = 1
635
+ for row in rows:
636
+ if row["value"] >= threshold:
637
+ writer.writerow({
638
+ "rank": rank,
639
+ "year": row["year"],
640
+ "departure": f"{row['value']:.6f}",
641
+ "threshold": f"{threshold:.6f}",
642
+ })
643
+ rank += 1
644
+ with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle:
645
+ writer = csv.DictWriter(handle, fieldnames=["Year", "Departure from Average"])
646
+ writer.writeheader()
647
+ for row in rows:
648
+ writer.writerow({"Year": row["year"], "Departure from Average": f"{row['value']:.6f}"})
649
+ values = [row["value"] for row in rows]
650
+ threshold_rows = [row for row in rows if row["value"] >= threshold]
651
+ min_row = min(rows, key=lambda row: row["value"]) if rows else None
652
+ max_row = max(rows, key=lambda row: row["value"]) if rows else None
653
+ summary = {
654
+ "series_name": spec.get("series_name", value_column),
655
+ "row_count": len(rows),
656
+ "year_range": {
657
+ "start": rows[0]["year"] if rows else None,
658
+ "end": rows[-1]["year"] if rows else None,
659
+ },
660
+ "value": {
661
+ "min": round(min(values), 6) if values else None,
662
+ "min_year": min_row["year"] if min_row else None,
663
+ "max": round(max(values), 6) if values else None,
664
+ "max_year": max_row["year"] if max_row else None,
665
+ "mean": round(statistics.fmean(values), 6) if values else None,
666
+ "median": round(statistics.median(values), 6) if values else None,
667
+ "sample_std": round(statistics.stdev(values), 6) if len(values) >= 2 else None,
668
+ },
669
+ "threshold": threshold,
670
+ "years_at_or_above_threshold": len(threshold_rows),
671
+ "first_threshold_year": threshold_rows[0]["year"] if threshold_rows else None,
672
+ "last_threshold_year": threshold_rows[-1]["year"] if threshold_rows else None,
673
+ }
674
+ if year_aggregation:
675
+ summary["year_aggregation"] = year_aggregation
676
+ summary["source_row_count"] = len(raw_rows)
677
+ _write_json(output_dir / "summary.json", summary)
678
+
679
+
20260907-002634-transport-safety-6f2c6a/tests/reference/internal/workflow_runtime.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from workflow_adapters_runtime import software_tutorial_outputs
3
+
4
+ def run_reference(input_dir: Path, output_dir: Path) -> None:
5
+ software_tutorial_outputs(input_dir, output_dir)
20260907-002634-transport-safety-6f2c6a/tests/reference/reference_manifest.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "workflow_kind": "software_tutorial_doc_audit",
3
+ "task_id": "repair3_20260907_087_repair2_20260906_093_repair_20260906_software_0110",
4
+ "domain": "transport_safety",
5
+ "task": "sumo_plainxml_document_audit",
6
+ "variant": "base",
7
+ "created_from": "standard reference workflow",
8
+ "required_outputs": [
9
+ {
10
+ "path": "summary.json",
11
+ "type": "json"
12
+ },
13
+ {
14
+ "path": "section_outline.csv",
15
+ "type": "csv"
16
+ },
17
+ {
18
+ "path": "keyword_inventory.csv",
19
+ "type": "csv"
20
+ },
21
+ {
22
+ "path": "code_block_inventory.csv",
23
+ "type": "csv"
24
+ }
25
+ ],
26
+ "numeric_tolerance": 1e-09,
27
+ "source_prior_sha256": "e338ca2c987a612024504d976fa1bc9c500c8779e986043eca1a870f6ef9a2a0",
28
+ "gold_output_hashes": {
29
+ "summary.json": "ad19c14767717b9d4629e558fa65a06fcca1a98bfac9c9fed0fe8da6e5c7327a",
30
+ "section_outline.csv": "2e5418f96aca2bcb5a3ea72bbbcddf959a0be5efa9736f865052f0bd46ba61ec",
31
+ "keyword_inventory.csv": "dcaa39e02418fd64be64cc0ce2f308e83ee27824e59c72316430cdfac6987379",
32
+ "code_block_inventory.csv": "db7636954eb57d7e16189292f25bcc9caa12bb176037d4734554f5193cfa807f"
33
+ }
34
+ }
20260907-002634-transport-safety-6f2c6a/tests/reference/reference_solution.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+
8
+ def main() -> int:
9
+ parser = argparse.ArgumentParser()
10
+ parser.add_argument("--input", required=True)
11
+ parser.add_argument("--output", required=True)
12
+ args = parser.parse_args()
13
+ sys.path.insert(0, str(Path(__file__).resolve().parent / "internal"))
14
+ from workflow_runtime import run_reference
15
+ run_reference(Path(args.input), Path(args.output))
16
+ return 0
17
+
18
+
19
+ if __name__ == "__main__":
20
+ raise SystemExit(main())
20260907-002634-transport-safety-6f2c6a/tests/test.sh ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u
3
+
4
+ TESTS_DIR="${HARBOR_TESTS_DIR:-/tests}"
5
+ WORKSPACE_DIR="${HARBOR_WORKSPACE_DIR:-/workspace}"
6
+ LOGS_DIR="${HARBOR_LOGS_DIR:-/logs/verifier}"
7
+
8
+ mkdir -p "${LOGS_DIR}" "${WORKSPACE_DIR}/output"
9
+
10
+ python "${TESTS_DIR}/evaluator_runner.py" \
11
+ --output-dir "${WORKSPACE_DIR}/output" \
12
+ --reference-dir "${TESTS_DIR}/reference" \
13
+ --reward-json "${LOGS_DIR}/reward.json" \
14
+ --details-json "${LOGS_DIR}/ale_evaluator_details.json"
15
+
16
+ if [ ! -f "${LOGS_DIR}/reward.json" ]; then
17
+ echo '{"score":0.0,"format":0.0,"output_present":0.0,"evaluator_available":0.0,"item_count":0.0}' > "${LOGS_DIR}/reward.json"
18
+ fi
19
+
20
+ python - <<'PY' "${LOGS_DIR}/reward.json" "${LOGS_DIR}/reward.txt"
21
+ import json
22
+ import sys
23
+ from pathlib import Path
24
+ reward = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
25
+ score = float(reward.get("score", 0.0))
26
+ Path(sys.argv[2]).write_text(f"{score}\n", encoding="utf-8")
27
+ PY
28
+
29
+ exit 0
20260907-002650-transport-safety-0ac894/.DS_Store ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:99db9dc5f3ad356ceb54cf28f45f3471fbd12d7c661084975a3120b9e928f425
3
+ size 6148
20260907-002650-transport-safety-0ac894/environment/Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ WORKDIR /workspace
4
+
5
+ COPY public_data/input /workspace/input
6
+ COPY public_data/software /workspace/software
7
+ COPY public_data/task_card.json /workspace/task_card.json
8
+ COPY public_data/main.py /workspace/main.py
9
+ COPY public_data/README.md /workspace/README.md
10
+
11
+ RUN mkdir -p /workspace/output /workspace/report /logs/agent /logs/artifacts \
12
+ && chmod -R 777 /workspace/output /workspace/report /logs
20260907-002650-transport-safety-0ac894/environment/public_data/README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Public Task Inputs
2
+
3
+ Files in this directory are copied into the workspace:
4
+
5
+ - `input/` -> `/workspace/input/`
6
+ - `software/` -> `/workspace/software/`
7
+ - `task_card.json` -> `/workspace/task_card.json`
8
+ - `main.py` -> `/workspace/main.py`
9
+
10
+ Hidden reference data and evaluator files are not present in the agent workspace.
11
+ Final deliverables must be written under `/workspace/output/`.
20260907-002650-transport-safety-0ac894/environment/public_data/input/README.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ This directory contains the public staged input for this task.
2
+ input/analysis_spec.json is the authoritative public contract for input columns, grouping/filtering rules, required output files, and output schemas.
3
+ Primary data file: input/tutorial_text_windows.csv.
4
+ Workflow kind: software_tutorial_doc_audit.
5
+ Required output files: output/summary.json, output/section_outline.csv, output/keyword_inventory.csv, output/code_block_inventory.csv.
6
+ Solve the task from the staged local files only; do not fetch fresh remote data during solve time.
20260907-002650-transport-safety-0ac894/environment/public_data/input/analysis_spec.json ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "input_file": "tutorial_text_windows.csv",
3
+ "source_file": "tutorial_source.html",
4
+ "workflow_kind": "software_tutorial_doc_audit",
5
+ "software_name": "SUMO",
6
+ "tutorial_url": "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md",
7
+ "source_urls": [
8
+ "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md"
9
+ ],
10
+ "window_rule": {
11
+ "cleaning": "Strip HTML/script/style tags, decode entities, collapse whitespace, and preserve document text order.",
12
+ "window_size_words": 40,
13
+ "stride_words": 20,
14
+ "minimum_windows": 100
15
+ },
16
+ "heading_rule": "Extract h1-h6 headings from HTML; if no HTML headings are present, use Markdown # headings.",
17
+ "keyword_rule": "Count case-insensitive occurrences of required_terms and code_terms in the cleaned tutorial text.",
18
+ "required_terms": [
19
+ "network",
20
+ "route",
21
+ "edge",
22
+ "node",
23
+ "vehicle"
24
+ ],
25
+ "code_terms": [
26
+ "duarouter",
27
+ "netedit",
28
+ ".net.xml",
29
+ ".rou.xml"
30
+ ],
31
+ "executables": [
32
+ "sumo",
33
+ "netconvert",
34
+ "duarouter",
35
+ "netedit"
36
+ ],
37
+ "required_system_packages": [
38
+ "sumo",
39
+ "sumo-tools"
40
+ ],
41
+ "required_outputs": [
42
+ {
43
+ "path": "summary.json",
44
+ "type": "json"
45
+ },
46
+ {
47
+ "path": "section_outline.csv",
48
+ "type": "csv"
49
+ },
50
+ {
51
+ "path": "keyword_inventory.csv",
52
+ "type": "csv"
53
+ },
54
+ {
55
+ "path": "code_block_inventory.csv",
56
+ "type": "csv"
57
+ }
58
+ ],
59
+ "output_schemas": {
60
+ "summary.json": {
61
+ "software_name": "string",
62
+ "source_file": "string",
63
+ "window_count": "integer",
64
+ "heading_count": "integer",
65
+ "code_block_count": "integer",
66
+ "keyword_total": "integer",
67
+ "unique_required_terms_found": "integer",
68
+ "top_keyword": "string|null",
69
+ "source_character_count": "integer"
70
+ },
71
+ "section_outline.csv": [
72
+ "rank",
73
+ "heading_level",
74
+ "heading_text",
75
+ "slug"
76
+ ],
77
+ "keyword_inventory.csv": [
78
+ "term",
79
+ "category",
80
+ "count",
81
+ "first_window",
82
+ "appears_in_code"
83
+ ],
84
+ "code_block_inventory.csv": [
85
+ "block_index",
86
+ "line_count",
87
+ "char_count",
88
+ "contains_code_term",
89
+ "first_line"
90
+ ]
91
+ },
92
+ "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."
93
+ }
20260907-002650-transport-safety-0ac894/environment/public_data/input/source_context_windows.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_metadata.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "software_name": "SUMO",
3
+ "tutorial_url": "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md",
4
+ "source_urls": [
5
+ "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md"
6
+ ],
7
+ "source_file": "tutorial_source.html",
8
+ "window_file": "tutorial_text_windows.csv",
9
+ "window_rule": {
10
+ "cleaning": "Strip HTML/script/style tags, decode entities, collapse whitespace, and preserve document text order.",
11
+ "window_size_words": 40,
12
+ "stride_words": 20,
13
+ "minimum_windows": 100
14
+ },
15
+ "required_terms": [
16
+ "network",
17
+ "route",
18
+ "edge",
19
+ "node",
20
+ "vehicle"
21
+ ],
22
+ "code_terms": [
23
+ "duarouter",
24
+ "netedit",
25
+ ".net.xml",
26
+ ".rou.xml"
27
+ ],
28
+ "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here."
29
+ }
20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_source.html ADDED
@@ -0,0 +1,1215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Source 1: PlainXML.md
2
+
3
+ - URL: https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md
4
+ - SHA256: afd8cecb140607cd783cd8efe6a610b521df3c8c4762047f07b7044c4080599d
5
+ - Bytes: 78218
6
+
7
+ ```markdown
8
+ ---
9
+ title: PlainXML
10
+ ---
11
+
12
+ **SUMO**-Networks have two representations:
13
+
14
+ - A set of *plain-xml* files which describe the network topology and
15
+ geometry
16
+ - The *.net.xml* file which is loaded into the simulation. This
17
+ contains lots of generated information such as structures within an
18
+ intersection and right-of-way logic.
19
+
20
+ [netconvert](../netconvert.md) can [convert freely](../Networks/Export.md#plain) and without information loss
21
+ between these two formats. Only the *plain-xml* format is meant to be
22
+ edited by the users. In contrast, the *.net.xml* format has lots of
23
+ subtle inter-dependencies between its elements and should never be
24
+ edited by hand. The *plain-xml* format is described below.
25
+
26
+ It is possible to load a *net.xml* file along with *plain-xml* patch
27
+ files into [netconvert](../netconvert.md) to modify some aspects of
28
+ an existing network.
29
+
30
+ To defined a network at least two files are needed: one file for nodes
31
+ and another one for the streets between them. Please notice that herein,
32
+ "node" and "junction" mean the same as well as "edge" and "street" do
33
+ (see also [Glossary](../Other/Glossary.md)). Besides defining the
34
+ nodes and edges, you can also join edge attributes by type and set
35
+ explicit connections between edges or lanes. We will describe how each
36
+ of these four file types should look like in the following chapters.
37
+ Further information on road networks may be also found in the [SUMO Road Networks](../Networks/SUMO_Road_Networks.md) description.
38
+
39
+ After you have generated the files as described below - you need at
40
+ least the edges and the nodes-files, using type and/or a connections
41
+ file is optional - you should run [netconvert](../netconvert.md) to
42
+ build the network. If you only use edges and nodes, stored in
43
+ "MyEdges.edg.xml" and "MyNodes.nod.xml" respectively, the call should
44
+ look like:
45
+
46
+ ```
47
+ netconvert --node-files=MyNodes.nod.xml --edge-files=MyEdges.edg.xml \
48
+ --output-file=MySUMONet.net.xml
49
+ ```
50
+
51
+ If you also use connections and types the call is:
52
+
53
+ ```
54
+ netconvert --node-files=MyNodes.nod.xml --edge-files=MyEdges.edg.xml \
55
+ --connection-files=MyConnections.con.xml --type-files=MyTypes.typ.xml \
56
+ --output-file=MySUMONet.net.xml
57
+ ```
58
+
59
+ The options used here, including their abbreviations, are documented on
60
+ the [netconvert manual page](../netconvert.md#input).
61
+
62
+ Maybe your edge definitions are incomplete or buggy. If you still want
63
+ to import your network, you can try passing **--ignore-errors** to
64
+ [netconvert](../netconvert.md). In this case, edges which are not
65
+ defined properly are omitted, but [netconvert](../netconvert.md)
66
+ tries to build the network anyway. You may also flip the network around
67
+ the horizontal axis. Use option **--flip-y-axis** for this.
68
+
69
+ The structures of the files described in the following are also
70
+ available as XML Schema Definitions:
71
+
72
+ - [nodes files](#node_descriptions):
73
+ <https://sumo.dlr.de/xsd/nodes_file.xsd>
74
+ - [edges files](#edge_descriptions):
75
+ <https://sumo.dlr.de/xsd/edges_file.xsd>
76
+ - [types files](#type_descriptions):
77
+ <https://sumo.dlr.de/xsd/types_file.xsd>
78
+ - [connections files](#connection_descriptions):
79
+ <https://sumo.dlr.de/xsd/connections_file.xsd>
80
+ - [tllogic files](#traffic_light_program_definition):
81
+ <https://sumo.dlr.de/xsd/tllogic_file.xsd>
82
+
83
+ # Node Descriptions
84
+
85
+ | Node Descriptions | |
86
+ |--------------------|---------------------------------|
87
+ | Filename extension | .nod.xml |
88
+ | Type of content | Nodes (intersections/junctions) |
89
+ | Open format? | Yes |
90
+ | SUMO specific? | Yes |
91
+ | XML Schema | [nodes_file.xsd](https://sumo.dlr.de/xsd/nodes_file.xsd) |
92
+
93
+ Within the nodes-files, normally having the extension ".nod.xml" (see
94
+ [Known Extensions](../Other/File_Extensions.md)), every node is
95
+ described in a single line which looks like this:
96
+
97
+ ```xml
98
+ <node id="<STRING>" x="<FLOAT>" y="<FLOAT>" [type="<TYPE>"]/>
99
+ ```
100
+
101
+ the straight brackets ('\[' and '\]')
102
+ indicate that the parameter is optional. Each of these attributes has a
103
+ certain meaning and value range:
104
+
105
+ | Attribute Name | Value Type | Description |
106
+ | --------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
107
+ | **id** | id (string) | The name of the node |
108
+ | **x** | float | The x-position of the node on the plane in meters |
109
+ | **y** | float | The y-position of the node on the plane in meters |
110
+ | z | float | The z-position of the node on the plane in meters |
111
+ | 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 |
112
+ | tlType | enum ( **"static"**, "actuated", "delay_based") | An optional type for the [traffic light algorithm](../Simulation/Traffic_Lights.md#type_actuated)
113
+ | tlLayout | enum ( **"opposites"**, "incoming", "alternateOneWay") | An optional layout for the traffic light plan (see below)
114
+ | tl | id (string) | An optional id for the traffic light program. Nodes with the same tl-value will be joined into a single program |
115
+ | radius | positive float | optional turning radius (for all corners) for that node in meters *(default 1.5)* |
116
+ | 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. |
117
+ | keepClear | bool | Whether the [junction-blocking-heuristic](../Simulation/Intersections.md#junction_blocking) should be activated at this node *(default true)* |
118
+ | rightOfWay | string | Set algorithm for computing [\#Right-of-way](#right-of-way). Allowed values are *default*, *edgePriority*, *mixedPriority*, and *allwayStop* |
119
+ | fringe | string | Clarify whether this junction is on the [network fringe](#fringe). Allowed values are *default*, *outer* and *inner* |
120
+ | roundabout | string | Clarify whether this junction may be part of a roundabout. Allowed values are *default*, *1* and *0* |
121
+ | 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 |
122
+
123
+ !!! note
124
+ 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.
125
+
126
+ When writing your nodes-file, please do not forget to embed your node
127
+ definitions into an opening and a closing "tag". A complete file should
128
+ like the example below, which is the node file "cross3l.nod.xml" for the
129
+ examples "{{SUMO}}/data/examples/netbuild/types/cross_usingtypes/" and
130
+ "{{SUMO}}/data/examples/netbuild/types/cross_notypes/" example.
131
+
132
+ ```xml
133
+ <nodes> <!-- The opening tag -->
134
+
135
+ <node id="0" x="0.0" y="0.0" type="traffic_light"/> <!-- def. of node "0" -->
136
+
137
+ <node id="1" x="-500.0" y="0.0" type="priority"/> <!-- def. of node "1" -->
138
+ <node id="2" x="+500.0" y="0.0" type="priority"/> <!-- def. of node "2" -->
139
+ <node id="3" x="0.0" y="-500.0" type="priority"/> <!-- def. of node "3" -->
140
+ <node id="4" x="0.0" y="+500.0" type="priority"/> <!-- def. of node "4" -->
141
+
142
+ <node id="m1" x="-250.0" y="0.0" type="priority"/> <!-- def. of node "m1" -->
143
+ <node id="m2" x="+250.0" y="0.0" type="priority"/> <!-- def. of node "m2" -->
144
+ <node id="m3" x="0.0" y="-250.0" type="priority"/> <!-- def. of node "m3" -->
145
+ <node id="m4" x="0.0" y="+250.0" type="priority"/> <!-- def. of node "m4" -->
146
+
147
+ </nodes> <!-- The closing tag -->
148
+ ```
149
+
150
+ As you may notice, only the first node named "0", which is the node in
151
+ the middle of the network, is a traffic light controlled junction. All
152
+ other nodes are uncontrolled. You may also notice, that each of both
153
+ ends of a street needs an according node. This is not really necessary
154
+ as you may see soon, but it eases the understanding of the concept:
155
+ every edge (street/road) is a connection between two nodes (junctions).
156
+
157
+ ## Traffic lights
158
+ For traffic light nodes, [netconvert](../netconvert.md) generates a
159
+ default traffic light program. The simulation can [load additional programs](../Simulation/Traffic_Lights.md) which may be used
160
+ instead.
161
+
162
+ ### tlType
163
+ If you leave out the tlType of the node, it is set to *static*. This
164
+ default may be changed using the option **--tls.default-type** {{DT_STR}}.
165
+
166
+ - `static`: Each phase of the traffic light
167
+ will last for a fixed duration
168
+ - `actuated`: Green phases may be prolonged
169
+ depending on traffic measurements from automatically added induction
170
+ loops ("*Zeitlückensteuerung*")
171
+
172
+ !!! note
173
+ 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.
174
+
175
+ ### tlLayout
176
+ If you leave out the tlLayout of the node, it is set to *opposites*. This
177
+ default may be changed using the option **--tls.layout** {{DT_STR}}
178
+
179
+ - `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.
180
+ - `incoming`: each incoming road gets its own green phase
181
+ - `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.
182
+
183
+ ## Node types
184
+
185
+ If you leave out the type of the node, it is automatically guessed by
186
+ [netconvert](../netconvert.md) but may not be the one you intended.
187
+ The following types are possible, any other string is counted as an
188
+ error and will yield in a program stop:
189
+
190
+ - `priority`: Vehicles on a low-priority
191
+ edge have to wait until vehicles on a high-priority edge have passed
192
+ the junction.
193
+ - `traffic_light`: The junction is
194
+ controlled by a traffic light (priority rules are used to avoid
195
+ collisions if conflicting links have green light at the same time).
196
+ - `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).
197
+ - `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).
198
+ - `unregulated`: The junction is completely
199
+ unregulated - all vehicles may pass without braking; Collision
200
+ detection on the intersection is disabled but collisions beyond the
201
+ intersection will be detected and are likely to occur.
202
+ - `traffic_light_unregulated`: The
203
+ junction is controlled by a traffic light without any further rules.
204
+ This may cause collision if unsafe signal plans are used. Note, that
205
+ collisions within the intersection will never be detected.
206
+ - `priority_stop`: This works like a
207
+ *priority*-junction but vehicles on minor links always have to stop
208
+ before passing.
209
+ - `allway_stop`: This junction works like
210
+ an [*All-way stop*](https://en.wikipedia.org/wiki/All-way_stop).
211
+ - `rail_signal`: This junction is
212
+ controlled by a [rail signal](../Simulation/Railways.md#rail_signals).
213
+ This type of junction/control is only useful for rails.
214
+ - `zipper`: This junction connects edges
215
+ where the number of lanes decreases and traffic needs to merge
216
+ [zipper-style (late merging)](https://en.wikipedia.org/wiki/Merge_%28traffic%29).
217
+ - `rail_crossing`: This junction models a
218
+ rail road crossing. It will allow trains to pass unimpeded and will
219
+ restrict vehicles via traffic signals when a train is approaching.
220
+ - `traffic_light_right_on_red`: The
221
+ junction is controlled by a traffic light as for type
222
+ *traffic_light*. Additionally, right-turning vehicles may drive in
223
+ any phase whenever it is safe to do so (after stopping once). This
224
+ behavior is known as
225
+ [right-turn-on-red](https://en.wikipedia.org/wiki/Right_turn_on_red).
226
+ - `dead_end`: There are no connections at this node. This type is assigned automatically. Using this as input will trigger guessing the type.
227
+
228
+ ## Right-of-way
229
+
230
+ The right-of-way computation at each intersection is based on the `type` of
231
+ the node. For the types *priority* and *priority_stop*, the
232
+ right-of-way also depends on the `importance` of the incoming and outgoing
233
+ edges as explained in the following. Generally, the traffic direction
234
+ with the edges of highest importance will get the right of way.
235
+
236
+ !!! note
237
+ Right-of-way computation also influences connection-guessing and the generated traffic light program.
238
+
239
+ ### rightOfWay="default"
240
+ This mode is the default and it is useful if the *priority*
241
+ attribute of the edges cannot be relied on to determine right-of-way all
242
+ by itself. It sorts edges according to attributes *priority*, *speed* and
243
+ *laneNumber*. The two incoming edges with the highest position are
244
+ determined and will receive right-of-way. All other edges will be
245
+ classified as minor.
246
+
247
+ ### rightOfWay="mixedPriority"
248
+ This behaves like "default".
249
+ Setting this value is only useful when configuring the switched-off behavior of
250
+ intersections controlled by traffic lights of type [NEMA](../Simulation/NEMA.md).
251
+ In this case it corresponds to main roads having priority (yellow blinking) and side roads having to stop (red blinking).
252
+
253
+ ### rightOfWay="edgePriority"
254
+ This mode is useful for customizing
255
+ right-of-way by tuning edge *priority* attributes. The relationship
256
+ between streams of different incoming-edge priority will be solely
257
+ determined by edge priority. For equal-priority values, turning
258
+ directions are also evaluated.
259
+
260
+ ### rightOfWay="allwayStop"
261
+ 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).
262
+ When this mode is used, the junction will behave like [type](#node_types) `allway_stop` in the 'off' state.
263
+ This is used as the default for nodes controlled by traffic lights of type [NEMA](../Simulation/NEMA.md).
264
+
265
+ ### Special Cases
266
+
267
+ - To model a turning priority road, all incoming and outgoing edges
268
+ that make up this road must have a a higher priority value than the
269
+ non-prioritized road edges.
270
+ - For [roundabouts](#roundabouts), the edges within the
271
+ roundabout always get the right of way over the edges incoming from
272
+ the outside.
273
+ - When [two lanes from the same edge approach the same target lane](#multiple_connections_from_the_same_edge_to_the_same_target_lane),
274
+ the right of way depends on the node type:
275
+ - If the type is *zipper*, then both lanes will react
276
+ symmetrically to each other and vehicles perform [zipper merging](https://en.wikipedia.org/wiki/Merge_%28traffic%29).
277
+ - Otherwise, the left lane will have priority while the right lane
278
+ will yield.
279
+
280
+ ### Understanding right-of-way rules in a Network
281
+
282
+ 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
283
+ *junctions-\>show lane to lane connections*.
284
+
285
+ The right-of-way relationship between any two connections ca be shown in
286
+ [netedit using right-of-way mode](../Netedit/editModesNetwork.md#prohibitions).
287
+
288
+ If a vehicle is braking in the simulation, the responsible foe vehicle
289
+ (if any) can also be [identified directly](../sumo-gui.md#right_of_way).
290
+
291
+ !!! caution
292
+ 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)
293
+
294
+ ### Modifying Right-of-Way
295
+
296
+ The right-of-way can be customized by specifying [additional prohibitions](#setting_connection_priorities) and by
297
+ specifying the [connection attribute](#explicitly_setting_which_edge_lane_is_connected_to_which)
298
+ `pass="true"`.
299
+
300
+ Since version 1.1.0, the algorithm for computing right-of-way from the
301
+ edge priorities can be switched between two modes using `<node>`-attribute
302
+ *rightOfWay*.
303
+
304
+ ## Fringe
305
+
306
+ 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:
307
+
308
+ - default: this junction is not part of the fringe
309
+ - outer: this junction is connected to additional edges in the real world. It is part of the outer boundary of the network
310
+ - 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
311
+
312
+ 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.
313
+
314
+ The 'fringe' attribute is used by [randomTrips.py](../Tools/Trip.md#randomtripspy) when setting option **--fringe-junctions**.
315
+
316
+ ## Joining Nodes
317
+
318
+ Sometimes your network may contain nodes which are very close together
319
+ forming a big cluster. This happens frequently when [Importing Networks from OpenStreetMap](../Networks/Import/OpenStreetMap.md).
320
+ [netconvert](../netconvert.md) supports the option **--junctions.join** to find such
321
+ clusters and join them into a big and well shaped junction. Junctions can also be joined manually with [netedit](../Netedit/index.md#processing_menu_options).
322
+ It is even possible to [undo joins](../Netedit/elementsNetwork.md#junctions) that were computed automatically.
323
+ 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)
324
+ the id will be abbreviated to something like *cluster_id0_id1_id2_id3_#5more* (for a 9 node cluster).
325
+
326
+ ### Reasons for joining node clusters
327
+ Within 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.
328
+ - To prevent jamming cross-traffic, vehicles should only enter an intersection space if they are not prevented from leaving by a downstream jam
329
+ - 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.
330
+
331
+ Further Issues:
332
+ - 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.
333
+ - 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).
334
+ - Automatically generated traffic light plans work much better at a single intersection
335
+
336
+ ### Algorithm for joining node clusters
337
+ You can control the joining algorithm by supplying the option **--junctions.join-dist** {{DT_FLOAT}} which sets a
338
+ search distance for finding clusters *(default 10m)*. The search for
339
+ joinable node clusters works like this:
340
+
341
+ 1. junction shapes are computed for all nodes
342
+ 2. the length of the edges between the junction shapes is compared
343
+ against **join-dist**
344
+ 3. nodes within the given distance are transitively added to a
345
+ candidate cluster
346
+ 4. nodes with only a single connection to the cluster (nodes at the
347
+ outside) are removed
348
+ 5. clusters which are to complex are simplified or filtered out (a warning with an
349
+ explanation is issued for each case)
350
+ - 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).
351
+ 7. each cluster is turned into a joined node
352
+
353
+ ### Specifying and excluding explicit joins
354
+
355
+ More fine grained control over joining can be achieved by using elements `<join>` and `<joinExclude>` within a nodes-file
356
+
357
+ ```xml
358
+ <nodes>
359
+ <join nodes="id0 id23 id24"/>
360
+ <joinExclude nodes="id13 id17"/>
361
+ </nodes>
362
+ ```
363
+
364
+ This will cause the nodes *id0*,*id23* and *id24* to be joined into a
365
+ single junction. It will also prevent the nodes *id13* and *id17* from
366
+ being joined. The **joinExclude**-tag is only useful together with the
367
+ option **--junctions.join** but the **join**-tag can also be used all by itself.
368
+
369
+ Element `<joinExclude>` only supports attribute `nodes` and works in the same way as option **--junctions.join-exclude id,[id\]+**.
370
+ The supported attributes for element `<join>` are described below.
371
+
372
+ | Attribute Name | Value Type | Description |
373
+ | --------------- | ----------------------------------------- | ------------------------------------------------------------------------- |
374
+ | **nodes* | id list (string) | The ids of nodes to join |
375
+ | reset | bool (default: *false*) | Whether all connections at the created node should be re-guessed |
376
+ | <any [node node attriutes](#node_descriptions)> | Sets attributes on the new node (i.e. its `id` or `type`) |
377
+
378
+
379
+ ### Connections after joining nodes
380
+
381
+ The connections at joined junctions depend on the loaded connection definitions and on further attributes and options
382
+
383
+ - 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)
384
+ - if any connections are loaded, they connections at the joined node will be re-created to match the loaded connectivity
385
+ - unless option `<join>`-attribute `reset="true"` or option **--junctions.join-reset** is set in which guess all connections will be guessed again
386
+
387
+ !!! note
388
+ Re-guessing loaded connections is useful when joining junctions while merging networks.
389
+
390
+ # Edge Descriptions
391
+
392
+ | Edge Descriptions | |
393
+ |--------------------|-----------------------|
394
+ | Filename extension | .edg.xml |
395
+ | Type of content | Edges (roads/streets) |
396
+ | Open format? | Yes |
397
+ | SUMO specific? | Yes |
398
+ | XML Schema | [edges_file.xsd](https://sumo.dlr.de/xsd/edges_file.xsd) |
399
+
400
+ Within the edges file, each description of a single edge looks like
401
+ this: `<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>]*"]/>`.
402
+
403
+ The origin and the destination nodes are defined using their IDs
404
+ (`from="<NODE_ID>" to="<NODE_ID>"`). Each
405
+ edge is unidirectional and starts at the
406
+ "`from`"-node and ends at the
407
+ "`to`"-node. If a name of one of the nodes can
408
+ not be dereferenced (because they have not been defined within the nodes
409
+ file) an error is generated. To avoid the stop of further netconversion
410
+ in such cases, you may start [netconvert](../netconvert.md) with
411
+ the option **--ignore-errors**.
412
+
413
+ For each edge, some further attributes should be supplied, being the
414
+ number of lanes the edge has (`numLanes`), the
415
+ maximum speed allowed on the edge `speed`.
416
+ Furthermore, the `priority` may be defined
417
+ optionally.
418
+
419
+ All edge values - beside the length in fact - may either be given for
420
+ each edge using according attributes or you can omit them by giving the
421
+ edge a "`type`". In this case, you should also
422
+ write a [SUMO edge type file](#type_descriptions). A type
423
+ with this name should of course be within the used type file, otherwise
424
+ an error is reported. Even if you supply a type, you can still override
425
+ the type's values by supplying any of the parameter
426
+ `allow`, `disallow`,
427
+ `numLanes`,
428
+ `priority` and
429
+ `speed`. You may also leave the edge parameter
430
+ completely unset. In this case, default-values will be used and the edge
431
+ will have a single lane, a default (unset) priority and the maximum
432
+ allowed speed on this edge will be 13.9m/s being around 50km/h. The
433
+ length of this edge will be computed as the distance between the
434
+ starting and the end point.
435
+
436
+ As an edge may have a more complicated geometry, you may supply the
437
+ edge's shape within the `shape` attribute. If
438
+ the length of the edge is not given otherwise, the distances of the
439
+ shape elements will be summed. The information
440
+ `spreadType="center"` forces
441
+ [netconvert](../netconvert.md) to spread lanes to both sides of the
442
+ connection between the begin node and the end node or from the list of
443
+ lines making up the shape. If not given, lanes are spread to right, as
444
+ default.
445
+
446
+ Let's list an edge's attributes again:
447
+
448
+ | Attribute Name | Value Type | Description |
449
+ | -------------- | ------------------------------------- | -------------------------------------------------------------- |
450
+ | **id** | id (string) | The id of the edge (must be unique) |
451
+ | from | referenced node id | The name of a node within the nodes-file the edge shall start at |
452
+ | to | referenced node id | The name of a node within the nodes-file the edge shall end at |
453
+ | type | referenced type id | The name of a type within the [SUMO edge type file](../SUMO_edge_type_file.md) |
454
+ | numLanes | int | The number of lanes of the edge; must be an integer value |
455
+ | 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") |
456
+ | priority | int | The priority of the edge. Used for [\#Right-of-way](#right-of-way)-computation |
457
+ | length | float | The length of the edge in meter |
458
+ | 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 |
459
+ | spreadType | enum ( "right", "center", "roadCenter") | The description of how to compute lane geometry from edge geometry. See [SpreadType](#spreadtype) |
460
+ | allow | list of vehicle classes | List of permitted vehicle classes (see [access permissions](#road_access_permissions_allow_disallow))|
461
+ | disallow | list of vehicle classes | List of forbidden vehicle classes (see [access permissions](#road_access_permissions_allow_disallow))|
462
+ | width | float | lane width for all lanes of this edge in meters (used for visualization) |
463
+ | name | string | street name (need not be unique, used for visualization) |
464
+ | endOffset | float \>= 0 | Move the stop line back from the intersection by the given amount (effectively shortening the edge and locally enlarging the intersection) |
465
+ | sidewalkWidth | float \>= 0 | Adds a sidewalk with the given width (defaults to -1 which adds nothing). |
466
+ | bikeLaneWidth | float \>= 0 | Adds a bicycle lane with the given width (defaults to -1 which adds nothing). |
467
+ | 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*). |
468
+ | bidi | id | Declares the opposite-direction edge that should form a pair of bidi-edges with this edge |
469
+ | routingType | id | Used together with [preference](../Simulation/Routing.md#routing_by_travel_time_and_routingtype) to set custom edge preferences for routing |
470
+
471
+ The priority plays a role during the computation of the way-giving rules
472
+ of a node. Normally, the allowed speed on the edge and the edge's number
473
+ of lanes are used to compute which edge has a greater priority on a
474
+ junction. Using the priority attribute, you may increase the priority of
475
+ the edge making more lanes yielding in it or making vehicles coming from
476
+ this edge into the junction not wait.
477
+
478
+ Also the definitions of edges must be embedded into an opening and a
479
+ closing tag and for the example
480
+ "{{SUMO}}/data/examples/netbuild/types/cross_notypes/" the whole edges-file
481
+ looks like this ("cross3l.edg.xml"):
482
+
483
+ ```xml
484
+ <edges>
485
+
486
+ <edge id="1fi" from="1" to="m1" priority="2" numLanes="2" speed="11.11"/>
487
+ <edge id="1si" from="m1" to="0" priority="3" numLanes="3" speed="13.89"/>
488
+ <edge id="1o" from="0" to="1" priority="1" numLanes="1" speed="11.11"/>
489
+
490
+ <edge id="2fi" from="2" to="m2" priority="2" numLanes="2" speed="11.11"/>
491
+ <edge id="2si" from="m2" to="0" priority="3" numLanes="3" speed="13.89"/>
492
+ <edge id="2o" from="0" to="2" priority="1" numLanes="1" speed="11.11"/>
493
+
494
+ <edge id="3fi" from="3" to="m3" priority="2" numLanes="2" speed="11.11"/>
495
+ <edge id="3si" from="m3" to="0" priority="3" numLanes="3" speed="13.89"/>
496
+ <edge id="3o" from="0" to="3" priority="1" numLanes="1" speed="11.11"/>
497
+
498
+ <edge id="4fi" from="4" to="m4" priority="2" numLanes="2" speed="11.11"/>
499
+ <edge id="4si" from="m4" to="0" priority="3" numLanes="3" speed="13.89"/>
500
+ <edge id="4o" from="0" to="4" priority="1" numLanes="1" speed="11.11"/>
501
+
502
+ </edges>
503
+ ```
504
+
505
+ Within this example, we have used explicit definitions of edges. An
506
+ example for using types is described in the chapter [Type Descriptions](#type_descriptions).
507
+
508
+ !!! caution
509
+ 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).
510
+
511
+ ## SpreadType
512
+ Each edge has a geometry definition (which defaults to the straight-line between from-junction and to-junction position).
513
+ The spreadType defines how to compute the lane geometry from the edge geometry:
514
+
515
+ - **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.
516
+ - **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
517
+ - **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.
518
+
519
+ ## Road access permissions (allow, disallow)
520
+
521
+ [access permissions](../Simulation/VehiclePermissions.md) are an
522
+ important tool for building multimodal scenarios. Either one of the
523
+ attributes `allow` or `disallow` may be used to configure this according to the following
524
+ semantics:
525
+
526
+ - neither *allow* nor *disallow* given: no access restrictions.
527
+ - *allow* given: Allow only the list of specified vehicle classes
528
+ (i.e. `allow="bus bicycle"` allows only busses and bicycles)
529
+ - *disallow* given: Allow all classes except the list of specified
530
+ ones (i.e. allows everything but pedestrians)
531
+ - the special value *all* may be used to disallow everything (`disallow="all"`) to
532
+ denote green verges or other kinds of spacing between lanes.
533
+
534
+ ## Lane-specific Definitions
535
+
536
+ You may allow/forbid explicit vehicle classes to use a lane. The
537
+ information which vehicle classes are allowed on a lane may be specified
538
+ within an edges descriptions file by embedding the list of lanes
539
+ together with vehicle classes allowed/forbidden on them into these
540
+ edge's lanes. Assume you want to allow only buses to use the leftmost
541
+ lane of edge "2si" from the example above. Simply change this edge's
542
+ definition into:
543
+
544
+ ```xml
545
+ ... previous definitions ...
546
+ <edge id="2si" from="m2" to="0" priority="3" numLanes="3" speed="13.89">
547
+ <lane index="2" allow="bus"/>
548
+ </edge>
549
+ ... further definitions ...
550
+ ```
551
+
552
+ If you would like to disallow passenger cars and taxis, the following
553
+ snippet would do it:
554
+
555
+ ```xml
556
+ ... previous definitions ...
557
+ <edge id="2si" from="m2" to="0" priority="3" numLanes="3" speed="13.89">
558
+ <lane index="2" disallow="passenger taxi"/>
559
+ </edge>
560
+ ... further definitions ...
561
+ ```
562
+
563
+ The definition of a lane contains the following optional attributes:
564
+
565
+ | Attribute Name | Value Type | Description |
566
+ | -------------- | ------------------------------------------------- | ---------------------------------------------------------------------------- |
567
+ | **index** | int | The enumeration index of the lane (0 is the rightmost lane, <NUMBER_LANES\>-1 is the leftmost one) |
568
+ | allow | list of vehicle classes | List of permitted vehicle classes (see [access permissions](#road_access_permissions_allow_disallow)) |
569
+ | disallow | list of vehicle classes | List of forbidden vehicle classes (see [access permissions](#road_access_permissions_allow_disallow)) |
570
+ | changeLeft | list of vehicle classes | List of vehicle classes that may change left from this lane |
571
+ | changeRight | list of vehicle classes | List of vehicle classes that may change right from this lane |
572
+ | speed | float | speed in meters per second |
573
+ | width | float | width in meters (used for visualization) |
574
+ | endOffset | float \>= 0 | Move the stop line back from the intersection by the given amount (effectively shortening the lane and locally enlarging the intersection) |
575
+ | 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.
576
+ | type | string | a custom type description for this lane (only informational) |
577
+ | acceleration | bool | whether this lane is a motorway acceleration lane (default *false*) |
578
+
579
+ See "Vehicle Classes" for further information about [allowed vehicle classes](../Definition_of_Vehicles,_Vehicle_Types,_and_Routes.md#abstract_vehicle_class)
580
+ and their usage.
581
+
582
+ ### lane change restrictions
583
+ When 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.
584
+
585
+ 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).
586
+
587
+ ## Stop Offsets
588
+
589
+ Each edge or lane may carry a `stopOffset` child element to specify an additional
590
+ stopping offset for vehicles of certain classes. This can be used to define a [bike box](https://en.wikipedia.org/wiki/Advanced_stop_line).
591
+
592
+ ```xml
593
+ <edge id="<ID>">
594
+ <stopOffset value="<distance in m.>" vClasses="<space-separated list of vClasses>" />
595
+ <lane id="<ID>" index="<INDEX>" ... >
596
+ <stopOffset value="<distance in m.>" exceptions="<space-separated list of vClasses>" />
597
+ </lane>
598
+ ...
599
+ </edge>
600
+ ```
601
+
602
+ Defining this element for an edge will affect all lanes of the edge that
603
+ do not hold an own `stopOffset` element. Note that there is the possibility to
604
+ define either all vehicle classes, that are affected by the stop offset
605
+ (attribute `vClasses`), or those, which are not affected (attribute `exceptions`). You may not
606
+ use both attributes in conjunction. The distance at which the specified
607
+ vehicle classes are required to stop from the lane end is specified by
608
+ the `value`-attribute.
609
+
610
+ | Name | Type | Description |
611
+ | -------------- | ---------------- | ------------------------------------------------------------------- |
612
+ | **value** | value (double) | The stop offset as positive value in meters. |
613
+ | **vClasses** | list of vClasses | Specifies, for which vehicle classes the stopOffset applies. |
614
+ | **exceptions** | list of vClasses | Specifies, for which vehicle classes the stopOffset does not apply. |
615
+
616
+ For specification of vehicle classes see
617
+ [here](../Definition_of_Vehicles,_Vehicle_Types,_and_Routes.md#abstract_vehicle_class).
618
+
619
+
620
+ ## Road Segment Refining
621
+
622
+ Normally, each edge has a certain number of lanes and a fixed speed;
623
+ road widenings and speed reductions are defined using consequent edges.
624
+ Though, in some cases, it is more comfortable to set up a single edge
625
+ and change the number of its lanes or the speed along its length.
626
+
627
+ This is possible using "split" - a subelement of an XML-edge definition
628
+ after 02.09.2009. A split may be given as following:
629
+
630
+ ```xml
631
+ ... previous definitions ...
632
+ <edge id="2si" from="m2" to="0" priority="3" numLanes="3" speed="13.89">
633
+ <split pos="30" lanes="0 1" speed="10"/>
634
+ </edge>
635
+ ... further definitions ...
636
+ ```
637
+
638
+ What happens here is the following: 30meters from its begin
639
+ (`pos="30"`) the edge is split, inserting a
640
+ node named <EDGE_ID\>.<POSITION\>. Until this node, the edge includes all
641
+ lanes. After this node, only the lanes given in the
642
+ `lanes` attribute are inserted and their speed
643
+ is reduced. This yields in two edges which replace the initial one and
644
+ the second edge contains only two lanes with a maximum speed of 10m/s.
645
+
646
+ The most common usage example is the other way round: lanes must be
647
+ added, not removed along a road. The following snippet shows the by
648
+ example:
649
+
650
+ ```xml
651
+ ... previous definitions ...
652
+ <edge id="2si" from="m2" to="0" priority="3" numLanes="3" speed="13.89">
653
+ <split pos="0" lanes="0 1"/>
654
+ <split pos="30" lanes="0 1 2"/>
655
+ </edge>
656
+ ... further definitions ...
657
+ ```
658
+
659
+ There are several things to note:
660
+
661
+ - In the road definition, we use the maximum lane number (3)
662
+ - We add an "split" at position 0; in this case, no node is built, but
663
+ the lane number is applied to the edge directly.
664
+ - If we add a split with a position only, it resets lane number and
665
+ speed to the default values for the edge (so in the example above we
666
+ could have left out the lanes attribute in the second split).
667
+
668
+ It is also possible to add a common split in both directions of a road.
669
+ With the example below, one new node is created which splits the forward
670
+ and backward edge:
671
+
672
+ ```xml
673
+ <edge id="123">
674
+ <split id="newNode" pos="150"/>
675
+ </edge>
676
+ ```
677
+
678
+ ```xml
679
+ <edge id="-123">
680
+ <split id="newNode" pos="-150"/>
681
+ </edge>
682
+ ```
683
+
684
+ The definition of a split uses the following attributes:
685
+
686
+ | Attribute Name | Value Type | Description |
687
+ | ------------------------------------------ | ----------------------- | --------------------------------- |
688
+ | **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 |
689
+ | lanes | list of lane ids (ints) | Information which lanes should exist after the split |
690
+ | speed | float | The speed in m/s after the split position |
691
+ | 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* |
692
+ | idBefore | id (string) | The id of the edge before the split (defaults to the original id) |
693
+ | idAfter | id (string) | The id of the edge after the split (defaults to <origID.pos\>) |
694
+ | offset | float | Extra sideways shift to be applied to the edge after the split |
695
+ | type, tl, tlType, shape, radius, keepClear | | see [\#Node_Descriptions](#node_descriptions) |
696
+
697
+ ## Roundabouts
698
+
699
+ Edges may be part of a roundabout. This influences the right of way
700
+ computation and disables turn-arounds for edges entering the roundabout
701
+ from outside. A roundabout is specified within an *.edg.xml*-file in the
702
+ following way:
703
+
704
+ ```xml
705
+ <edges>
706
+ ... <!--Edge Definitions -->
707
+
708
+ <roundabout edges="<EDGE_ID> <EDGE_ID> [<EDGE_ID>..]"/>
709
+
710
+ </edges>
711
+ ```
712
+
713
+ Manual specification of roundabouts is a useful supplement for the
714
+ existing roundabout heuristic (activated via option **--roundabouts.guess**). Guessed
715
+ roundabouts are written as part of the *plain-xml* output (option **--plain-output-prefix**).
716
+ This output can then be customized by the user and fed back into
717
+ [netconvert](../netconvert.md).
718
+
719
+ ## Neighboring opposite-direction Lanes
720
+
721
+ To enable
722
+ [opposite-direction-driving](../Simulation/OppositeDirectionDriving.md),
723
+ the adjacency information for opposite direction lanes must be defined.
724
+ This can be done explicitly by using the `<neigh>` element in an *.edg.xml* file
725
+ as follows:
726
+
727
+ ```xml
728
+ <edges>
729
+ <edge id="a" from="X" to="Y" numLanes="2">
730
+ <neigh lane="b_0"/>
731
+ </edge>
732
+
733
+ <edge id="b" from="Y" to="X">
734
+ <neigh lane="a_1"/>
735
+ </edge>
736
+ </edges>
737
+ ```
738
+
739
+ In the above input the inner-most lanes of edges *a* and *b* are
740
+ declared as adjacent.
741
+
742
+ ## Deleting edges or lanes
743
+
744
+ In order to delete an edge or lane which comes from a different source
745
+ or a preprocessed net one can give the edge id and the optional index in
746
+ the following way:
747
+
748
+ ```xml
749
+ <edges>
750
+ <delete id="a"/> <!-- deletes the edge "a" -->
751
+ <delete id="a" index="0"/> <!-- deletes the first lane of edge "a" -->
752
+ </edges>
753
+ ```
754
+
755
+ It is also possible to remove all edges of a specific type (see below)
756
+ by giving the attribute remove="true" to the type.
757
+
758
+ # Type Descriptions
759
+
760
+ | **Edge Type Descriptions** | |
761
+ |--------------------|----------------|
762
+ | Filename extension | .typ.xml |
763
+ | Type of content | Edge Types |
764
+ | Open format? | Yes |
765
+ | SUMO specific? | Yes |
766
+ | XML Schema | [types_file.xsd](https://sumo.dlr.de/xsd/types_file.xsd) |
767
+
768
+ As mentioned, [edge types](../SUMO_edge_type_file.md) are meant to
769
+ be used to ease the definition of edges. Each description of an edge
770
+ should include information about the number of lanes, the maximum speed
771
+ allowed on this edge and optionally this edge's priority and its allowed
772
+ and disallowed vehicle classes. See [SUMO edge type file](../SUMO_edge_type_file.md) for a complete description of edge
773
+ types and the format of those files.
774
+
775
+ The attributes of a type are of course exactly the same as for edges
776
+ themselves. The information about the nodes the edge starts and ends at
777
+ is not given within the types' descriptions. They can only be set within
778
+ the edge's attributes. Here's an example on referencing types in edge
779
+ definitions:
780
+
781
+ ```xml
782
+ <edges>
783
+
784
+ <edge id="1fi" from="1" to="m1" type="b"/>
785
+ <edge id="1si" from="m1" to="0" type="a"/>
786
+ <edge id="1o" from="0" to="1" type="c"/>
787
+
788
+ <edge id="2fi" from="2" to="m2" type="b"/>
789
+ <edge id="2si" from="m2" to="0" type="a"/>
790
+ <edge id="2o" from="0" to="2" type="c"/>
791
+
792
+ <edge id="3fi" from="3" to="m3" type="b"/>
793
+ <edge id="3si" from="m3" to="0" type="a"/>
794
+ <edge id="3o" from="0" to="3" type="c"/>
795
+
796
+ <edge id="4fi" from="4" to="m4" type="b"/>
797
+ <edge id="4si" from="m4" to="0" type="a"/>
798
+ <edge id="4o" from="0" to="4" type="c"/>
799
+
800
+ </edges>
801
+ ```
802
+
803
+ The according types file looks like this (see [SUMO edge type file](../SUMO_edge_type_file.md)):
804
+
805
+ ```xml
806
+ <types>
807
+
808
+ <type id="a" priority="3" numLanes="3" speed="13.889"/>
809
+ <type id="b" priority="2" numLanes="2" speed="11.111"/>
810
+ <type id="c" priority="1" numLanes="1" speed="11.111"/>
811
+
812
+ </types>
813
+ ```
814
+
815
+ As you can see, we have joined the edges into three classes "a", "b",
816
+ and "c" and have generated a description for each of these classes.
817
+ Doing this, the generated net is similar to the one generated using the
818
+ settings described above (example
819
+ "{{SUMO}}/docs/examples/netconvert/types/cross_notypes/" ).
820
+
821
+ ## vehicle-class specific speed limits
822
+
823
+ Using `<type>` definitions it is possible to implement vClass specific speed
824
+ limits:
825
+
826
+ ```xml
827
+ <type id="a" priority="3" numLanes="3" speed="38.89">
828
+ <restriction vClass="truck" speed="27.89"/>
829
+ </type>
830
+ ```
831
+
832
+ 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).
833
+
834
+ An example use of vehicle-class specific speed limits would be trucks on
835
+ German motorways which are not permitted to exceed 100km/h even where
836
+ passenger cars have a higher speed limit. While this could also be
837
+ modeled by setting a lower `maxSpeed` for trucks, that approach would preclude the
838
+ use of `speedDev` and `speedFactor` to easily model the variation of speeds around the legal
839
+ speed limit.
840
+
841
+ !!! note
842
+ vClass-specific speed limit restrictions can also be loaded directly into [sumo](../sumo.md) from an additional file (only type attribute 'id' is needed)
843
+
844
+ ## speed on junction
845
+
846
+ 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:
847
+
848
+ 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.
849
+ If the network was built with option **--junctions.higher-speed**, the maximum of both speeds is used on the junction instead.
850
+
851
+ # Connection Descriptions
852
+
853
+ | **Connection Descriptions** | |
854
+ |--------------------|----------------------|
855
+ | Filename extension | .con.xml |
856
+ | Type of content | Connections |
857
+ | Open format? | Yes |
858
+ | SUMO specific? | Yes |
859
+ | XML Schema | [connections_file.xsd](https://sumo.dlr.de/xsd/connections_file.xsd) |
860
+
861
+ "Connections" describe how a node's incoming and outgoing edges are
862
+ connected (for example to prohibit left-turns at some junctions). Your
863
+ can specify connections on the edge level or you can declare in in
864
+ detail which incoming lane shall be connected to which outgoing lanes.
865
+ If you leave some connections unspecified
866
+ [netconvert](../netconvert.md) automatically computes the missing
867
+ information based on heuristics.
868
+
869
+ !!! note
870
+ 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).
871
+
872
+ ## Explicitly setting which Edge / Lane is connected to which
873
+
874
+ Though guessed if not given, definitions of connections between edges or
875
+ lanes may be manually set up and given to
876
+ [netconvert](../netconvert.md) using connection files. The
877
+ connection file specifies which edges outgoing from a junction may be
878
+ reached by a certain edge incoming into this junction and optionally
879
+ also which lanes shall be used on both sides.
880
+
881
+ ### Edge-to-Edge connectivity
882
+
883
+ If you only want to describe which edges may be reached from a certain
884
+ edge, the definition is:
885
+
886
+ ```
887
+ <connection from="<FROM_EDGE_ID>" to="<T0_EDGE_ID>"/>
888
+ ```
889
+
890
+ This tells [netconvert](../netconvert.md) not only that vehicles shall be
891
+ allowed to drive from the edge named *<FROM_EDGE_ID\>* to the edge named
892
+ *<TO_EDGE_ID\>*, but also prohibits all movements to other edges from
893
+ *<FROM_EDGE_ID\>*, unless they are specified within this file. Let's
894
+ repeat the parameters:
895
+
896
+ | Attribute Name | Value Type | Description |
897
+ | -------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------ |
898
+ | **from** | referenced edge id | The name of the edge the vehicles leave |
899
+ | 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. |
900
+
901
+ When using the kind of input, [netconvert](../netconvert.md) will
902
+ compute which lanes shall be used if any of the connected edges has more
903
+ than one lane. To obtain more control, additional attributes may be given as described below.
904
+
905
+ ### Lane-to-Lane connectivity
906
+
907
+ To declare connections fully (and avoid any kind of guessing), use the following:
908
+
909
+ ```
910
+ <connection from="<FROM_EDGE_ID>" to="<T0_EDGE_ID>" fromLane="<INT_1>" toLane="<INT_2>"/>
911
+ ```
912
+
913
+ 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.
914
+
915
+ | Attribute Name | Value Type | Default | Description |
916
+ | -------------- | -------------------------------------- | ------- | ----------------------------------------------------------------------- |
917
+ | **from** | referenced edge id | | The name of the edge the vehicles leave |
918
+ | to | referenced edge id | | The name of the edge the vehicles may reach when leaving "from" |
919
+ | fromLane | *<INT\>* | | the lane index of the incoming lane (numbers starting with 0) |
920
+ | toLane | *<INT\>* | | the lane index of the outgoing lane (numbers starting with 0) |
921
+ | pass | bool | false | if set, vehicles which pass this (lane-2-lane) connection) will not wait |
922
+ | 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). |
923
+ | 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. |
924
+ | 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. |
925
+ | 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. |
926
+ | 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. |
927
+ | uncontrolled | bool | false | if set to *true*, This connection will not be TLS-controlled despite its node being controlled. |
928
+ | allow | list of vehicle classes | | set custom permissions independent of from-lane and to-lane permissions. |
929
+ | disallow | list of vehicle classes | | set custom permissions independent of from-lane and to-lane permissions. |
930
+ | changeLeft | list of vehicle classes | List of vehicle classes that may change left from this lane |
931
+ | changeRight | list of vehicle classes | List of vehicle classes that may change right from this lane |
932
+ | length | float | | set a [custom length](../Simulation/Distances.md#length-geometry-mismatch) for this connection |
933
+ | indirect | bool | false | declare an indirect (two-step) turning movement (affects geometry and right-of-way) |
934
+ | type | string | | set custom edgeType for applying [vClass-specific speed limits](#vehicle-class_specific_speed_limits) |
935
+
936
+ ### Deleting connections
937
+
938
+ [netconvert](../netconvert.md) may be used to patch existing sumo networks (*.net.xml* files) and changing connections is one of the supported use cases.
939
+ If you only wish to **remove** a connection it may be convenient to use
940
+ the following xml definition:
941
+
942
+ ```
943
+ <delete from="<FROM_EDGE_ID>" to="<T0_EDGE_ID>"/>
944
+ ```
945
+
946
+ The attributes are the same as for the
947
+ simple connection element:
948
+
949
+ | Attribute Name | Value Type | Description |
950
+ | -------------- | ------------------ | ---------------------------------------------------------- |
951
+ | **from** | referenced edge id | The source edge id of the connection to be removed |
952
+ | **to** | referenced edge id | The destination edge id of the connection to be removed |
953
+ | fromLane | referenced lane no | The source lane index of the connection to be removed |
954
+ | toLane | referenced lane no | The destination lane index of the connection to be removed |
955
+
956
+ !!! note
957
+ 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.
958
+
959
+ ### Patching connections and guessing again
960
+
961
+ By default there are two modes when processing connections.
962
+
963
+ 1. when loading from *plain-xml*, any missing information is guessed (and this typically causes connections to be added)
964
+ 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).
965
+
966
+ It may be convenient to trigger re-guessing of connections for selected edges (i.e. after loading and edge-patch to change lane numbers).
967
+ For this, the following definition may be used:
968
+
969
+ ```
970
+ <connection from="<FROM_EDGE_ID>" reset="true"/>
971
+ ```
972
+
973
+ This will trigger all connections from edge with id `FROM_EDGE_ID` to be removed and re-guessed.
974
+
975
+ ### Examples
976
+
977
+ There are two examples within the distribution. Both use the nodes and
978
+ edges descriptions from the example located in
979
+ "{{SUMO}}/docs/examples/netconvert/types/cross_notypes/". The junction in the
980
+ center of this example looks like shown within the next figure. We will
981
+ now call it the "unconstrained network" because all connections and
982
+ turnarounds are computed using the default values.
983
+
984
+ ![cross3l_unconstrained.gif](../images/Cross3l_unconstrained.gif "Unconstrained Network")
985
+ Unconstrained Network
986
+
987
+ The example
988
+ {{SUMO}}/docs/examples/netconvert/connections/cross3l_edge2edge_conns/" shows
989
+ what happens when one uses connections to limit the number of reachable
990
+ edges. To do this we built a connections file where we say that the
991
+ horizontal edges ("1si" and "2si") have only connections to the edges
992
+ right to them and the edge in straight direction. The file looks like
993
+ this:
994
+
995
+ ```xml
996
+ <connections>
997
+
998
+ <connection from="1si" to="3o"/>
999
+ <connection from="1si" to="2o"/>
1000
+
1001
+ <connection from="2si" to="4o"/>
1002
+ <connection from="2si" to="1o"/>
1003
+
1004
+ </connections>
1005
+ ```
1006
+
1007
+ As you may see in the next picture, the horizontal edges within the
1008
+ result network contain no left-moving connections.
1009
+
1010
+ ![cross3l_edge2edge_conns.gif](../images/Cross3l_edge2edge_conns.gif "Network with explicit edge-2-edge connections")
1011
+ Network with explicit edge-2-edge connections
1012
+
1013
+ In the second example located in
1014
+ {{SUMO}}/docs/examples/netconvert/connections/cross3l_lane2lane_conns" we
1015
+ additionally describe which lanes shall be connected. The according
1016
+ connections file says that the connections going straight shall be start
1017
+ at the second lane of the incoming edges:
1018
+
1019
+ ```xml
1020
+ <connections>
1021
+
1022
+ <connection from="1si" to="3o" fromLane="0" toLane="0"/>
1023
+ <connection from="1si" to="2o" fromLane="2" toLane="0"/>
1024
+
1025
+ <connection from="2si" to="4o" fromLane="0" toLane="0"/>
1026
+ <connection from="2si" to="1o" fromLane="2" toLane="0"/>
1027
+
1028
+ </connections>
1029
+ ```
1030
+
1031
+ The built network looks like this:
1032
+
1033
+ ![cross3l_lane2lane_conns.gif](../images/Cross3l_lane2lane_conns.gif "Network with explicit lane-2-lane connections")
1034
+ Network with explicit lane-2-lane connections
1035
+
1036
+ !!! caution
1037
+ 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.
1038
+
1039
+
1040
+
1041
+ ## Setting Connection Priorities
1042
+
1043
+ Since version 0.9.6 you can also let vehicles passing a connection
1044
+ between two edges wait for another stream. Let's take another look at
1045
+ "Network with explicit edge-2-edge connections" above. Here, all
1046
+ right-moving vehicles may drive. The following definition within the
1047
+ connections file lets vehicles on vertical edges moving right wait for
1048
+ those which move straight on horizontal edges:
1049
+
1050
+ ```xml
1051
+ <connections>
1052
+
1053
+ <!-- The next four connection definitions are same as in
1054
+ "Network with explicit edge-2-edge connections" -->
1055
+ <connection from="1si" to="3o"/>
1056
+ <connection from="1si" to="2o"/>
1057
+
1058
+ <connection from="2si" to="4o"/>
1059
+ <connection from="2si" to="1o"/>
1060
+
1061
+ <!-- now, let's prohibit the vertical connections by the horizontal -->
1062
+ <!-- prohibit moving right from top to left by straight from right to left -->
1063
+ <prohibition prohibitor="2si->1o" prohibited="4si->1o"/>
1064
+ <!-- prohibit moving straight from top to bottom by straight from right to left -->
1065
+ <prohibition prohibitor="2si->1o" prohibited="4si->3o"/>
1066
+ <!-- prohibit moving left from top to right by straight from right to left -->
1067
+ <prohibition prohibitor="2si->1o" prohibited="4si->2o"/>
1068
+
1069
+ <!-- prohibit moving right from bottom to right by straight from left to right -->
1070
+ <prohibition prohibitor="1si->2o" prohibited="3si->2o"/>
1071
+ <!-- prohibit moving straight from bottom to top by straight from left to right -->
1072
+ <prohibition prohibitor="1si->2o" prohibited="3si->4o"/>
1073
+ <!-- prohibit moving left from bottom to right by straight from left to right -->
1074
+ <prohibition prohibitor="1si->2o" prohibited="3si->1o"/>
1075
+
1076
+ </connections>
1077
+ ```
1078
+
1079
+ As one may see, it was necessary to prohibit all connections from a
1080
+ vertical edge by the counter-clockwise straight connection on a
1081
+ horizontal edge because otherwise the vehicles on the horizontal edge
1082
+ want to wait due to right-before-left - rule. The network looks like
1083
+ this:
1084
+
1085
+ ![cross3l_prohibitions.gif](../images/Cross3l_prohibitions.gif "Network with explicite prohibitions")
1086
+ Network with explicit prohibitions
1087
+
1088
+ 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>"/>`.
1089
+ This means we define two connections (edge-to-edge), the prohibiting one
1090
+ (prohibitor) and the prohibited (prohibited). Each connection is defined
1091
+ by a from-edge and a to-edge, divided by "-\>".
1092
+
1093
+ ## Multiple connections from the same edge to the same target lane
1094
+
1095
+ From version 0.25.0 on, specifying conflicting connections from the same
1096
+ edge will cause a priority order to be established among them, allowing
1097
+ for a collision-free simulation. By default, the right-most lane will
1098
+ have the right of way but this can be customized by using attribute
1099
+ *pass* as shown below:
1100
+
1101
+ ```xml
1102
+ <connections>
1103
+ <connection from="WC" to="CE" fromLane="0" toLane="0"/>
1104
+ <connection from="WC" to="CE" fromLane="1" toLane="0" pass="true"/>
1105
+ </connections>
1106
+ ```
1107
+
1108
+ # Traffic Light Program Definition
1109
+
1110
+ | ** Traffic light Descriptions** | |
1111
+ |--------------------|--------------------------|
1112
+ | Filename extension | .tll.xml |
1113
+ | Type of content | traffic light definition |
1114
+ | Open format? | Yes |
1115
+ | SUMO specific? | Yes |
1116
+ | XML Schema | [tllogic_file.xsd](https://sumo.dlr.de/xsd/tllogic_file.xsd) |
1117
+
1118
+ This file describes traffic lights, signal plans and defines which
1119
+ connections they control. It consists of two types of elements described
1120
+ below. Files of this type must be loaded in
1121
+ [netconvert](../netconvert.md) using the option **--tllogic-files** {{DT_FILE}}.
1122
+
1123
+ ## traffic light definitions
1124
+
1125
+ `<tlLogic ...>`-elements follow the same format as described in
1126
+ [Simulation/Traffic_Lights](../Simulation/Traffic_Lights.md). By
1127
+ using them in [netconvert](../netconvert.md), multiple programs
1128
+ (even for the same intersection) may be embedded in the *.net.xml* file
1129
+ instead of loading them into SUMO.
1130
+
1131
+ !!! caution
1132
+ 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.
1133
+
1134
+ ## controlled connections
1135
+
1136
+ `<connection .../>`-elements are an extension of
1137
+ [\#Connection_Descriptions](#connection_descriptions) and
1138
+ are used to define the relationship between a signal plan and the
1139
+ controlled connections.
1140
+
1141
+ This may be used to simplify signal plans by implementing signal groups.
1142
+ In this case multiple connections are defined by the same index of the
1143
+ signal plan. It can also be used to define traffic light controllers
1144
+ which control multiple intersections.
1145
+
1146
+ | Attribute Name | Value Type | Description |
1147
+ | -------------- | ------------------ | ---------------------------------------------------------------------------------- |
1148
+ | **from** | referenced edge id | The name of the edge the vehicles leave |
1149
+ | **to** | referenced edge id | The name of the edge the vehicles may reach when leaving "from" |
1150
+ | **fromLane** | int | the lane index of the incoming lane (numbers starting with 0) |
1151
+ | **toLane** | int | the lane index of the outgoing lane (numbers starting with 0) |
1152
+ | **tl** | string | id of the traffic light which controls this connection |
1153
+ | **linkIndex** | int | the index in the *state*-attribute of the `<phase>`-elements which controls this connection |
1154
+ | linkIndex2 | int | the index in the *state*-attribute of the `<phase>`-elements which controls the internal junction link (by default this is uncontrolled) |
1155
+
1156
+ You can easily get examples for this type of file by loading a
1157
+ *sumo.net.xml* in [netconvert](../netconvert.md) and using option **--plain-output-prefix**.
1158
+
1159
+ # Pedestrian Crossings
1160
+
1161
+ When building a network for [pedestrian simulation](../Simulation/Pedestrians.md), pedestrian crossings at
1162
+ intersections can be specified explicitly. This is done using elements
1163
+ within a
1164
+ [*connection-file*](#connection_descriptions).
1165
+
1166
+ ```xml
1167
+ <crossing node="C" edges="edge1 edge2" priority="true"/>
1168
+ ```
1169
+
1170
+ The attributes are described in the following.
1171
+
1172
+ | Attribute Name | Value Type | Description |
1173
+ | -------------- | ---------------------------------------------- | ------------------------------------------------------------------ |
1174
+ | **node** | id (string) | The name of the node at which this crossing is located |
1175
+ | **edges** | ids (list of strings) | The (road) edges which are crossed |
1176
+ | priority | bool | Whether the pedestrians have priority over the vehicles (automatically set to true at tls-controlled intersections). |
1177
+ | width | real (m) | The width of the crossings. |
1178
+ | 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. |
1179
+ | linkIndex | int | specifies a custom index within the signal plan (for the forward direction) |
1180
+ | linkIndex2 | int | specifies a custom index within the signal plan (for the backward direction) |
1181
+ | 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. |
1182
+
1183
+ Pedestrians may only cross the street at a crossing. Crossings may have
1184
+ priority which means, pedestrians are free to walk without
1185
+ considerations for vehicular traffic. This can be used to model the
1186
+ behavior at controlled intersections and at marked pedestrian crossings
1187
+ (at least for some countries such as Germany). At uncontrolled
1188
+ intersections pedestrians may only cross when there is a suitable gap in
1189
+ road traffic.
1190
+
1191
+ !!! note
1192
+ 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.
1193
+
1194
+ # Walking Areas
1195
+
1196
+ When building a network for [pedestrian simulation](../Simulation/Pedestrians.md) walking areas are
1197
+ generated automatically. These network elements are used to connect
1198
+ multiple side walks and pedestrian crossings (typically one in each
1199
+ corner of an intersection). The shape of a walking area can be specified
1200
+ explicitly. This is done using `walkingArea` element within a
1201
+ [*connection-file*](#connection_descriptions).
1202
+
1203
+ ```xml
1204
+ <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"/>
1205
+ ```
1206
+
1207
+ The attributes are described in the following.
1208
+
1209
+ | Attribute Name | Value Type | Description |
1210
+ | -------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------- |
1211
+ | **node** | id (string) | The name of the node at which this walking area is located |
1212
+ | **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. |
1213
+ | **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.
1214
+ | width | double | custom width for waiting/walking on this walking area |
1215
+ ```
20260907-002650-transport-safety-0ac894/environment/public_data/input/tutorial_text_windows.csv ADDED
The diff for this file is too large to render. See raw diff
 
20260907-002650-transport-safety-0ac894/environment/public_data/main.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import importlib.util
4
+ import json
5
+ import os
6
+ import shlex
7
+ import shutil
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+
12
+ class Task:
13
+ def __init__(self, task_id: str, description: str, metadata: dict[str, Any]):
14
+ self.task_id = task_id
15
+ self.description = description
16
+ self.prompt = description
17
+ self.metadata = metadata
18
+ self.computer = {"setup_config": {"os_type": "linux"}}
19
+
20
+
21
+ def _task_dir() -> Path:
22
+ return Path(__file__).resolve().parent
23
+
24
+
25
+ def _load_card() -> dict[str, Any]:
26
+ path = _task_dir() / "task_card.json"
27
+ if not path.is_file():
28
+ return {
29
+ "taskId": os.environ.get("ALE_TASK_ID", "transport_safety/sumo_plainxml_document_inventory_audit"),
30
+ "taskPrompt": "Task card has not been rendered yet; this fallback exists for stage-03 hook smoke only.",
31
+ "metadata": {
32
+ "domain": "transport_safety",
33
+ "task": "sumo_plainxml_document_inventory_audit",
34
+ "variant": "base",
35
+ "domain_name": "transport_safety",
36
+ "task_name": "sumo_plainxml_document_inventory_audit",
37
+ "variant_name": "base",
38
+ "requires_task_data": True,
39
+ "task_dir": "/media/user/data/agenthle/transport_safety/sumo_plainxml_document_inventory_audit/base",
40
+ "input_dir": "/media/user/data/agenthle/transport_safety/sumo_plainxml_document_inventory_audit/base/input",
41
+ "software_dir": "/media/user/data/agenthle/transport_safety/sumo_plainxml_document_inventory_audit/base/software",
42
+ "remote_output_dir": "/media/user/data/agenthle/transport_safety/sumo_plainxml_document_inventory_audit/base/output",
43
+ "reference_dir": "/media/user/data/agenthle/transport_safety/sumo_plainxml_document_inventory_audit/base/reference",
44
+ },
45
+ }
46
+ with path.open("r", encoding="utf-8") as handle:
47
+ return json.load(handle)
48
+
49
+
50
+ def load() -> list[Task]:
51
+ card = _load_card()
52
+ metadata = dict(card.get("metadata") or {})
53
+ if not metadata:
54
+ domain, _, task = str(card["taskId"]).partition("/")
55
+ variant = "base"
56
+ task_dir = f"/media/user/data/agenthle/{domain}/{task}/{variant}"
57
+ metadata.update({
58
+ "domain": domain,
59
+ "task": task,
60
+ "variant": variant,
61
+ "domain_name": domain,
62
+ "task_name": task,
63
+ "variant_name": variant,
64
+ "requires_task_data": True,
65
+ "task_dir": task_dir,
66
+ "input_dir": f"{task_dir}/input",
67
+ "software_dir": f"{task_dir}/software",
68
+ "remote_output_dir": f"{task_dir}/output",
69
+ "reference_dir": f"{task_dir}/reference",
70
+ })
71
+ return [Task(task_id=card["taskId"], description=card["taskPrompt"], metadata=metadata)]
72
+
73
+
74
+ def _metadata(cfg: Any = None) -> dict[str, Any]:
75
+ if cfg is None:
76
+ return {}
77
+ value = getattr(cfg, "metadata", None)
78
+ return value if isinstance(value, dict) else {}
79
+
80
+
81
+ def _remote_path(metadata: dict[str, Any], key: str, fallback: str) -> str:
82
+ value = str(metadata.get(key) or "").strip()
83
+ return value or fallback
84
+
85
+
86
+ async def _remote_run(session: Any, command: str, *, check: bool = False) -> Any:
87
+ try:
88
+ return await session.run_command(command, check=check)
89
+ except TypeError:
90
+ return await session.run_command(command)
91
+
92
+
93
+ async def _remote_start(cfg: Any, session: Any) -> dict[str, Any]:
94
+ metadata = _metadata(cfg)
95
+ output_dir = _remote_path(metadata, "remote_output_dir", "output")
96
+ input_dir = _remote_path(metadata, "input_dir", "input")
97
+ software_dir = _remote_path(metadata, "software_dir", "software")
98
+ command = (
99
+ "set -eu\n"
100
+ f"mkdir -p {shlex.quote(output_dir)}\n"
101
+ f"find {shlex.quote(output_dir)} -mindepth 1 -maxdepth 1 -exec rm -rf -- {{}} +\n"
102
+ )
103
+ await _remote_run(session, command, check=True)
104
+ return {"ok": True, "input_dir": input_dir, "software_dir": software_dir, "output_dir": output_dir}
105
+
106
+
107
+ def start(cfg: Any = None, session: Any = None) -> dict[str, Any]:
108
+ if session is not None:
109
+ return _remote_start(cfg, session)
110
+ del cfg
111
+ output_dir = Path(os.environ.get("ALE_OUTPUT_DIR", "output"))
112
+ output_dir.mkdir(parents=True, exist_ok=True)
113
+ for child in output_dir.iterdir():
114
+ if child.is_dir():
115
+ shutil.rmtree(child)
116
+ else:
117
+ child.unlink()
118
+ input_dir = Path(os.environ.get("ALE_INPUT_DIR", "input"))
119
+ software_dir = Path(os.environ.get("ALE_SOFTWARE_DIR", "software"))
120
+ return {
121
+ "ok": True,
122
+ "input_dir": str(input_dir),
123
+ "software_dir": str(software_dir),
124
+ "output_dir": str(output_dir),
125
+ }
126
+
127
+
128
+ async def _remote_evaluate(cfg: Any, session: Any) -> list[float]:
129
+ metadata = _metadata(cfg)
130
+ output_dir = _remote_path(metadata, "remote_output_dir", "output")
131
+ reference_dir = _remote_path(metadata, "reference_dir", "reference")
132
+ script = f"""
133
+ import importlib.util
134
+ import json
135
+ import pathlib
136
+
137
+ output_dir = pathlib.Path({output_dir!r})
138
+ reference_dir = pathlib.Path({reference_dir!r})
139
+ evaluator_path = reference_dir / "evaluator.py"
140
+ if not evaluator_path.is_file():
141
+ raise FileNotFoundError(f"hidden evaluator is missing: {{evaluator_path}}")
142
+ spec = importlib.util.spec_from_file_location("hidden_ale_evaluator", evaluator_path)
143
+ if spec is None or spec.loader is None:
144
+ raise RuntimeError(f"cannot import hidden evaluator: {{evaluator_path}}")
145
+ module = importlib.util.module_from_spec(spec)
146
+ spec.loader.exec_module(module)
147
+ result = module.evaluate(output_dir, reference_dir)
148
+ print(json.dumps(result))
149
+ """
150
+ command = "python3 - <<'PY'\n" + script + "\nPY"
151
+ result = await _remote_run(session, command, check=True)
152
+ stdout = getattr(result, "stdout", "") or ""
153
+ for line in reversed([item.strip() for item in stdout.splitlines() if item.strip()]):
154
+ try:
155
+ payload = json.loads(line)
156
+ if isinstance(payload, list):
157
+ return [float(max(0.0, min(1.0, value))) for value in payload]
158
+ except Exception:
159
+ continue
160
+ raise RuntimeError("hidden evaluator did not emit a JSON score list")
161
+
162
+
163
+ def evaluate(cfg: Any = None, session: Any = None) -> list[float]:
164
+ if session is not None:
165
+ return _remote_evaluate(cfg, session)
166
+ del cfg
167
+ output_dir = Path(os.environ.get("ALE_OUTPUT_DIR", "output"))
168
+ reference_dir = Path(os.environ.get("ALE_REFERENCE_DIR", "reference"))
169
+ evaluator_path = reference_dir / "evaluator.py"
170
+ if not evaluator_path.is_file():
171
+ raise FileNotFoundError(f"hidden evaluator is missing: {evaluator_path}")
172
+ spec = importlib.util.spec_from_file_location("hidden_ale_evaluator", evaluator_path)
173
+ if spec is None or spec.loader is None:
174
+ raise RuntimeError(f"cannot import hidden evaluator: {evaluator_path}")
175
+ module = importlib.util.module_from_spec(spec)
176
+ spec.loader.exec_module(module)
177
+ result = module.evaluate(output_dir, reference_dir)
178
+ if not isinstance(result, list):
179
+ raise TypeError("hidden evaluator must return list[float]")
180
+ return [float(max(0.0, min(1.0, value))) for value in result]
20260907-002650-transport-safety-0ac894/environment/public_data/software/command_examples.csv ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ term,kind,software_name
2
+ duarouter,code_term,SUMO
3
+ netedit,code_term,SUMO
4
+ .net.xml,code_term,SUMO
5
+ .rou.xml,code_term,SUMO
6
+ sumo,executable,SUMO
7
+ netconvert,executable,SUMO
8
+ duarouter,executable,SUMO
9
+ netedit,executable,SUMO
20260907-002650-transport-safety-0ac894/environment/public_data/software/software_manifest.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "software_name": "SUMO",
3
+ "executables": [
4
+ "sumo",
5
+ "netconvert",
6
+ "duarouter",
7
+ "netedit"
8
+ ],
9
+ "required_system_packages": [
10
+ "sumo",
11
+ "sumo-tools"
12
+ ],
13
+ "official_sources": [
14
+ "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md"
15
+ ],
16
+ "solve_time_network": "disabled",
17
+ "python_wrapper_only": false,
18
+ "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs."
19
+ }
20260907-002650-transport-safety-0ac894/environment/public_data/software/validate_outputs.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+
10
+ def required_outputs(input_dir: Path) -> list[str]:
11
+ spec_path = input_dir / "analysis_spec.json"
12
+ if spec_path.is_file():
13
+ payload = json.loads(spec_path.read_text(encoding="utf-8"))
14
+ required = payload.get("required_outputs") if isinstance(payload, dict) else None
15
+ if isinstance(required, list):
16
+ rows = [str(item.get("path") or "") for item in required if isinstance(item, dict)]
17
+ rows = [item for item in rows if item]
18
+ if rows:
19
+ return rows
20
+ return [
21
+ "summary.json",
22
+ "magnitude_depth_bins.csv",
23
+ "region_daily_counts.csv",
24
+ "filtered_events.geojson",
25
+ ]
26
+
27
+
28
+ def main() -> int:
29
+ output_dir = Path(sys.argv[1]) if len(sys.argv) > 1 else Path("output")
30
+ input_dir = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(os.environ.get("ALE_INPUT_DIR", "input"))
31
+ required = required_outputs(input_dir)
32
+ missing = [name for name in required if not (output_dir / name).is_file()]
33
+ if missing:
34
+ print(json.dumps({"ok": False, "missing": missing}, indent=2))
35
+ return 1
36
+ print(json.dumps({"ok": True, "required": required}, indent=2))
37
+ return 0
38
+
39
+
40
+ if __name__ == "__main__":
41
+ raise SystemExit(main())
20260907-002650-transport-safety-0ac894/environment/public_data/task_card.json ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "taskId": "transport_safety/sumo_plainxml_document_inventory_audit__20260907-002650_transport_safety_0ac894",
3
+ "title": "Repair3 20260907 088 Repair2 20260906 094 Repair 20260906 Software 0108",
4
+ "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).",
5
+ "category": "transport_safety",
6
+ "taxonomy": {
7
+ "domain_id": "1",
8
+ "domain_code": "engineering",
9
+ "subdomain_id": "1.10",
10
+ "subdomain_code": "urban_planning",
11
+ "subdomain_name": "Urban & Spatial Planning",
12
+ "classifier": {
13
+ "source": "public software metadata mapping",
14
+ "rationale": "Subdomain selected from public task metadata."
15
+ }
16
+ },
17
+ "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.",
18
+ "agentMustDo": [
19
+ "Read input/analysis_spec.json first and treat it as the authoritative public specification.",
20
+ "Read input/tutorial_text_windows.csv and compute results from the staged local data.",
21
+ "Create output/summary.json as json exactly as specified by analysis_spec.json.",
22
+ "Create output/section_outline.csv as csv exactly as specified by analysis_spec.json.",
23
+ "Create output/keyword_inventory.csv as csv exactly as specified by analysis_spec.json.",
24
+ "Create output/code_block_inventory.csv as csv exactly as specified by analysis_spec.json.",
25
+ "Place every final deliverable directly under output/ with the exact required filename.",
26
+ "Use only local staged files and installed Linux CLI tooling; do not download fresh data."
27
+ ],
28
+ "inputFiles": [
29
+ {
30
+ "name": "README.md",
31
+ "format": "Markdown",
32
+ "path": "input/README.md",
33
+ "description": "Agent-visible staged input file for this task."
34
+ },
35
+ {
36
+ "name": "analysis_spec.json",
37
+ "format": "JSON",
38
+ "path": "input/analysis_spec.json",
39
+ "description": "Agent-visible staged input file for this task."
40
+ },
41
+ {
42
+ "name": "source_context_windows.jsonl",
43
+ "format": "JSONL",
44
+ "path": "input/source_context_windows.jsonl",
45
+ "description": "Agent-visible staged input file for this task."
46
+ },
47
+ {
48
+ "name": "tutorial_metadata.json",
49
+ "format": "JSON",
50
+ "path": "input/tutorial_metadata.json",
51
+ "description": "Agent-visible staged input file for this task."
52
+ },
53
+ {
54
+ "name": "tutorial_source.html",
55
+ "format": "HTML",
56
+ "path": "input/tutorial_source.html",
57
+ "description": "Agent-visible staged input file for this task."
58
+ },
59
+ {
60
+ "name": "tutorial_text_windows.csv",
61
+ "format": "CSV",
62
+ "path": "input/tutorial_text_windows.csv",
63
+ "description": "Agent-visible staged input file for this task."
64
+ }
65
+ ],
66
+ "referenceFiles": [
67
+ {
68
+ "name": "summary.json",
69
+ "format": "JSON",
70
+ "path": "output/summary.json",
71
+ "description": "Required agent output file evaluated against hidden reference data."
72
+ },
73
+ {
74
+ "name": "section_outline.csv",
75
+ "format": "CSV",
76
+ "path": "output/section_outline.csv",
77
+ "description": "Required agent output file evaluated against hidden reference data."
78
+ },
79
+ {
80
+ "name": "keyword_inventory.csv",
81
+ "format": "CSV",
82
+ "path": "output/keyword_inventory.csv",
83
+ "description": "Required agent output file evaluated against hidden reference data."
84
+ },
85
+ {
86
+ "name": "code_block_inventory.csv",
87
+ "format": "CSV",
88
+ "path": "output/code_block_inventory.csv",
89
+ "description": "Required agent output file evaluated against hidden reference data."
90
+ }
91
+ ],
92
+ "software": [
93
+ "SUMO",
94
+ "sumo",
95
+ "netconvert",
96
+ "duarouter",
97
+ "netedit",
98
+ "Python 3.11",
99
+ "standard Unix shell",
100
+ "software/command_examples.csv",
101
+ "software/software_manifest.json",
102
+ "software/validate_outputs.py"
103
+ ],
104
+ "requiredSystemPackages": [
105
+ "sumo",
106
+ "sumo-tools"
107
+ ],
108
+ "evaluation": "Final required files under output/ are compared against standard-reference outputs generated by the deterministic workflow for this task.",
109
+ "vm": {
110
+ "machineType": "c4-standard-4",
111
+ "snapshot": "cpu-free-ubuntu",
112
+ "timeout": 7200
113
+ }
114
+ }
20260907-002650-transport-safety-0ac894/instruction.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Repair3 20260907 088 Repair2 20260906 094 Repair 20260906 Software 0108
2
+
3
+ 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).
4
+
5
+ ## Task
6
+
7
+ 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:
8
+ - 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"}
9
+ - output/section_outline.csv: CSV header exactly rank, heading_level, heading_text, slug
10
+ - output/keyword_inventory.csv: CSV header exactly term, category, count, first_window, appears_in_code
11
+ - output/code_block_inventory.csv: CSV header exactly block_index, line_count, char_count, contains_code_term, first_line
12
+ Compute 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.
13
+
14
+ ## Workspace
15
+
16
+ You are working in `/workspace`.
17
+
18
+ - Public input files are under `/workspace/input/`.
19
+ - Public helper software and validation scripts are under `/workspace/software/`.
20
+ - The public task card is available at `/workspace/task_card.json`.
21
+ - The public task driver is available at `/workspace/main.py` for reference only.
22
+ - Do not use hidden reference data, network downloads, credentials, GUI tools, or browser automation.
23
+
24
+ ## Required Outputs
25
+
26
+ Create every final deliverable exactly at these paths:
27
+
28
+ - `/workspace/output/summary.json` (json)
29
+ - `/workspace/output/section_outline.csv` (csv)
30
+ - `/workspace/output/keyword_inventory.csv` (csv)
31
+ - `/workspace/output/code_block_inventory.csv` (csv)
32
+
33
+ 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.
20260907-002650-transport-safety-0ac894/solution/internal/workflow_adapters_runtime.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import datetime as dt
5
+ import html
6
+ import json
7
+ import math
8
+ import re
9
+ import shutil
10
+ import statistics
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ def _read_json(path: Path) -> Any:
16
+ with path.open("r", encoding="utf-8") as handle:
17
+ return json.load(handle)
18
+
19
+
20
+ def _write_json(path: Path, payload: Any) -> None:
21
+ path.parent.mkdir(parents=True, exist_ok=True)
22
+ with path.open("w", encoding="utf-8") as handle:
23
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
24
+ handle.write("\n")
25
+
26
+ def _stable_region(place: str) -> str:
27
+ if not place:
28
+ return "unknown"
29
+ if "," in place:
30
+ return place.split(",")[-1].strip() or place.strip()
31
+ parts = place.split()
32
+ return " ".join(parts[-2:]) if len(parts) >= 2 else place.strip()
33
+
34
+
35
+ def _mag_bin(value: float | None) -> str:
36
+ if value is None or math.isnan(value):
37
+ return "unknown"
38
+ lower = math.floor(value)
39
+ upper = lower + 1
40
+ return f"{lower:.0f}-{upper:.0f}"
41
+
42
+
43
+ def _depth_bin(value: float | None) -> str:
44
+ if value is None or math.isnan(value):
45
+ return "unknown"
46
+ if value < 0:
47
+ return "<0"
48
+ if value < 10:
49
+ return "0-10"
50
+ if value < 30:
51
+ return "10-30"
52
+ if value < 70:
53
+ return "30-70"
54
+ if value < 300:
55
+ return "70-300"
56
+ return "300+"
57
+
58
+
59
+ def _clean_markup_text(raw: str) -> str:
60
+ text = re.sub(r"(?is)<(script|style|noscript)[^>]*>.*?</\1>", " ", raw)
61
+ text = re.sub(r"(?is)<br\s*/?>", "\n", text)
62
+ text = re.sub(r"(?is)</(p|div|li|tr|h[1-6]|pre)>", "\n", text)
63
+ text = re.sub(r"(?is)<[^>]+>", " ", text)
64
+ text = html.unescape(text)
65
+ text = re.sub(r"[ \t]+", " ", text)
66
+ text = re.sub(r"\n\s+", "\n", text)
67
+ return text.strip()
68
+
69
+
70
+ def _heading_slug(value: str) -> str:
71
+ slug = re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_")
72
+ return slug[:80] or "section"
73
+
74
+
75
+ def _extract_headings(raw: str) -> list[dict[str, str]]:
76
+ headings: list[dict[str, str]] = []
77
+ for match in re.finditer(r"(?is)<h([1-6])[^>]*>(.*?)</h\1>", raw):
78
+ text = _clean_markup_text(match.group(2))
79
+ if text:
80
+ headings.append({"level": f"h{match.group(1)}", "text": text})
81
+ if headings:
82
+ return headings
83
+ for line in raw.splitlines():
84
+ match = re.match(r"^(#{1,6})\s+(.+?)\s*$", line)
85
+ if match:
86
+ headings.append({"level": f"h{len(match.group(1))}", "text": match.group(2).strip()})
87
+ return headings
88
+
89
+
90
+ def _extract_code_blocks(raw: str) -> list[str]:
91
+ blocks: list[str] = []
92
+ for match in re.finditer(r"(?is)<pre[^>]*>(.*?)</pre>", raw):
93
+ text = _clean_markup_text(match.group(1))
94
+ if text:
95
+ blocks.append(text)
96
+ for match in re.finditer(r"(?is)<code[^>]*>(.*?)</code>", raw):
97
+ text = _clean_markup_text(match.group(1))
98
+ if text and text not in blocks:
99
+ blocks.append(text)
100
+ for match in re.finditer(r"(?s)```(?:[A-Za-z0-9_-]+)?\n(.*?)```", raw):
101
+ text = html.unescape(match.group(1).strip())
102
+ if text and text not in blocks:
103
+ blocks.append(text)
104
+ return blocks
105
+
106
+
107
+ def _window_rows(clean_text: str, *, width: int = 40, stride: int = 20) -> list[dict[str, Any]]:
108
+ words = re.findall(r"\S+", clean_text)
109
+ rows: list[dict[str, Any]] = []
110
+ if not words:
111
+ return rows
112
+ start = 0
113
+ while start < len(words):
114
+ end = min(start + width, len(words))
115
+ rows.append({
116
+ "window_id": len(rows) + 1,
117
+ "start_word": start,
118
+ "end_word": end,
119
+ "text": " ".join(words[start:end]),
120
+ })
121
+ if end == len(words):
122
+ break
123
+ start += stride
124
+ return rows
125
+
126
+
127
+ def _term_count(text: str, term: str) -> int:
128
+ term = term.strip()
129
+ if not term:
130
+ return 0
131
+ return len(re.findall(re.escape(term), text, flags=re.IGNORECASE))
132
+
133
+
134
+ def _first_window(windows: list[dict[str, Any]], term: str) -> str:
135
+ term_lower = term.lower()
136
+ for row in windows:
137
+ if term_lower in str(row.get("text") or "").lower():
138
+ return str(row.get("window_id") or "")
139
+ return ""
140
+
141
+
142
+ def _write_tutorial_public_inputs(input_dir: Path, source_path: Path, spec_payload: dict[str, Any]) -> None:
143
+ raw = source_path.read_text(encoding="utf-8", errors="replace")
144
+ # Tutorial examples may contain a maintainer's local Windows path. Keep
145
+ # the command semantics while preventing host-specific paths from entering
146
+ # the public task artifact.
147
+ sanitized_raw = re.sub(r"(?i)\b[A-Z]:\\(?:[^\\\r\n<>\"']+\\?)*[^\\\r\n<>\"']*", "./local.db", raw)
148
+ clean_text = _clean_markup_text(sanitized_raw)
149
+ windows = _window_rows(clean_text)
150
+ if len(windows) < 100:
151
+ raise ValueError(f"official tutorial source produced only {len(windows)} text windows; need at least 100")
152
+ required_terms = [str(item) for item in spec_payload.get("required_terms") or []]
153
+ code_terms = [str(item) for item in spec_payload.get("code_terms") or []]
154
+ input_dir.mkdir(parents=True, exist_ok=True)
155
+ destination = input_dir / str(spec_payload["source_file"])
156
+ # Always materialize the sanitized copy, including when the downloader
157
+ # already placed the source at the destination path.
158
+ destination.write_text(sanitized_raw, encoding="utf-8")
159
+ with (input_dir / str(spec_payload["input_file"])).open("w", encoding="utf-8", newline="") as handle:
160
+ fieldnames = ["window_id", "start_word", "end_word", "text", "contains_code_term", "matched_required_terms"]
161
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
162
+ writer.writeheader()
163
+ for row in windows:
164
+ text = str(row["text"])
165
+ matched = [term for term in required_terms if term.lower() in text.lower()]
166
+ contains_code = any(term.lower() in text.lower() for term in code_terms)
167
+ writer.writerow({
168
+ "window_id": row["window_id"],
169
+ "start_word": row["start_word"],
170
+ "end_word": row["end_word"],
171
+ "text": text,
172
+ "contains_code_term": "true" if contains_code else "false",
173
+ "matched_required_terms": "|".join(matched),
174
+ })
175
+ metadata = {
176
+ "software_name": spec_payload.get("software_name"),
177
+ "tutorial_url": spec_payload.get("tutorial_url"),
178
+ "source_urls": spec_payload.get("source_urls"),
179
+ "source_file": spec_payload.get("source_file"),
180
+ "window_file": spec_payload.get("input_file"),
181
+ "window_rule": spec_payload.get("window_rule"),
182
+ "required_terms": spec_payload.get("required_terms"),
183
+ "code_terms": spec_payload.get("code_terms"),
184
+ "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here.",
185
+ }
186
+ _write_json(input_dir / "tutorial_metadata.json", metadata)
187
+
188
+
189
+ def _source_context_text(path: Path) -> str:
190
+ try:
191
+ raw = path.read_text(encoding="utf-8", errors="replace")
192
+ except Exception:
193
+ return f"{path.name}\nsha256={_sha256_file(path)}\nsize_bytes={path.stat().st_size}\n"
194
+ if path.suffix.lower() in {".html", ".htm", ".md", ".txt"}:
195
+ return _clean_markup_text(raw)
196
+ return re.sub(r"\s+", " ", raw).strip()
197
+
198
+
199
+ def _ensure_public_input_footprint(input_dir: Path, source_paths: list[Path]) -> str:
200
+ current = _tree_file_bytes(input_dir)
201
+ if current >= MIN_PUBLIC_TASK_DATA_BYTES:
202
+ return f"public input footprint is {current} bytes; no context expansion needed"
203
+ context_path = input_dir / "source_context_windows.jsonl"
204
+ base = current - (context_path.stat().st_size if context_path.is_file() else 0)
205
+ context_path.unlink(missing_ok=True)
206
+ rows: list[dict[str, Any]] = []
207
+ for source in source_paths:
208
+ if not source.is_file() or source.resolve() == context_path.resolve():
209
+ continue
210
+ text = _source_context_text(source)
211
+ if not text:
212
+ continue
213
+ start = 0
214
+ width = 1800
215
+ stride = 900
216
+ while start < len(text):
217
+ end = min(len(text), start + width)
218
+ rows.append({
219
+ "source_file": source.relative_to(input_dir).as_posix() if source.is_relative_to(input_dir) else source.name,
220
+ "source_sha256": _sha256_file(source),
221
+ "start_char": start,
222
+ "end_char": end,
223
+ "text": text[start:end],
224
+ })
225
+ if end == len(text):
226
+ break
227
+ start += stride
228
+ if not rows:
229
+ raise ValueError("public input footprint expansion has no public source text")
230
+ input_dir.mkdir(parents=True, exist_ok=True)
231
+ rows_written = 0
232
+ target_extra = MIN_PUBLIC_TASK_DATA_BYTES - max(0, base)
233
+ with context_path.open("w", encoding="utf-8") as handle:
234
+ cycle = 0
235
+ while handle.tell() < target_extra or rows_written < 100:
236
+ row = dict(rows[rows_written % len(rows)])
237
+ row["window_id"] = rows_written + 1
238
+ row["cycle"] = cycle
239
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
240
+ rows_written += 1
241
+ if rows_written % len(rows) == 0:
242
+ cycle += 1
243
+ handle.flush()
244
+ return f"wrote input/source_context_windows.jsonl with {rows_written} public-source windows and {context_path.stat().st_size} bytes"
245
+
246
+
247
+ def _write_software_manifest(software_dir: Path, spec_payload: dict[str, Any]) -> None:
248
+ if str(spec_payload.get("workflow_kind") or "") != "software_tutorial_doc_audit":
249
+ return
250
+ software_dir.mkdir(parents=True, exist_ok=True)
251
+ software_name = str(spec_payload.get("software_name") or "").strip()
252
+ executables = [str(item).strip() for item in spec_payload.get("executables") or [] if str(item).strip()]
253
+ system_packages = [str(item).strip() for item in spec_payload.get("required_system_packages") or [] if str(item).strip()]
254
+ source_urls = [str(item).strip() for item in spec_payload.get("source_urls") or [] if str(item).strip()]
255
+ _write_json(software_dir / "software_manifest.json", {
256
+ "software_name": software_name,
257
+ "executables": executables,
258
+ "required_system_packages": system_packages,
259
+ "official_sources": source_urls,
260
+ "solve_time_network": "disabled",
261
+ "python_wrapper_only": False,
262
+ "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs.",
263
+ })
264
+ with (software_dir / "command_examples.csv").open("w", encoding="utf-8", newline="") as handle:
265
+ writer = csv.DictWriter(handle, fieldnames=["term", "kind", "software_name"])
266
+ writer.writeheader()
267
+ for term in spec_payload.get("code_terms") or []:
268
+ writer.writerow({"term": str(term), "kind": "code_term", "software_name": software_name})
269
+ for exe in executables:
270
+ writer.writerow({"term": exe, "kind": "executable", "software_name": software_name})
271
+
272
+
273
+ def software_tutorial_outputs(input_dir: Path, output_dir: Path) -> None:
274
+ spec = _read_json(input_dir / "analysis_spec.json")
275
+ source_file = str(spec["source_file"])
276
+ source_text = (input_dir / source_file).read_text(encoding="utf-8", errors="replace")
277
+ clean_text = _clean_markup_text(source_text)
278
+ headings = _extract_headings(source_text)
279
+ code_blocks = _extract_code_blocks(source_text)
280
+ window_rows: list[dict[str, str]] = []
281
+ with (input_dir / str(spec["input_file"])).open("r", encoding="utf-8", newline="") as handle:
282
+ window_rows = list(csv.DictReader(handle))
283
+ output_dir.mkdir(parents=True, exist_ok=True)
284
+
285
+ with (output_dir / "section_outline.csv").open("w", encoding="utf-8", newline="") as handle:
286
+ fieldnames = ["rank", "heading_level", "heading_text", "slug"]
287
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
288
+ writer.writeheader()
289
+ for rank, heading in enumerate(headings, start=1):
290
+ writer.writerow({
291
+ "rank": rank,
292
+ "heading_level": heading["level"],
293
+ "heading_text": heading["text"],
294
+ "slug": _heading_slug(heading["text"]),
295
+ })
296
+
297
+ all_terms: list[tuple[str, str]] = []
298
+ for term in spec.get("required_terms") or []:
299
+ all_terms.append((str(term), "required"))
300
+ for term in spec.get("code_terms") or []:
301
+ if str(term) not in {item[0] for item in all_terms}:
302
+ all_terms.append((str(term), "code"))
303
+ code_text = "\n".join(code_blocks)
304
+ term_rows: list[dict[str, Any]] = []
305
+ for term, category in all_terms:
306
+ term_rows.append({
307
+ "term": term,
308
+ "category": category,
309
+ "count": _term_count(clean_text, term),
310
+ "first_window": _first_window(window_rows, term),
311
+ "appears_in_code": "true" if term.lower() in code_text.lower() else "false",
312
+ })
313
+ term_rows.sort(key=lambda row: (str(row["category"]), str(row["term"]).lower()))
314
+ with (output_dir / "keyword_inventory.csv").open("w", encoding="utf-8", newline="") as handle:
315
+ fieldnames = ["term", "category", "count", "first_window", "appears_in_code"]
316
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
317
+ writer.writeheader()
318
+ for row in term_rows:
319
+ writer.writerow(row)
320
+
321
+ code_terms = [str(item).lower() for item in spec.get("code_terms") or []]
322
+ with (output_dir / "code_block_inventory.csv").open("w", encoding="utf-8", newline="") as handle:
323
+ fieldnames = ["block_index", "line_count", "char_count", "contains_code_term", "first_line"]
324
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
325
+ writer.writeheader()
326
+ for index, block in enumerate(code_blocks, start=1):
327
+ lines = [line for line in block.splitlines() if line.strip()]
328
+ contains = any(term and term in block.lower() for term in code_terms)
329
+ writer.writerow({
330
+ "block_index": index,
331
+ "line_count": len(lines),
332
+ "char_count": len(block),
333
+ "contains_code_term": "true" if contains else "false",
334
+ "first_line": lines[0][:200] if lines else "",
335
+ })
336
+
337
+ keyword_total = sum(int(row["count"]) for row in term_rows)
338
+ required_found = sum(1 for row in term_rows if row["category"] == "required" and int(row["count"]) > 0)
339
+ top_keyword = None
340
+ if term_rows:
341
+ top = max(term_rows, key=lambda row: (int(row["count"]), str(row["term"]).lower()))
342
+ top_keyword = str(top["term"]) if int(top["count"]) > 0 else None
343
+ summary = {
344
+ "software_name": str(spec.get("software_name") or ""),
345
+ "source_file": source_file,
346
+ "window_count": len(window_rows),
347
+ "heading_count": len(headings),
348
+ "code_block_count": len(code_blocks),
349
+ "keyword_total": keyword_total,
350
+ "unique_required_terms_found": required_found,
351
+ "top_keyword": top_keyword,
352
+ "source_character_count": len(clean_text),
353
+ }
354
+ _write_json(output_dir / "summary.json", summary)
355
+
356
+
357
+ def geojson_outputs(input_dir: Path, output_dir: Path) -> None:
358
+ payload = _read_json(input_dir / "events.geojson")
359
+ features = payload.get("features") if isinstance(payload, dict) else []
360
+ rows: list[dict[str, Any]] = []
361
+ for feature in features:
362
+ if not isinstance(feature, dict):
363
+ continue
364
+ props = feature.get("properties") if isinstance(feature.get("properties"), dict) else {}
365
+ geom = feature.get("geometry") if isinstance(feature.get("geometry"), dict) else {}
366
+ coords = geom.get("coordinates") if isinstance(geom.get("coordinates"), list) else []
367
+ mag = props.get("mag")
368
+ try:
369
+ mag = float(mag) if mag is not None else None
370
+ except (TypeError, ValueError):
371
+ mag = None
372
+ depth = None
373
+ if len(coords) >= 3:
374
+ try:
375
+ depth = float(coords[2])
376
+ except (TypeError, ValueError):
377
+ depth = None
378
+ time_ms = props.get("time")
379
+ date_utc = "unknown"
380
+ if isinstance(time_ms, (int, float)):
381
+ date_utc = dt.datetime.utcfromtimestamp(time_ms / 1000).date().isoformat()
382
+ rows.append({
383
+ "id": feature.get("id") or props.get("code") or "",
384
+ "mag": mag,
385
+ "depth": depth,
386
+ "place": str(props.get("place") or ""),
387
+ "region": _stable_region(str(props.get("place") or "")),
388
+ "date_utc": date_utc,
389
+ "feature": feature,
390
+ })
391
+ output_dir.mkdir(parents=True, exist_ok=True)
392
+ mags = [row["mag"] for row in rows if row["mag"] is not None]
393
+ depths = [row["depth"] for row in rows if row["depth"] is not None]
394
+ summary = {
395
+ "event_count": len(rows),
396
+ "magnitude": {
397
+ "count": len(mags),
398
+ "min": round(min(mags), 6) if mags else None,
399
+ "max": round(max(mags), 6) if mags else None,
400
+ "mean": round(statistics.fmean(mags), 6) if mags else None,
401
+ "median": round(statistics.median(mags), 6) if mags else None,
402
+ },
403
+ "depth_km": {
404
+ "count": len(depths),
405
+ "min": round(min(depths), 6) if depths else None,
406
+ "max": round(max(depths), 6) if depths else None,
407
+ "mean": round(statistics.fmean(depths), 6) if depths else None,
408
+ },
409
+ "time_range_utc": {
410
+ "start_date": min((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None),
411
+ "end_date": max((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None),
412
+ },
413
+ "quality_flags": {
414
+ "missing_magnitude": sum(1 for row in rows if row["mag"] is None),
415
+ "missing_depth": sum(1 for row in rows if row["depth"] is None),
416
+ "unique_regions": len({row["region"] for row in rows}),
417
+ },
418
+ }
419
+ _write_json(output_dir / "summary.json", summary)
420
+
421
+ grouped: dict[tuple[str, str], list[dict[str, Any]]] = {}
422
+ for row in rows:
423
+ grouped.setdefault((_mag_bin(row["mag"]), _depth_bin(row["depth"])), []).append(row)
424
+ with (output_dir / "magnitude_depth_bins.csv").open("w", encoding="utf-8", newline="") as handle:
425
+ fieldnames = ["mag_bin", "depth_bin", "event_count", "mean_magnitude", "max_magnitude"]
426
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
427
+ writer.writeheader()
428
+ for (mag_bin, depth_bin), group in sorted(grouped.items()):
429
+ group_mags = [row["mag"] for row in group if row["mag"] is not None]
430
+ writer.writerow({
431
+ "mag_bin": mag_bin,
432
+ "depth_bin": depth_bin,
433
+ "event_count": len(group),
434
+ "mean_magnitude": f"{statistics.fmean(group_mags):.6f}" if group_mags else "",
435
+ "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "",
436
+ })
437
+
438
+ daily: dict[tuple[str, str], list[dict[str, Any]]] = {}
439
+ for row in rows:
440
+ daily.setdefault((row["region"], row["date_utc"]), []).append(row)
441
+ with (output_dir / "region_daily_counts.csv").open("w", encoding="utf-8", newline="") as handle:
442
+ fieldnames = ["region", "date_utc", "event_count", "max_magnitude"]
443
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
444
+ writer.writeheader()
445
+ for (region, date_utc), group in sorted(daily.items()):
446
+ group_mags = [row["mag"] for row in group if row["mag"] is not None]
447
+ writer.writerow({
448
+ "region": region,
449
+ "date_utc": date_utc,
450
+ "event_count": len(group),
451
+ "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "",
452
+ })
453
+
454
+ filtered = [row["feature"] for row in rows if row["mag"] is not None and row["mag"] >= 4.5]
455
+ _write_json(output_dir / "filtered_events.geojson", {"type": "FeatureCollection", "features": filtered})
456
+
457
+
458
+ def csv_time_series_outputs(input_dir: Path, output_dir: Path) -> None:
459
+ spec = _read_json(input_dir / "analysis_spec.json")
460
+ csv_name = spec["input_file"]
461
+ date_column = spec["date_column"]
462
+ value_column = spec["value_column"]
463
+ rows: list[dict[str, Any]] = []
464
+ with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle:
465
+ lines = [line for line in raw_handle if not line.lstrip().startswith("#")]
466
+ reader = csv.DictReader(lines)
467
+ for item in reader:
468
+ raw_date = item.get(date_column, "")
469
+ try:
470
+ day = dt.date.fromisoformat(raw_date)
471
+ except ValueError:
472
+ if raw_date.isdigit() and len(raw_date) == 4:
473
+ day = dt.date(int(raw_date), 1, 1)
474
+ else:
475
+ continue
476
+ raw_value = item.get(value_column, "")
477
+ try:
478
+ value = float(raw_value)
479
+ except (TypeError, ValueError):
480
+ value = None
481
+ rows.append({"date": day, "value": value, "raw": item})
482
+ rows.sort(key=lambda item: item["date"])
483
+ valid = [row for row in rows if row["value"] is not None]
484
+ output_dir.mkdir(parents=True, exist_ok=True)
485
+ monthly: dict[str, list[float]] = {}
486
+ for row in valid:
487
+ key = row["date"].strftime("%Y-%m")
488
+ monthly.setdefault(key, []).append(row["value"])
489
+ with (output_dir / "monthly_statistics.csv").open("w", encoding="utf-8", newline="") as handle:
490
+ fieldnames = ["month", "count", "mean", "median", "min", "max"]
491
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
492
+ writer.writeheader()
493
+ for month, values in sorted(monthly.items()):
494
+ writer.writerow({
495
+ "month": month,
496
+ "count": len(values),
497
+ "mean": f"{statistics.fmean(values):.6f}",
498
+ "median": f"{statistics.median(values):.6f}",
499
+ "min": f"{min(values):.6f}",
500
+ "max": f"{max(values):.6f}",
501
+ })
502
+ existing_dates = {row["date"] for row in rows}
503
+ missing_days: list[dt.date] = []
504
+ if rows:
505
+ day = rows[0]["date"]
506
+ while day <= rows[-1]["date"]:
507
+ if day.weekday() < 5 and day not in existing_dates:
508
+ missing_days.append(day)
509
+ day += dt.timedelta(days=1)
510
+ with (output_dir / "missing_business_days.csv").open("w", encoding="utf-8", newline="") as handle:
511
+ writer = csv.DictWriter(handle, fieldnames=["date"])
512
+ writer.writeheader()
513
+ for day in missing_days:
514
+ writer.writerow({"date": day.isoformat()})
515
+ with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle:
516
+ writer = csv.DictWriter(handle, fieldnames=["date", "value"])
517
+ writer.writeheader()
518
+ for row in valid:
519
+ writer.writerow({"date": row["date"].isoformat(), "value": f"{row['value']:.6f}"})
520
+ values = [row["value"] for row in valid]
521
+ summary = {
522
+ "series_name": spec.get("series_name", value_column),
523
+ "row_count": len(rows),
524
+ "valid_value_count": len(valid),
525
+ "missing_value_count": len(rows) - len(valid),
526
+ "missing_business_day_count": len(missing_days),
527
+ "date_range": {
528
+ "start": rows[0]["date"].isoformat() if rows else None,
529
+ "end": rows[-1]["date"].isoformat() if rows else None,
530
+ },
531
+ "value": {
532
+ "min": round(min(values), 6) if values else None,
533
+ "max": round(max(values), 6) if values else None,
534
+ "mean": round(statistics.fmean(values), 6) if values else None,
535
+ "median": round(statistics.median(values), 6) if values else None,
536
+ },
537
+ }
538
+ _write_json(output_dir / "summary.json", summary)
539
+
540
+
541
+ def _aggregate_annual_rows(rows: list[dict[str, Any]], aggregation: str) -> list[dict[str, Any]]:
542
+ if not aggregation:
543
+ return rows
544
+ grouped: dict[int, list[float]] = {}
545
+ for row in rows:
546
+ grouped.setdefault(int(row["year"]), []).append(float(row["value"]))
547
+ aggregated: list[dict[str, Any]] = []
548
+ for year, values in sorted(grouped.items()):
549
+ if aggregation == "mean":
550
+ value = statistics.fmean(values)
551
+ elif aggregation == "median":
552
+ value = statistics.median(values)
553
+ elif aggregation == "max":
554
+ value = max(values)
555
+ elif aggregation == "min":
556
+ value = min(values)
557
+ elif aggregation == "count":
558
+ value = float(len(values))
559
+ else:
560
+ raise ValueError(f"unsupported year_aggregation for csv_annual_series_audit: {aggregation}")
561
+ aggregated.append({"year": year, "value": value})
562
+ return aggregated
563
+
564
+
565
+ def csv_annual_series_outputs(input_dir: Path, output_dir: Path) -> None:
566
+ spec = _read_json(input_dir / "analysis_spec.json")
567
+ csv_name = spec["input_file"]
568
+ year_column = spec["year_column"]
569
+ value_column = spec["value_column"]
570
+ # Optional: derive the year from an ISO-8601 timestamp column (e.g. USGS FDSN
571
+ # `time` = "2022-06-29T19:17:58.929Z") instead of parsing an integer year.
572
+ # When unset, behaviour is unchanged (integer year column).
573
+ year_from_timestamp = bool(spec.get("year_from_timestamp", False))
574
+ year_aggregation = str(spec.get("year_aggregation") or "").strip().lower()
575
+ raw_rows: list[dict[str, Any]] = []
576
+ with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle:
577
+ lines = [line for line in raw_handle if not line.lstrip().startswith("#")]
578
+ reader = csv.DictReader(lines)
579
+ for item in reader:
580
+ raw_year = str(item.get(year_column, "")).strip()
581
+ try:
582
+ if year_from_timestamp:
583
+ # Take the leading 4-digit year of an ISO timestamp/date.
584
+ match = re.match(r"\s*(\d{4})", raw_year)
585
+ if not match:
586
+ continue
587
+ year = int(match.group(1))
588
+ else:
589
+ year = int(raw_year)
590
+ value = float(str(item.get(value_column, "")).strip())
591
+ except (TypeError, ValueError):
592
+ continue
593
+ raw_rows.append({"year": year, "value": value})
594
+ rows = _aggregate_annual_rows(raw_rows, year_aggregation)
595
+ rows.sort(key=lambda item: item["year"])
596
+ output_dir.mkdir(parents=True, exist_ok=True)
597
+ decades: dict[str, list[float]] = {}
598
+ for row in rows:
599
+ decade_start = (row["year"] // 10) * 10
600
+ decades.setdefault(f"{decade_start}s", []).append(row["value"])
601
+ with (output_dir / "decadal_statistics.csv").open("w", encoding="utf-8", newline="") as handle:
602
+ fieldnames = [
603
+ "decade_start",
604
+ "start_year",
605
+ "end_year",
606
+ "count",
607
+ "mean_departure",
608
+ "median_departure",
609
+ "min_departure",
610
+ "max_departure",
611
+ "sample_std_departure",
612
+ ]
613
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
614
+ writer.writeheader()
615
+ for decade, values in sorted(decades.items()):
616
+ decade_start = int(decade.rstrip("s"))
617
+ years = [row["year"] for row in rows if decade_start <= row["year"] <= decade_start + 9]
618
+ writer.writerow({
619
+ "decade_start": decade_start,
620
+ "start_year": min(years),
621
+ "end_year": max(years),
622
+ "count": len(values),
623
+ "mean_departure": f"{statistics.fmean(values):.6f}",
624
+ "median_departure": f"{statistics.median(values):.6f}",
625
+ "min_departure": f"{min(values):.6f}",
626
+ "max_departure": f"{max(values):.6f}",
627
+ "sample_std_departure": f"{statistics.stdev(values):.6f}" if len(values) >= 2 else "",
628
+ })
629
+ threshold = float(spec.get("threshold", 1.0))
630
+ with (output_dir / "threshold_years.csv").open("w", encoding="utf-8", newline="") as handle:
631
+ fieldnames = ["rank", "year", "departure", "threshold"]
632
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
633
+ writer.writeheader()
634
+ rank = 1
635
+ for row in rows:
636
+ if row["value"] >= threshold:
637
+ writer.writerow({
638
+ "rank": rank,
639
+ "year": row["year"],
640
+ "departure": f"{row['value']:.6f}",
641
+ "threshold": f"{threshold:.6f}",
642
+ })
643
+ rank += 1
644
+ with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle:
645
+ writer = csv.DictWriter(handle, fieldnames=["Year", "Departure from Average"])
646
+ writer.writeheader()
647
+ for row in rows:
648
+ writer.writerow({"Year": row["year"], "Departure from Average": f"{row['value']:.6f}"})
649
+ values = [row["value"] for row in rows]
650
+ threshold_rows = [row for row in rows if row["value"] >= threshold]
651
+ min_row = min(rows, key=lambda row: row["value"]) if rows else None
652
+ max_row = max(rows, key=lambda row: row["value"]) if rows else None
653
+ summary = {
654
+ "series_name": spec.get("series_name", value_column),
655
+ "row_count": len(rows),
656
+ "year_range": {
657
+ "start": rows[0]["year"] if rows else None,
658
+ "end": rows[-1]["year"] if rows else None,
659
+ },
660
+ "value": {
661
+ "min": round(min(values), 6) if values else None,
662
+ "min_year": min_row["year"] if min_row else None,
663
+ "max": round(max(values), 6) if values else None,
664
+ "max_year": max_row["year"] if max_row else None,
665
+ "mean": round(statistics.fmean(values), 6) if values else None,
666
+ "median": round(statistics.median(values), 6) if values else None,
667
+ "sample_std": round(statistics.stdev(values), 6) if len(values) >= 2 else None,
668
+ },
669
+ "threshold": threshold,
670
+ "years_at_or_above_threshold": len(threshold_rows),
671
+ "first_threshold_year": threshold_rows[0]["year"] if threshold_rows else None,
672
+ "last_threshold_year": threshold_rows[-1]["year"] if threshold_rows else None,
673
+ }
674
+ if year_aggregation:
675
+ summary["year_aggregation"] = year_aggregation
676
+ summary["source_row_count"] = len(raw_rows)
677
+ _write_json(output_dir / "summary.json", summary)
678
+
679
+
20260907-002650-transport-safety-0ac894/solution/internal/workflow_runtime.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from workflow_adapters_runtime import software_tutorial_outputs
3
+
4
+ def run_reference(input_dir: Path, output_dir: Path) -> None:
5
+ software_tutorial_outputs(input_dir, output_dir)
20260907-002650-transport-safety-0ac894/solution/reference_solution.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+
8
+ def main() -> int:
9
+ parser = argparse.ArgumentParser()
10
+ parser.add_argument("--input", required=True)
11
+ parser.add_argument("--output", required=True)
12
+ args = parser.parse_args()
13
+ sys.path.insert(0, str(Path(__file__).resolve().parent / "internal"))
14
+ from workflow_runtime import run_reference
15
+ run_reference(Path(args.input), Path(args.output))
16
+ return 0
17
+
18
+
19
+ if __name__ == "__main__":
20
+ raise SystemExit(main())
20260907-002650-transport-safety-0ac894/solution/solve.sh ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ INPUT_DIR="${1:-/workspace/input}"
4
+ OUTPUT_DIR="${2:-/workspace/output}"
5
+ SOLUTION_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
6
+ mkdir -p "${OUTPUT_DIR}"
7
+ python "${SOLUTION_DIR}/reference_solution.py" --input "${INPUT_DIR}" --output "${OUTPUT_DIR}"
20260907-002650-transport-safety-0ac894/task.toml ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ schema_version = "1.3"
2
+ artifacts = ["/workspace/output/summary.json", "/workspace/output/section_outline.csv", "/workspace/output/keyword_inventory.csv", "/workspace/output/code_block_inventory.csv"]
3
+
4
+ [task]
5
+ name = "ale-cli/20260907-002650-transport-safety-0ac894"
6
+ 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"
7
+ keywords = ["agents-last-exam", "ale-cli", "deterministic-evaluator", "linux-cli", "software-tutorial-doc-audit", "transport-safety"]
8
+
9
+ [metadata]
10
+ benchmark = "ale_cli"
11
+ source_format = "ale_cli_official_style"
12
+ converter = "ale_cli_to_harbor"
13
+ source_task_key = "20260907-002650_transport_safety_0ac894"
14
+ task_id = "transport_safety/sumo_plainxml_document_inventory_audit__20260907-002650_transport_safety_0ac894"
15
+ domain = "transport_safety"
16
+ task = "sumo_plainxml_document_inventory_audit"
17
+ variant = "base"
18
+ oracle_available = true
19
+ scoring_method = "deterministic_hidden_evaluator"
20
+ required_outputs = ["summary.json", "section_outline.csv", "keyword_inventory.csv", "code_block_inventory.csv"]
21
+
22
+ [agent]
23
+ timeout_sec = 1800
24
+
25
+ [verifier]
26
+ timeout_sec = 600
27
+ environment_mode = "separate"
28
+
29
+ [verifier.environment]
30
+ build_timeout_sec = 900.0
31
+ network_mode = "public"
32
+ os = "linux"
33
+ cpus = 1
34
+ memory_mb = 2048
35
+ storage_mb = 4096
36
+ gpus = 0
37
+
38
+ [environment]
39
+ build_timeout_sec = 1200.0
40
+ network_mode = "public"
41
+ os = "linux"
42
+ cpus = 2
43
+ memory_mb = 4096
44
+ storage_mb = 10240
45
+ gpus = 0
20260907-002650-transport-safety-0ac894/tests/Dockerfile ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ WORKDIR /workspace
4
+
5
+ COPY . /tests
6
+ RUN chmod +x /tests/test.sh
20260907-002650-transport-safety-0ac894/tests/evaluator_runner.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import importlib.util
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+
11
+ def read_json(path: Path) -> Any:
12
+ return json.loads(path.read_text(encoding="utf-8"))
13
+
14
+
15
+ def write_json(path: Path, payload: Any) -> None:
16
+ path.parent.mkdir(parents=True, exist_ok=True)
17
+ path.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
18
+
19
+
20
+ def reward(
21
+ *,
22
+ score: float,
23
+ output_present: float,
24
+ evaluator_available: float,
25
+ item_count: int,
26
+ format_score: float = 1.0,
27
+ ) -> dict[str, float]:
28
+ clipped = max(0.0, min(1.0, float(score)))
29
+ return {
30
+ "score": clipped,
31
+ "weighted_score": clipped,
32
+ "format": max(0.0, min(1.0, float(format_score))),
33
+ "output_present": max(0.0, min(1.0, float(output_present))),
34
+ "evaluator_available": max(0.0, min(1.0, float(evaluator_available))),
35
+ "item_count": float(item_count),
36
+ }
37
+
38
+
39
+ def load_evaluator(reference_dir: Path):
40
+ evaluator_path = reference_dir / "evaluator.py"
41
+ spec = importlib.util.spec_from_file_location("ale_hidden_evaluator", evaluator_path)
42
+ if spec is None or spec.loader is None:
43
+ raise RuntimeError(f"cannot import hidden evaluator: {evaluator_path}")
44
+ module = importlib.util.module_from_spec(spec)
45
+ spec.loader.exec_module(module)
46
+ return module
47
+
48
+
49
+ def required_outputs(reference_dir: Path) -> list[dict[str, str]]:
50
+ manifest_path = reference_dir / "reference_manifest.json"
51
+ if not manifest_path.is_file():
52
+ return []
53
+ manifest = read_json(manifest_path)
54
+ rows = manifest.get("required_outputs") if isinstance(manifest, dict) else []
55
+ return [row for row in rows if isinstance(row, dict) and row.get("path")]
56
+
57
+
58
+ def main() -> int:
59
+ parser = argparse.ArgumentParser(description="Run a hidden ALE CLI evaluator in Harbor.")
60
+ parser.add_argument("--output-dir", type=Path, required=True)
61
+ parser.add_argument("--reference-dir", type=Path, required=True)
62
+ parser.add_argument("--reward-json", type=Path, required=True)
63
+ parser.add_argument("--details-json", type=Path, required=True)
64
+ args = parser.parse_args()
65
+
66
+ required = required_outputs(args.reference_dir)
67
+ present = [row for row in required if (args.output_dir / str(row["path"])).is_file()]
68
+ item_count = len(required)
69
+ if not required:
70
+ write_json(args.reward_json, reward(score=0.0, output_present=0.0, evaluator_available=0.0, item_count=0, format_score=0.0))
71
+ write_json(args.details_json, {"ok": False, "error": "reference_manifest.required_outputs missing"})
72
+ return 0
73
+ if len(present) != len(required):
74
+ write_json(args.reward_json, reward(score=0.0, output_present=0.0, evaluator_available=1.0, item_count=item_count))
75
+ write_json(args.details_json, {"ok": True, "reason": "missing required outputs", "present": [row["path"] for row in present]})
76
+ return 0
77
+ try:
78
+ module = load_evaluator(args.reference_dir)
79
+ result = module.evaluate(args.output_dir, args.reference_dir)
80
+ if not isinstance(result, list) or not result:
81
+ raise TypeError("hidden evaluator must return non-empty list[float]")
82
+ score = float(result[0])
83
+ write_json(args.reward_json, reward(score=score, output_present=1.0, evaluator_available=1.0, item_count=item_count))
84
+ write_json(args.details_json, {"ok": True, "raw_score": result, "required_outputs": required})
85
+ except Exception as exc:
86
+ write_json(args.reward_json, reward(score=0.0, output_present=1.0, evaluator_available=0.0, item_count=item_count))
87
+ write_json(args.details_json, {"ok": False, "error": f"{type(exc).__name__}: {exc}", "required_outputs": required})
88
+ return 0
89
+
90
+
91
+ if __name__ == "__main__":
92
+ raise SystemExit(main())
20260907-002650-transport-safety-0ac894/tests/reference/__pycache__/evaluator.cpython-312.pyc ADDED
Binary file (6.23 kB). View file
 
20260907-002650-transport-safety-0ac894/tests/reference/evaluator.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import json
5
+ import math
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+
10
+ def _load_json(path: Path) -> Any:
11
+ with path.open("r", encoding="utf-8") as handle:
12
+ return json.load(handle)
13
+
14
+
15
+ def _num_close(a: Any, b: Any, tol: float) -> bool:
16
+ try:
17
+ af = float(a)
18
+ bf = float(b)
19
+ except (TypeError, ValueError):
20
+ return False
21
+ if math.isnan(af) and math.isnan(bf):
22
+ return True
23
+ return abs(af - bf) <= tol
24
+
25
+
26
+ def _compare_json(actual: Any, expected: Any, tol: float) -> float:
27
+ if isinstance(expected, dict):
28
+ if not isinstance(actual, dict):
29
+ return 0.0
30
+ if not expected:
31
+ return 1.0
32
+ scores = []
33
+ for key, exp_value in expected.items():
34
+ if key not in actual:
35
+ scores.append(0.0)
36
+ else:
37
+ scores.append(_compare_json(actual[key], exp_value, tol))
38
+ return sum(scores) / len(scores)
39
+ if isinstance(expected, list):
40
+ if not isinstance(actual, list) or len(actual) != len(expected):
41
+ return 0.0
42
+ if not expected:
43
+ return 1.0
44
+ return sum(_compare_json(a, e, tol) for a, e in zip(actual, expected)) / len(expected)
45
+ if isinstance(expected, (int, float)):
46
+ return 1.0 if _num_close(actual, expected, tol) else 0.0
47
+ return 1.0 if actual == expected else 0.0
48
+
49
+
50
+ def _read_csv(path: Path) -> list[dict[str, str]]:
51
+ with path.open("r", encoding="utf-8", newline="") as handle:
52
+ return list(csv.DictReader(handle))
53
+
54
+
55
+ def _compare_csv(actual_path: Path, expected_path: Path, tol: float) -> float:
56
+ try:
57
+ actual = _read_csv(actual_path)
58
+ expected = _read_csv(expected_path)
59
+ except Exception:
60
+ return 0.0
61
+ if len(actual) != len(expected):
62
+ return 0.0
63
+ if not expected:
64
+ return 1.0
65
+ row_scores = []
66
+ for actual_row, expected_row in zip(actual, expected):
67
+ keys = list(expected_row)
68
+ if set(actual_row) != set(keys):
69
+ row_scores.append(0.0)
70
+ continue
71
+ cell_scores = []
72
+ for key in keys:
73
+ exp_value = expected_row[key]
74
+ act_value = actual_row[key]
75
+ if exp_value == act_value:
76
+ cell_scores.append(1.0)
77
+ elif _num_close(act_value, exp_value, tol):
78
+ cell_scores.append(1.0)
79
+ else:
80
+ cell_scores.append(0.0)
81
+ row_scores.append(sum(cell_scores) / len(cell_scores) if cell_scores else 1.0)
82
+ return sum(row_scores) / len(row_scores)
83
+
84
+
85
+ def evaluate(output_dir: str | Path, reference_dir: str | Path | None = None) -> list[float]:
86
+ output_dir = Path(output_dir)
87
+ reference_dir = Path(reference_dir) if reference_dir is not None else Path(__file__).resolve().parent
88
+ manifest = _load_json(reference_dir / "reference_manifest.json")
89
+ tolerance = float(manifest.get("numeric_tolerance", 1e-9))
90
+ required = manifest.get("required_outputs") or []
91
+ if not required:
92
+ return [0.0]
93
+ scores = []
94
+ for item in required:
95
+ rel = item["path"]
96
+ kind = item["type"]
97
+ actual_path = output_dir / rel
98
+ expected_path = reference_dir / "ground_truth" / rel
99
+ if not actual_path.is_file() or not expected_path.is_file():
100
+ scores.append(0.0)
101
+ continue
102
+ try:
103
+ if kind == "json":
104
+ scores.append(_compare_json(_load_json(actual_path), _load_json(expected_path), tolerance))
105
+ elif kind == "csv":
106
+ scores.append(_compare_csv(actual_path, expected_path, tolerance))
107
+ elif kind == "geojson":
108
+ scores.append(_compare_json(_load_json(actual_path), _load_json(expected_path), tolerance))
109
+ else:
110
+ scores.append(1.0 if actual_path.read_bytes() == expected_path.read_bytes() else 0.0)
111
+ except Exception:
112
+ scores.append(0.0)
113
+ score = max(0.0, min(1.0, sum(scores) / len(scores)))
114
+ return [score]
20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/code_block_inventory.csv ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ block_index,line_count,char_count,contains_code_term,first_line
2
+ 1,31,1824,true,---
3
+ 2,1,50,false,If you also use connections and types the call is:
4
+ 3,31,1715,false,"The options used here, including their abbreviations, are documented on"
5
+ 4,27,6599,false,the straight brackets ('\[' and '\]')
6
+ 5,167,12846,true,"As you may notice, only the first node named ""0"", which is the node in"
7
+ 6,100,9194,false,"This will cause the nodes *id0*,*id23* and *id24* to be joined into a"
8
+ 7,30,2425,false,"Within this example, we have used explicit definitions of edges. An"
9
+ 8,2,90,false,"If you would like to disallow passenger cars and taxis, the following"
10
+ 9,22,3547,false,The definition of a lane contains the following optional attributes:
11
+ 10,21,1586,false,Defining this element for an edge will affect all lanes of the edge that
12
+ 11,10,564,false,What happens here is the following: 30meters from its begin
13
+ 12,10,585,false,There are several things to note:
14
+ 13,16,1827,false,The definition of a split uses the following attributes:
15
+ 14,11,633,false,Manual specification of roundabouts is a useful supplement for the
16
+ 15,6,278,false,In the above input the inner-most lanes of edges *a* and *b* are
17
+ 16,21,1195,false,It is also possible to remove all edges of a specific type (see below)
18
+ 17,1,96,false,The according types file looks like this (see [SUMO edge type file](../SUMO_edge_type_file.md)):
19
+ 18,8,429,false,"As you can see, we have joined the edges into three classes ""a"", ""b"","
20
+ 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)."
21
+ 20,14,1357,false,This tells [netconvert](../netconvert.md) not only that vehicles shall be
22
+ 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"
23
+ 22,16,1609,true,The attributes are the same as for the
24
+ 23,17,988,false,This will trigger all connections from edge with id `FROM_EDGE_ID` to be removed and re-guessed.
25
+ 24,9,574,false,"As you may see in the next picture, the horizontal edges within the"
26
+ 25,12,831,false,The built network looks like this:
27
+ 26,17,1168,false,"As one may see, it was necessary to prohibit all connections from a"
28
+ 27,45,3451,true,# Traffic Light Program Definition
29
+ 28,27,3881,false,The attributes are described in the following.
30
+ 29,7,1226,false,The attributes are described in the following.
20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/keyword_inventory.csv ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ term,category,count,first_window,appears_in_code
2
+ .net.xml,code,9,1,true
3
+ .rou.xml,code,0,,false
4
+ duarouter,code,0,,false
5
+ netedit,code,7,101,true
6
+ edge,required,242,8,true
7
+ network,required,52,1,true
8
+ node,required,105,7,true
9
+ route,required,4,107,true
10
+ vehicle,required,75,64,true
20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/section_outline.csv ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ rank,heading_level,heading_text,slug
2
+ 1,h1,Source 1: PlainXML.md,source_1_plainxml_md
3
+ 2,h1,Node Descriptions,node_descriptions
4
+ 3,h2,Traffic lights,traffic_lights
5
+ 4,h3,tlType,tltype
6
+ 5,h3,tlLayout,tllayout
7
+ 6,h2,Node types,node_types
8
+ 7,h2,Right-of-way,right_of_way
9
+ 8,h3,"rightOfWay=""default""",rightofway_default
10
+ 9,h3,"rightOfWay=""mixedPriority""",rightofway_mixedpriority
11
+ 10,h3,"rightOfWay=""edgePriority""",rightofway_edgepriority
12
+ 11,h3,"rightOfWay=""allwayStop""",rightofway_allwaystop
13
+ 12,h3,Special Cases,special_cases
14
+ 13,h3,Understanding right-of-way rules in a Network,understanding_right_of_way_rules_in_a_network
15
+ 14,h3,Modifying Right-of-Way,modifying_right_of_way
16
+ 15,h2,Fringe,fringe
17
+ 16,h2,Joining Nodes,joining_nodes
18
+ 17,h3,Reasons for joining node clusters,reasons_for_joining_node_clusters
19
+ 18,h3,Algorithm for joining node clusters,algorithm_for_joining_node_clusters
20
+ 19,h3,Specifying and excluding explicit joins,specifying_and_excluding_explicit_joins
21
+ 20,h3,Connections after joining nodes,connections_after_joining_nodes
22
+ 21,h1,Edge Descriptions,edge_descriptions
23
+ 22,h2,SpreadType,spreadtype
24
+ 23,h2,"Road access permissions (allow, disallow)",road_access_permissions_allow_disallow
25
+ 24,h2,Lane-specific Definitions,lane_specific_definitions
26
+ 25,h3,lane change restrictions,lane_change_restrictions
27
+ 26,h2,Stop Offsets,stop_offsets
28
+ 27,h2,Road Segment Refining,road_segment_refining
29
+ 28,h2,Roundabouts,roundabouts
30
+ 29,h2,Neighboring opposite-direction Lanes,neighboring_opposite_direction_lanes
31
+ 30,h2,Deleting edges or lanes,deleting_edges_or_lanes
32
+ 31,h1,Type Descriptions,type_descriptions
33
+ 32,h2,vehicle-class specific speed limits,vehicle_class_specific_speed_limits
34
+ 33,h2,speed on junction,speed_on_junction
35
+ 34,h1,Connection Descriptions,connection_descriptions
36
+ 35,h2,Explicitly setting which Edge / Lane is connected to which,explicitly_setting_which_edge_lane_is_connected_to_which
37
+ 36,h3,Edge-to-Edge connectivity,edge_to_edge_connectivity
38
+ 37,h3,Lane-to-Lane connectivity,lane_to_lane_connectivity
39
+ 38,h3,Deleting connections,deleting_connections
40
+ 39,h3,Patching connections and guessing again,patching_connections_and_guessing_again
41
+ 40,h3,Examples,examples
42
+ 41,h2,Setting Connection Priorities,setting_connection_priorities
43
+ 42,h2,Multiple connections from the same edge to the same target lane,multiple_connections_from_the_same_edge_to_the_same_target_lane
44
+ 43,h1,Traffic Light Program Definition,traffic_light_program_definition
45
+ 44,h2,traffic light definitions,traffic_light_definitions
46
+ 45,h2,controlled connections,controlled_connections
47
+ 46,h1,Pedestrian Crossings,pedestrian_crossings
48
+ 47,h1,Walking Areas,walking_areas
20260907-002650-transport-safety-0ac894/tests/reference/ground_truth/summary.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "software_name": "SUMO",
3
+ "source_file": "tutorial_source.html",
4
+ "window_count": 425,
5
+ "heading_count": 47,
6
+ "code_block_count": 29,
7
+ "keyword_total": 494,
8
+ "unique_required_terms_found": 5,
9
+ "top_keyword": "edge",
10
+ "source_character_count": 56655
11
+ }
20260907-002650-transport-safety-0ac894/tests/reference/internal/workflow_adapters_runtime.py ADDED
@@ -0,0 +1,679 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import datetime as dt
5
+ import html
6
+ import json
7
+ import math
8
+ import re
9
+ import shutil
10
+ import statistics
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+
15
+ def _read_json(path: Path) -> Any:
16
+ with path.open("r", encoding="utf-8") as handle:
17
+ return json.load(handle)
18
+
19
+
20
+ def _write_json(path: Path, payload: Any) -> None:
21
+ path.parent.mkdir(parents=True, exist_ok=True)
22
+ with path.open("w", encoding="utf-8") as handle:
23
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
24
+ handle.write("\n")
25
+
26
+ def _stable_region(place: str) -> str:
27
+ if not place:
28
+ return "unknown"
29
+ if "," in place:
30
+ return place.split(",")[-1].strip() or place.strip()
31
+ parts = place.split()
32
+ return " ".join(parts[-2:]) if len(parts) >= 2 else place.strip()
33
+
34
+
35
+ def _mag_bin(value: float | None) -> str:
36
+ if value is None or math.isnan(value):
37
+ return "unknown"
38
+ lower = math.floor(value)
39
+ upper = lower + 1
40
+ return f"{lower:.0f}-{upper:.0f}"
41
+
42
+
43
+ def _depth_bin(value: float | None) -> str:
44
+ if value is None or math.isnan(value):
45
+ return "unknown"
46
+ if value < 0:
47
+ return "<0"
48
+ if value < 10:
49
+ return "0-10"
50
+ if value < 30:
51
+ return "10-30"
52
+ if value < 70:
53
+ return "30-70"
54
+ if value < 300:
55
+ return "70-300"
56
+ return "300+"
57
+
58
+
59
+ def _clean_markup_text(raw: str) -> str:
60
+ text = re.sub(r"(?is)<(script|style|noscript)[^>]*>.*?</\1>", " ", raw)
61
+ text = re.sub(r"(?is)<br\s*/?>", "\n", text)
62
+ text = re.sub(r"(?is)</(p|div|li|tr|h[1-6]|pre)>", "\n", text)
63
+ text = re.sub(r"(?is)<[^>]+>", " ", text)
64
+ text = html.unescape(text)
65
+ text = re.sub(r"[ \t]+", " ", text)
66
+ text = re.sub(r"\n\s+", "\n", text)
67
+ return text.strip()
68
+
69
+
70
+ def _heading_slug(value: str) -> str:
71
+ slug = re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_")
72
+ return slug[:80] or "section"
73
+
74
+
75
+ def _extract_headings(raw: str) -> list[dict[str, str]]:
76
+ headings: list[dict[str, str]] = []
77
+ for match in re.finditer(r"(?is)<h([1-6])[^>]*>(.*?)</h\1>", raw):
78
+ text = _clean_markup_text(match.group(2))
79
+ if text:
80
+ headings.append({"level": f"h{match.group(1)}", "text": text})
81
+ if headings:
82
+ return headings
83
+ for line in raw.splitlines():
84
+ match = re.match(r"^(#{1,6})\s+(.+?)\s*$", line)
85
+ if match:
86
+ headings.append({"level": f"h{len(match.group(1))}", "text": match.group(2).strip()})
87
+ return headings
88
+
89
+
90
+ def _extract_code_blocks(raw: str) -> list[str]:
91
+ blocks: list[str] = []
92
+ for match in re.finditer(r"(?is)<pre[^>]*>(.*?)</pre>", raw):
93
+ text = _clean_markup_text(match.group(1))
94
+ if text:
95
+ blocks.append(text)
96
+ for match in re.finditer(r"(?is)<code[^>]*>(.*?)</code>", raw):
97
+ text = _clean_markup_text(match.group(1))
98
+ if text and text not in blocks:
99
+ blocks.append(text)
100
+ for match in re.finditer(r"(?s)```(?:[A-Za-z0-9_-]+)?\n(.*?)```", raw):
101
+ text = html.unescape(match.group(1).strip())
102
+ if text and text not in blocks:
103
+ blocks.append(text)
104
+ return blocks
105
+
106
+
107
+ def _window_rows(clean_text: str, *, width: int = 40, stride: int = 20) -> list[dict[str, Any]]:
108
+ words = re.findall(r"\S+", clean_text)
109
+ rows: list[dict[str, Any]] = []
110
+ if not words:
111
+ return rows
112
+ start = 0
113
+ while start < len(words):
114
+ end = min(start + width, len(words))
115
+ rows.append({
116
+ "window_id": len(rows) + 1,
117
+ "start_word": start,
118
+ "end_word": end,
119
+ "text": " ".join(words[start:end]),
120
+ })
121
+ if end == len(words):
122
+ break
123
+ start += stride
124
+ return rows
125
+
126
+
127
+ def _term_count(text: str, term: str) -> int:
128
+ term = term.strip()
129
+ if not term:
130
+ return 0
131
+ return len(re.findall(re.escape(term), text, flags=re.IGNORECASE))
132
+
133
+
134
+ def _first_window(windows: list[dict[str, Any]], term: str) -> str:
135
+ term_lower = term.lower()
136
+ for row in windows:
137
+ if term_lower in str(row.get("text") or "").lower():
138
+ return str(row.get("window_id") or "")
139
+ return ""
140
+
141
+
142
+ def _write_tutorial_public_inputs(input_dir: Path, source_path: Path, spec_payload: dict[str, Any]) -> None:
143
+ raw = source_path.read_text(encoding="utf-8", errors="replace")
144
+ # Tutorial examples may contain a maintainer's local Windows path. Keep
145
+ # the command semantics while preventing host-specific paths from entering
146
+ # the public task artifact.
147
+ sanitized_raw = re.sub(r"(?i)\b[A-Z]:\\(?:[^\\\r\n<>\"']+\\?)*[^\\\r\n<>\"']*", "./local.db", raw)
148
+ clean_text = _clean_markup_text(sanitized_raw)
149
+ windows = _window_rows(clean_text)
150
+ if len(windows) < 100:
151
+ raise ValueError(f"official tutorial source produced only {len(windows)} text windows; need at least 100")
152
+ required_terms = [str(item) for item in spec_payload.get("required_terms") or []]
153
+ code_terms = [str(item) for item in spec_payload.get("code_terms") or []]
154
+ input_dir.mkdir(parents=True, exist_ok=True)
155
+ destination = input_dir / str(spec_payload["source_file"])
156
+ # Always materialize the sanitized copy, including when the downloader
157
+ # already placed the source at the destination path.
158
+ destination.write_text(sanitized_raw, encoding="utf-8")
159
+ with (input_dir / str(spec_payload["input_file"])).open("w", encoding="utf-8", newline="") as handle:
160
+ fieldnames = ["window_id", "start_word", "end_word", "text", "contains_code_term", "matched_required_terms"]
161
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
162
+ writer.writeheader()
163
+ for row in windows:
164
+ text = str(row["text"])
165
+ matched = [term for term in required_terms if term.lower() in text.lower()]
166
+ contains_code = any(term.lower() in text.lower() for term in code_terms)
167
+ writer.writerow({
168
+ "window_id": row["window_id"],
169
+ "start_word": row["start_word"],
170
+ "end_word": row["end_word"],
171
+ "text": text,
172
+ "contains_code_term": "true" if contains_code else "false",
173
+ "matched_required_terms": "|".join(matched),
174
+ })
175
+ metadata = {
176
+ "software_name": spec_payload.get("software_name"),
177
+ "tutorial_url": spec_payload.get("tutorial_url"),
178
+ "source_urls": spec_payload.get("source_urls"),
179
+ "source_file": spec_payload.get("source_file"),
180
+ "window_file": spec_payload.get("input_file"),
181
+ "window_rule": spec_payload.get("window_rule"),
182
+ "required_terms": spec_payload.get("required_terms"),
183
+ "code_terms": spec_payload.get("code_terms"),
184
+ "note": "Provenance and public extraction rules only; scored aggregate values are intentionally not stored here.",
185
+ }
186
+ _write_json(input_dir / "tutorial_metadata.json", metadata)
187
+
188
+
189
+ def _source_context_text(path: Path) -> str:
190
+ try:
191
+ raw = path.read_text(encoding="utf-8", errors="replace")
192
+ except Exception:
193
+ return f"{path.name}\nsha256={_sha256_file(path)}\nsize_bytes={path.stat().st_size}\n"
194
+ if path.suffix.lower() in {".html", ".htm", ".md", ".txt"}:
195
+ return _clean_markup_text(raw)
196
+ return re.sub(r"\s+", " ", raw).strip()
197
+
198
+
199
+ def _ensure_public_input_footprint(input_dir: Path, source_paths: list[Path]) -> str:
200
+ current = _tree_file_bytes(input_dir)
201
+ if current >= MIN_PUBLIC_TASK_DATA_BYTES:
202
+ return f"public input footprint is {current} bytes; no context expansion needed"
203
+ context_path = input_dir / "source_context_windows.jsonl"
204
+ base = current - (context_path.stat().st_size if context_path.is_file() else 0)
205
+ context_path.unlink(missing_ok=True)
206
+ rows: list[dict[str, Any]] = []
207
+ for source in source_paths:
208
+ if not source.is_file() or source.resolve() == context_path.resolve():
209
+ continue
210
+ text = _source_context_text(source)
211
+ if not text:
212
+ continue
213
+ start = 0
214
+ width = 1800
215
+ stride = 900
216
+ while start < len(text):
217
+ end = min(len(text), start + width)
218
+ rows.append({
219
+ "source_file": source.relative_to(input_dir).as_posix() if source.is_relative_to(input_dir) else source.name,
220
+ "source_sha256": _sha256_file(source),
221
+ "start_char": start,
222
+ "end_char": end,
223
+ "text": text[start:end],
224
+ })
225
+ if end == len(text):
226
+ break
227
+ start += stride
228
+ if not rows:
229
+ raise ValueError("public input footprint expansion has no public source text")
230
+ input_dir.mkdir(parents=True, exist_ok=True)
231
+ rows_written = 0
232
+ target_extra = MIN_PUBLIC_TASK_DATA_BYTES - max(0, base)
233
+ with context_path.open("w", encoding="utf-8") as handle:
234
+ cycle = 0
235
+ while handle.tell() < target_extra or rows_written < 100:
236
+ row = dict(rows[rows_written % len(rows)])
237
+ row["window_id"] = rows_written + 1
238
+ row["cycle"] = cycle
239
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
240
+ rows_written += 1
241
+ if rows_written % len(rows) == 0:
242
+ cycle += 1
243
+ handle.flush()
244
+ return f"wrote input/source_context_windows.jsonl with {rows_written} public-source windows and {context_path.stat().st_size} bytes"
245
+
246
+
247
+ def _write_software_manifest(software_dir: Path, spec_payload: dict[str, Any]) -> None:
248
+ if str(spec_payload.get("workflow_kind") or "") != "software_tutorial_doc_audit":
249
+ return
250
+ software_dir.mkdir(parents=True, exist_ok=True)
251
+ software_name = str(spec_payload.get("software_name") or "").strip()
252
+ executables = [str(item).strip() for item in spec_payload.get("executables") or [] if str(item).strip()]
253
+ system_packages = [str(item).strip() for item in spec_payload.get("required_system_packages") or [] if str(item).strip()]
254
+ source_urls = [str(item).strip() for item in spec_payload.get("source_urls") or [] if str(item).strip()]
255
+ _write_json(software_dir / "software_manifest.json", {
256
+ "software_name": software_name,
257
+ "executables": executables,
258
+ "required_system_packages": system_packages,
259
+ "official_sources": source_urls,
260
+ "solve_time_network": "disabled",
261
+ "python_wrapper_only": False,
262
+ "note": "This task audits real official software documentation/source staged offline; Python helpers only validate outputs.",
263
+ })
264
+ with (software_dir / "command_examples.csv").open("w", encoding="utf-8", newline="") as handle:
265
+ writer = csv.DictWriter(handle, fieldnames=["term", "kind", "software_name"])
266
+ writer.writeheader()
267
+ for term in spec_payload.get("code_terms") or []:
268
+ writer.writerow({"term": str(term), "kind": "code_term", "software_name": software_name})
269
+ for exe in executables:
270
+ writer.writerow({"term": exe, "kind": "executable", "software_name": software_name})
271
+
272
+
273
+ def software_tutorial_outputs(input_dir: Path, output_dir: Path) -> None:
274
+ spec = _read_json(input_dir / "analysis_spec.json")
275
+ source_file = str(spec["source_file"])
276
+ source_text = (input_dir / source_file).read_text(encoding="utf-8", errors="replace")
277
+ clean_text = _clean_markup_text(source_text)
278
+ headings = _extract_headings(source_text)
279
+ code_blocks = _extract_code_blocks(source_text)
280
+ window_rows: list[dict[str, str]] = []
281
+ with (input_dir / str(spec["input_file"])).open("r", encoding="utf-8", newline="") as handle:
282
+ window_rows = list(csv.DictReader(handle))
283
+ output_dir.mkdir(parents=True, exist_ok=True)
284
+
285
+ with (output_dir / "section_outline.csv").open("w", encoding="utf-8", newline="") as handle:
286
+ fieldnames = ["rank", "heading_level", "heading_text", "slug"]
287
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
288
+ writer.writeheader()
289
+ for rank, heading in enumerate(headings, start=1):
290
+ writer.writerow({
291
+ "rank": rank,
292
+ "heading_level": heading["level"],
293
+ "heading_text": heading["text"],
294
+ "slug": _heading_slug(heading["text"]),
295
+ })
296
+
297
+ all_terms: list[tuple[str, str]] = []
298
+ for term in spec.get("required_terms") or []:
299
+ all_terms.append((str(term), "required"))
300
+ for term in spec.get("code_terms") or []:
301
+ if str(term) not in {item[0] for item in all_terms}:
302
+ all_terms.append((str(term), "code"))
303
+ code_text = "\n".join(code_blocks)
304
+ term_rows: list[dict[str, Any]] = []
305
+ for term, category in all_terms:
306
+ term_rows.append({
307
+ "term": term,
308
+ "category": category,
309
+ "count": _term_count(clean_text, term),
310
+ "first_window": _first_window(window_rows, term),
311
+ "appears_in_code": "true" if term.lower() in code_text.lower() else "false",
312
+ })
313
+ term_rows.sort(key=lambda row: (str(row["category"]), str(row["term"]).lower()))
314
+ with (output_dir / "keyword_inventory.csv").open("w", encoding="utf-8", newline="") as handle:
315
+ fieldnames = ["term", "category", "count", "first_window", "appears_in_code"]
316
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
317
+ writer.writeheader()
318
+ for row in term_rows:
319
+ writer.writerow(row)
320
+
321
+ code_terms = [str(item).lower() for item in spec.get("code_terms") or []]
322
+ with (output_dir / "code_block_inventory.csv").open("w", encoding="utf-8", newline="") as handle:
323
+ fieldnames = ["block_index", "line_count", "char_count", "contains_code_term", "first_line"]
324
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
325
+ writer.writeheader()
326
+ for index, block in enumerate(code_blocks, start=1):
327
+ lines = [line for line in block.splitlines() if line.strip()]
328
+ contains = any(term and term in block.lower() for term in code_terms)
329
+ writer.writerow({
330
+ "block_index": index,
331
+ "line_count": len(lines),
332
+ "char_count": len(block),
333
+ "contains_code_term": "true" if contains else "false",
334
+ "first_line": lines[0][:200] if lines else "",
335
+ })
336
+
337
+ keyword_total = sum(int(row["count"]) for row in term_rows)
338
+ required_found = sum(1 for row in term_rows if row["category"] == "required" and int(row["count"]) > 0)
339
+ top_keyword = None
340
+ if term_rows:
341
+ top = max(term_rows, key=lambda row: (int(row["count"]), str(row["term"]).lower()))
342
+ top_keyword = str(top["term"]) if int(top["count"]) > 0 else None
343
+ summary = {
344
+ "software_name": str(spec.get("software_name") or ""),
345
+ "source_file": source_file,
346
+ "window_count": len(window_rows),
347
+ "heading_count": len(headings),
348
+ "code_block_count": len(code_blocks),
349
+ "keyword_total": keyword_total,
350
+ "unique_required_terms_found": required_found,
351
+ "top_keyword": top_keyword,
352
+ "source_character_count": len(clean_text),
353
+ }
354
+ _write_json(output_dir / "summary.json", summary)
355
+
356
+
357
+ def geojson_outputs(input_dir: Path, output_dir: Path) -> None:
358
+ payload = _read_json(input_dir / "events.geojson")
359
+ features = payload.get("features") if isinstance(payload, dict) else []
360
+ rows: list[dict[str, Any]] = []
361
+ for feature in features:
362
+ if not isinstance(feature, dict):
363
+ continue
364
+ props = feature.get("properties") if isinstance(feature.get("properties"), dict) else {}
365
+ geom = feature.get("geometry") if isinstance(feature.get("geometry"), dict) else {}
366
+ coords = geom.get("coordinates") if isinstance(geom.get("coordinates"), list) else []
367
+ mag = props.get("mag")
368
+ try:
369
+ mag = float(mag) if mag is not None else None
370
+ except (TypeError, ValueError):
371
+ mag = None
372
+ depth = None
373
+ if len(coords) >= 3:
374
+ try:
375
+ depth = float(coords[2])
376
+ except (TypeError, ValueError):
377
+ depth = None
378
+ time_ms = props.get("time")
379
+ date_utc = "unknown"
380
+ if isinstance(time_ms, (int, float)):
381
+ date_utc = dt.datetime.utcfromtimestamp(time_ms / 1000).date().isoformat()
382
+ rows.append({
383
+ "id": feature.get("id") or props.get("code") or "",
384
+ "mag": mag,
385
+ "depth": depth,
386
+ "place": str(props.get("place") or ""),
387
+ "region": _stable_region(str(props.get("place") or "")),
388
+ "date_utc": date_utc,
389
+ "feature": feature,
390
+ })
391
+ output_dir.mkdir(parents=True, exist_ok=True)
392
+ mags = [row["mag"] for row in rows if row["mag"] is not None]
393
+ depths = [row["depth"] for row in rows if row["depth"] is not None]
394
+ summary = {
395
+ "event_count": len(rows),
396
+ "magnitude": {
397
+ "count": len(mags),
398
+ "min": round(min(mags), 6) if mags else None,
399
+ "max": round(max(mags), 6) if mags else None,
400
+ "mean": round(statistics.fmean(mags), 6) if mags else None,
401
+ "median": round(statistics.median(mags), 6) if mags else None,
402
+ },
403
+ "depth_km": {
404
+ "count": len(depths),
405
+ "min": round(min(depths), 6) if depths else None,
406
+ "max": round(max(depths), 6) if depths else None,
407
+ "mean": round(statistics.fmean(depths), 6) if depths else None,
408
+ },
409
+ "time_range_utc": {
410
+ "start_date": min((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None),
411
+ "end_date": max((row["date_utc"] for row in rows if row["date_utc"] != "unknown"), default=None),
412
+ },
413
+ "quality_flags": {
414
+ "missing_magnitude": sum(1 for row in rows if row["mag"] is None),
415
+ "missing_depth": sum(1 for row in rows if row["depth"] is None),
416
+ "unique_regions": len({row["region"] for row in rows}),
417
+ },
418
+ }
419
+ _write_json(output_dir / "summary.json", summary)
420
+
421
+ grouped: dict[tuple[str, str], list[dict[str, Any]]] = {}
422
+ for row in rows:
423
+ grouped.setdefault((_mag_bin(row["mag"]), _depth_bin(row["depth"])), []).append(row)
424
+ with (output_dir / "magnitude_depth_bins.csv").open("w", encoding="utf-8", newline="") as handle:
425
+ fieldnames = ["mag_bin", "depth_bin", "event_count", "mean_magnitude", "max_magnitude"]
426
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
427
+ writer.writeheader()
428
+ for (mag_bin, depth_bin), group in sorted(grouped.items()):
429
+ group_mags = [row["mag"] for row in group if row["mag"] is not None]
430
+ writer.writerow({
431
+ "mag_bin": mag_bin,
432
+ "depth_bin": depth_bin,
433
+ "event_count": len(group),
434
+ "mean_magnitude": f"{statistics.fmean(group_mags):.6f}" if group_mags else "",
435
+ "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "",
436
+ })
437
+
438
+ daily: dict[tuple[str, str], list[dict[str, Any]]] = {}
439
+ for row in rows:
440
+ daily.setdefault((row["region"], row["date_utc"]), []).append(row)
441
+ with (output_dir / "region_daily_counts.csv").open("w", encoding="utf-8", newline="") as handle:
442
+ fieldnames = ["region", "date_utc", "event_count", "max_magnitude"]
443
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
444
+ writer.writeheader()
445
+ for (region, date_utc), group in sorted(daily.items()):
446
+ group_mags = [row["mag"] for row in group if row["mag"] is not None]
447
+ writer.writerow({
448
+ "region": region,
449
+ "date_utc": date_utc,
450
+ "event_count": len(group),
451
+ "max_magnitude": f"{max(group_mags):.6f}" if group_mags else "",
452
+ })
453
+
454
+ filtered = [row["feature"] for row in rows if row["mag"] is not None and row["mag"] >= 4.5]
455
+ _write_json(output_dir / "filtered_events.geojson", {"type": "FeatureCollection", "features": filtered})
456
+
457
+
458
+ def csv_time_series_outputs(input_dir: Path, output_dir: Path) -> None:
459
+ spec = _read_json(input_dir / "analysis_spec.json")
460
+ csv_name = spec["input_file"]
461
+ date_column = spec["date_column"]
462
+ value_column = spec["value_column"]
463
+ rows: list[dict[str, Any]] = []
464
+ with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle:
465
+ lines = [line for line in raw_handle if not line.lstrip().startswith("#")]
466
+ reader = csv.DictReader(lines)
467
+ for item in reader:
468
+ raw_date = item.get(date_column, "")
469
+ try:
470
+ day = dt.date.fromisoformat(raw_date)
471
+ except ValueError:
472
+ if raw_date.isdigit() and len(raw_date) == 4:
473
+ day = dt.date(int(raw_date), 1, 1)
474
+ else:
475
+ continue
476
+ raw_value = item.get(value_column, "")
477
+ try:
478
+ value = float(raw_value)
479
+ except (TypeError, ValueError):
480
+ value = None
481
+ rows.append({"date": day, "value": value, "raw": item})
482
+ rows.sort(key=lambda item: item["date"])
483
+ valid = [row for row in rows if row["value"] is not None]
484
+ output_dir.mkdir(parents=True, exist_ok=True)
485
+ monthly: dict[str, list[float]] = {}
486
+ for row in valid:
487
+ key = row["date"].strftime("%Y-%m")
488
+ monthly.setdefault(key, []).append(row["value"])
489
+ with (output_dir / "monthly_statistics.csv").open("w", encoding="utf-8", newline="") as handle:
490
+ fieldnames = ["month", "count", "mean", "median", "min", "max"]
491
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
492
+ writer.writeheader()
493
+ for month, values in sorted(monthly.items()):
494
+ writer.writerow({
495
+ "month": month,
496
+ "count": len(values),
497
+ "mean": f"{statistics.fmean(values):.6f}",
498
+ "median": f"{statistics.median(values):.6f}",
499
+ "min": f"{min(values):.6f}",
500
+ "max": f"{max(values):.6f}",
501
+ })
502
+ existing_dates = {row["date"] for row in rows}
503
+ missing_days: list[dt.date] = []
504
+ if rows:
505
+ day = rows[0]["date"]
506
+ while day <= rows[-1]["date"]:
507
+ if day.weekday() < 5 and day not in existing_dates:
508
+ missing_days.append(day)
509
+ day += dt.timedelta(days=1)
510
+ with (output_dir / "missing_business_days.csv").open("w", encoding="utf-8", newline="") as handle:
511
+ writer = csv.DictWriter(handle, fieldnames=["date"])
512
+ writer.writeheader()
513
+ for day in missing_days:
514
+ writer.writerow({"date": day.isoformat()})
515
+ with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle:
516
+ writer = csv.DictWriter(handle, fieldnames=["date", "value"])
517
+ writer.writeheader()
518
+ for row in valid:
519
+ writer.writerow({"date": row["date"].isoformat(), "value": f"{row['value']:.6f}"})
520
+ values = [row["value"] for row in valid]
521
+ summary = {
522
+ "series_name": spec.get("series_name", value_column),
523
+ "row_count": len(rows),
524
+ "valid_value_count": len(valid),
525
+ "missing_value_count": len(rows) - len(valid),
526
+ "missing_business_day_count": len(missing_days),
527
+ "date_range": {
528
+ "start": rows[0]["date"].isoformat() if rows else None,
529
+ "end": rows[-1]["date"].isoformat() if rows else None,
530
+ },
531
+ "value": {
532
+ "min": round(min(values), 6) if values else None,
533
+ "max": round(max(values), 6) if values else None,
534
+ "mean": round(statistics.fmean(values), 6) if values else None,
535
+ "median": round(statistics.median(values), 6) if values else None,
536
+ },
537
+ }
538
+ _write_json(output_dir / "summary.json", summary)
539
+
540
+
541
+ def _aggregate_annual_rows(rows: list[dict[str, Any]], aggregation: str) -> list[dict[str, Any]]:
542
+ if not aggregation:
543
+ return rows
544
+ grouped: dict[int, list[float]] = {}
545
+ for row in rows:
546
+ grouped.setdefault(int(row["year"]), []).append(float(row["value"]))
547
+ aggregated: list[dict[str, Any]] = []
548
+ for year, values in sorted(grouped.items()):
549
+ if aggregation == "mean":
550
+ value = statistics.fmean(values)
551
+ elif aggregation == "median":
552
+ value = statistics.median(values)
553
+ elif aggregation == "max":
554
+ value = max(values)
555
+ elif aggregation == "min":
556
+ value = min(values)
557
+ elif aggregation == "count":
558
+ value = float(len(values))
559
+ else:
560
+ raise ValueError(f"unsupported year_aggregation for csv_annual_series_audit: {aggregation}")
561
+ aggregated.append({"year": year, "value": value})
562
+ return aggregated
563
+
564
+
565
+ def csv_annual_series_outputs(input_dir: Path, output_dir: Path) -> None:
566
+ spec = _read_json(input_dir / "analysis_spec.json")
567
+ csv_name = spec["input_file"]
568
+ year_column = spec["year_column"]
569
+ value_column = spec["value_column"]
570
+ # Optional: derive the year from an ISO-8601 timestamp column (e.g. USGS FDSN
571
+ # `time` = "2022-06-29T19:17:58.929Z") instead of parsing an integer year.
572
+ # When unset, behaviour is unchanged (integer year column).
573
+ year_from_timestamp = bool(spec.get("year_from_timestamp", False))
574
+ year_aggregation = str(spec.get("year_aggregation") or "").strip().lower()
575
+ raw_rows: list[dict[str, Any]] = []
576
+ with (input_dir / csv_name).open("r", encoding="utf-8", newline="") as raw_handle:
577
+ lines = [line for line in raw_handle if not line.lstrip().startswith("#")]
578
+ reader = csv.DictReader(lines)
579
+ for item in reader:
580
+ raw_year = str(item.get(year_column, "")).strip()
581
+ try:
582
+ if year_from_timestamp:
583
+ # Take the leading 4-digit year of an ISO timestamp/date.
584
+ match = re.match(r"\s*(\d{4})", raw_year)
585
+ if not match:
586
+ continue
587
+ year = int(match.group(1))
588
+ else:
589
+ year = int(raw_year)
590
+ value = float(str(item.get(value_column, "")).strip())
591
+ except (TypeError, ValueError):
592
+ continue
593
+ raw_rows.append({"year": year, "value": value})
594
+ rows = _aggregate_annual_rows(raw_rows, year_aggregation)
595
+ rows.sort(key=lambda item: item["year"])
596
+ output_dir.mkdir(parents=True, exist_ok=True)
597
+ decades: dict[str, list[float]] = {}
598
+ for row in rows:
599
+ decade_start = (row["year"] // 10) * 10
600
+ decades.setdefault(f"{decade_start}s", []).append(row["value"])
601
+ with (output_dir / "decadal_statistics.csv").open("w", encoding="utf-8", newline="") as handle:
602
+ fieldnames = [
603
+ "decade_start",
604
+ "start_year",
605
+ "end_year",
606
+ "count",
607
+ "mean_departure",
608
+ "median_departure",
609
+ "min_departure",
610
+ "max_departure",
611
+ "sample_std_departure",
612
+ ]
613
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
614
+ writer.writeheader()
615
+ for decade, values in sorted(decades.items()):
616
+ decade_start = int(decade.rstrip("s"))
617
+ years = [row["year"] for row in rows if decade_start <= row["year"] <= decade_start + 9]
618
+ writer.writerow({
619
+ "decade_start": decade_start,
620
+ "start_year": min(years),
621
+ "end_year": max(years),
622
+ "count": len(values),
623
+ "mean_departure": f"{statistics.fmean(values):.6f}",
624
+ "median_departure": f"{statistics.median(values):.6f}",
625
+ "min_departure": f"{min(values):.6f}",
626
+ "max_departure": f"{max(values):.6f}",
627
+ "sample_std_departure": f"{statistics.stdev(values):.6f}" if len(values) >= 2 else "",
628
+ })
629
+ threshold = float(spec.get("threshold", 1.0))
630
+ with (output_dir / "threshold_years.csv").open("w", encoding="utf-8", newline="") as handle:
631
+ fieldnames = ["rank", "year", "departure", "threshold"]
632
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
633
+ writer.writeheader()
634
+ rank = 1
635
+ for row in rows:
636
+ if row["value"] >= threshold:
637
+ writer.writerow({
638
+ "rank": rank,
639
+ "year": row["year"],
640
+ "departure": f"{row['value']:.6f}",
641
+ "threshold": f"{threshold:.6f}",
642
+ })
643
+ rank += 1
644
+ with (output_dir / "clean_series.csv").open("w", encoding="utf-8", newline="") as handle:
645
+ writer = csv.DictWriter(handle, fieldnames=["Year", "Departure from Average"])
646
+ writer.writeheader()
647
+ for row in rows:
648
+ writer.writerow({"Year": row["year"], "Departure from Average": f"{row['value']:.6f}"})
649
+ values = [row["value"] for row in rows]
650
+ threshold_rows = [row for row in rows if row["value"] >= threshold]
651
+ min_row = min(rows, key=lambda row: row["value"]) if rows else None
652
+ max_row = max(rows, key=lambda row: row["value"]) if rows else None
653
+ summary = {
654
+ "series_name": spec.get("series_name", value_column),
655
+ "row_count": len(rows),
656
+ "year_range": {
657
+ "start": rows[0]["year"] if rows else None,
658
+ "end": rows[-1]["year"] if rows else None,
659
+ },
660
+ "value": {
661
+ "min": round(min(values), 6) if values else None,
662
+ "min_year": min_row["year"] if min_row else None,
663
+ "max": round(max(values), 6) if values else None,
664
+ "max_year": max_row["year"] if max_row else None,
665
+ "mean": round(statistics.fmean(values), 6) if values else None,
666
+ "median": round(statistics.median(values), 6) if values else None,
667
+ "sample_std": round(statistics.stdev(values), 6) if len(values) >= 2 else None,
668
+ },
669
+ "threshold": threshold,
670
+ "years_at_or_above_threshold": len(threshold_rows),
671
+ "first_threshold_year": threshold_rows[0]["year"] if threshold_rows else None,
672
+ "last_threshold_year": threshold_rows[-1]["year"] if threshold_rows else None,
673
+ }
674
+ if year_aggregation:
675
+ summary["year_aggregation"] = year_aggregation
676
+ summary["source_row_count"] = len(raw_rows)
677
+ _write_json(output_dir / "summary.json", summary)
678
+
679
+
20260907-002650-transport-safety-0ac894/tests/reference/internal/workflow_runtime.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from workflow_adapters_runtime import software_tutorial_outputs
3
+
4
+ def run_reference(input_dir: Path, output_dir: Path) -> None:
5
+ software_tutorial_outputs(input_dir, output_dir)
20260907-002650-transport-safety-0ac894/tests/reference/reference_manifest.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "workflow_kind": "software_tutorial_doc_audit",
3
+ "task_id": "repair3_20260907_088_repair2_20260906_094_repair_20260906_software_0108",
4
+ "domain": "transport_safety",
5
+ "task": "sumo_plainxml_document_inventory_audit",
6
+ "variant": "base",
7
+ "created_from": "standard reference workflow",
8
+ "required_outputs": [
9
+ {
10
+ "path": "summary.json",
11
+ "type": "json"
12
+ },
13
+ {
14
+ "path": "section_outline.csv",
15
+ "type": "csv"
16
+ },
17
+ {
18
+ "path": "keyword_inventory.csv",
19
+ "type": "csv"
20
+ },
21
+ {
22
+ "path": "code_block_inventory.csv",
23
+ "type": "csv"
24
+ }
25
+ ],
26
+ "numeric_tolerance": 1e-09,
27
+ "source_prior_sha256": "e338ca2c987a612024504d976fa1bc9c500c8779e986043eca1a870f6ef9a2a0",
28
+ "gold_output_hashes": {
29
+ "summary.json": "7c3ea2038e4c09fc61bff98483d80a65c9455dd83b288bd4260feaaea58a5233",
30
+ "section_outline.csv": "2e5418f96aca2bcb5a3ea72bbbcddf959a0be5efa9736f865052f0bd46ba61ec",
31
+ "keyword_inventory.csv": "21e285cec25a9b9dec2918ee1339d261f1df2b71f4e6c9384e64492c903e6ed0",
32
+ "code_block_inventory.csv": "7d8b5401cca2b6495d9d19f52e244164132bbb49d79a9a76752069be1d064e85"
33
+ }
34
+ }
20260907-002650-transport-safety-0ac894/tests/reference/reference_solution.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import sys
5
+ from pathlib import Path
6
+
7
+
8
+ def main() -> int:
9
+ parser = argparse.ArgumentParser()
10
+ parser.add_argument("--input", required=True)
11
+ parser.add_argument("--output", required=True)
12
+ args = parser.parse_args()
13
+ sys.path.insert(0, str(Path(__file__).resolve().parent / "internal"))
14
+ from workflow_runtime import run_reference
15
+ run_reference(Path(args.input), Path(args.output))
16
+ return 0
17
+
18
+
19
+ if __name__ == "__main__":
20
+ raise SystemExit(main())
20260907-002650-transport-safety-0ac894/tests/test.sh ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u
3
+
4
+ TESTS_DIR="${HARBOR_TESTS_DIR:-/tests}"
5
+ WORKSPACE_DIR="${HARBOR_WORKSPACE_DIR:-/workspace}"
6
+ LOGS_DIR="${HARBOR_LOGS_DIR:-/logs/verifier}"
7
+
8
+ mkdir -p "${LOGS_DIR}" "${WORKSPACE_DIR}/output"
9
+
10
+ python "${TESTS_DIR}/evaluator_runner.py" \
11
+ --output-dir "${WORKSPACE_DIR}/output" \
12
+ --reference-dir "${TESTS_DIR}/reference" \
13
+ --reward-json "${LOGS_DIR}/reward.json" \
14
+ --details-json "${LOGS_DIR}/ale_evaluator_details.json"
15
+
16
+ if [ ! -f "${LOGS_DIR}/reward.json" ]; then
17
+ echo '{"score":0.0,"format":0.0,"output_present":0.0,"evaluator_available":0.0,"item_count":0.0}' > "${LOGS_DIR}/reward.json"
18
+ fi
19
+
20
+ python - <<'PY' "${LOGS_DIR}/reward.json" "${LOGS_DIR}/reward.txt"
21
+ import json
22
+ import sys
23
+ from pathlib import Path
24
+ reward = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8"))
25
+ score = float(reward.get("score", 0.0))
26
+ Path(sys.argv[2]).write_text(f"{score}\n", encoding="utf-8")
27
+ PY
28
+
29
+ exit 0
20260907-002702-transport-safety-26060d/.DS_Store ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:23728b1425152eb65ed68df85c78dd546f7d692f222cdfe03e89721aa6b72972
3
+ size 6148
20260907-002702-transport-safety-26060d/environment/Dockerfile ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ WORKDIR /workspace
4
+
5
+ COPY public_data/input /workspace/input
6
+ COPY public_data/software /workspace/software
7
+ COPY public_data/task_card.json /workspace/task_card.json
8
+ COPY public_data/main.py /workspace/main.py
9
+ COPY public_data/README.md /workspace/README.md
10
+
11
+ RUN mkdir -p /workspace/output /workspace/report /logs/agent /logs/artifacts \
12
+ && chmod -R 777 /workspace/output /workspace/report /logs
20260907-002702-transport-safety-26060d/environment/public_data/README.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Public Task Inputs
2
+
3
+ Files in this directory are copied into the workspace:
4
+
5
+ - `input/` -> `/workspace/input/`
6
+ - `software/` -> `/workspace/software/`
7
+ - `task_card.json` -> `/workspace/task_card.json`
8
+ - `main.py` -> `/workspace/main.py`
9
+
10
+ Hidden reference data and evaluator files are not present in the agent workspace.
11
+ Final deliverables must be written under `/workspace/output/`.
20260907-002702-transport-safety-26060d/environment/public_data/input/README.md ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ This directory contains the public staged input for this task.
2
+ input/analysis_spec.json is the authoritative public contract for input columns, grouping/filtering rules, required output files, and output schemas.
3
+ Primary data file: input/tutorial_text_windows.csv.
4
+ Workflow kind: software_tutorial_doc_audit.
5
+ Required output files: output/summary.json, output/section_outline.csv, output/keyword_inventory.csv, output/code_block_inventory.csv.
6
+ Solve the task from the staged local files only; do not fetch fresh remote data during solve time.
20260907-002702-transport-safety-26060d/environment/public_data/input/analysis_spec.json ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "input_file": "tutorial_text_windows.csv",
3
+ "source_file": "tutorial_source.html",
4
+ "workflow_kind": "software_tutorial_doc_audit",
5
+ "software_name": "SUMO",
6
+ "tutorial_url": "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md",
7
+ "source_urls": [
8
+ "https://raw.githubusercontent.com/eclipse-sumo/sumo/main/docs/web/docs/Networks/PlainXML.md"
9
+ ],
10
+ "window_rule": {
11
+ "cleaning": "Strip HTML/script/style tags, decode entities, collapse whitespace, and preserve document text order.",
12
+ "window_size_words": 40,
13
+ "stride_words": 20,
14
+ "minimum_windows": 100
15
+ },
16
+ "heading_rule": "Extract h1-h6 headings from HTML; if no HTML headings are present, use Markdown # headings.",
17
+ "keyword_rule": "Count case-insensitive occurrences of required_terms and code_terms in the cleaned tutorial text.",
18
+ "required_terms": [
19
+ "SUMO",
20
+ "network",
21
+ "route",
22
+ "edge",
23
+ "vehicle"
24
+ ],
25
+ "code_terms": [
26
+ "sumo",
27
+ "netconvert",
28
+ "duarouter",
29
+ "netedit"
30
+ ],
31
+ "executables": [
32
+ "sumo",
33
+ "netconvert",
34
+ "duarouter",
35
+ "netedit"
36
+ ],
37
+ "required_system_packages": [
38
+ "sumo",
39
+ "sumo-tools"
40
+ ],
41
+ "required_outputs": [
42
+ {
43
+ "path": "summary.json",
44
+ "type": "json"
45
+ },
46
+ {
47
+ "path": "section_outline.csv",
48
+ "type": "csv"
49
+ },
50
+ {
51
+ "path": "keyword_inventory.csv",
52
+ "type": "csv"
53
+ },
54
+ {
55
+ "path": "code_block_inventory.csv",
56
+ "type": "csv"
57
+ }
58
+ ],
59
+ "output_schemas": {
60
+ "summary.json": {
61
+ "software_name": "string",
62
+ "source_file": "string",
63
+ "window_count": "integer",
64
+ "heading_count": "integer",
65
+ "code_block_count": "integer",
66
+ "keyword_total": "integer",
67
+ "unique_required_terms_found": "integer",
68
+ "top_keyword": "string|null",
69
+ "source_character_count": "integer"
70
+ },
71
+ "section_outline.csv": [
72
+ "rank",
73
+ "heading_level",
74
+ "heading_text",
75
+ "slug"
76
+ ],
77
+ "keyword_inventory.csv": [
78
+ "term",
79
+ "category",
80
+ "count",
81
+ "first_window",
82
+ "appears_in_code"
83
+ ],
84
+ "code_block_inventory.csv": [
85
+ "block_index",
86
+ "line_count",
87
+ "char_count",
88
+ "contains_code_term",
89
+ "first_line"
90
+ ]
91
+ },
92
+ "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."
93
+ }