Download core/engineering.py from Surajnitp/flowmarg: direct link, hf CLI and curl.
- Browser
- Download file 16.3 kB
-
https://huggingface.co/spaces/Surajnitp/flowmarg/resolve/main/core/engineering.py
- Command line
-
hf download hf://spaces/Surajnitp/flowmarg/core/engineering.py
-
curl -L -o engineering.py https://huggingface.co/spaces/Surajnitp/flowmarg/resolve/main/core/engineering.py
16.3 kB
| """ | |
| Core Engineering Calculations for Track Design | |
| Network Rail Standards - NR/L2/TRK/2500 | |
| """ | |
| import pandas as pd | |
| from typing import List, Dict | |
| from dataclasses import dataclass, field | |
| import re | |
| # ============================================ | |
| # HELPER FUNCTIONS (REQUIRED BY xml_parser.py) | |
| # ============================================ | |
| def num(value): | |
| """Convert value to float, return None if invalid""" | |
| try: | |
| if value is None: | |
| return None | |
| if isinstance(value, (int, float)): | |
| return float(value) | |
| if isinstance(value, str): | |
| value = value.strip() | |
| if not value: | |
| return None | |
| return float(value) | |
| return None | |
| except (ValueError, TypeError): | |
| return None | |
| def valid(v): | |
| """Check if value is valid (not None and not NaN)""" | |
| return v is not None and pd.notna(v) | |
| def station_of_point(point_element): | |
| """Get station/chainage from a point element""" | |
| if point_element is None: | |
| return None | |
| station = point_element.find("station") | |
| if station is None: | |
| return None | |
| return num(station.get("internalStation")) | |
| def classify(name): | |
| """Classify alignment name as CL, LH, RH, or OTHER. | |
| Uses token-based matching so names like 'CL_Existing' are handled. | |
| """ | |
| s = str(name).lower() | |
| # split on non-alphanumeric and underscore so tokens like 'cl' are isolated | |
| tokens = [t for t in re.split(r'[\W_]+', s) if t] | |
| for t in tokens: | |
| if t in ("cl", "centre", "center", "centreline", "centerline"): | |
| return "CL" | |
| if t in ("lh", "lr", "left"): | |
| return "LH" | |
| if t in ("rh", "rr", "right"): | |
| return "RH" | |
| # fallback: look for keywords anywhere | |
| if any(k in s for k in ["centre", "center", "centreline", "centerline"]): | |
| return "CL" | |
| if any(k in s for k in ["left", "lh", "lr"]): | |
| return "LH" | |
| if any(k in s for k in ["right", "rh", "rr"]): | |
| return "RH" | |
| return "OTHER" | |
| # ============================================ | |
| # NR LIMITS | |
| # ============================================ | |
| NR_LIMITS = { | |
| 'disp_lift': 30.0, | |
| 'disp_slue': 50.0, | |
| 'disp_cant_diff': 15.0, | |
| 'disp_sixfoot_diff': 10.0, | |
| 'disp_por': 20.0, | |
| 'match_distance': 0.10, | |
| 'geom_min_radius': 150.0, | |
| 'geom_min_transition': 20.0, | |
| 'geom_min_curve_length': 50.0, | |
| 'geom_max_cant': 150.0, | |
| 'geom_max_cant_def': 110.0, | |
| 'geom_max_roc': 55.0, | |
| 'geom_max_gradient': 2.5, | |
| 'geom_min_vertical_length': 50.0, | |
| 'geom_min_k': 30.0, | |
| } | |
| # ============================================ | |
| # CALCULATIONS | |
| # ============================================ | |
| def calculate_lift_value(existing_level, proposed_level): | |
| if existing_level is None or proposed_level is None: | |
| return None | |
| # Return rounded value to avoid tiny floating point residues in tests | |
| return round((proposed_level - existing_level) * 1000.0, 6) | |
| def calculate_slue_value(existing_offset, proposed_offset): | |
| if existing_offset is None or proposed_offset is None: | |
| return None | |
| return round((proposed_offset - existing_offset) * 1000.0, 6) | |
| def calculate_cant_value(left_level, right_level): | |
| if left_level is None or right_level is None: | |
| return None | |
| return round((right_level - left_level) * 1000.0, 6) | |
| def calculate_twist(level1, level2, distance_m): | |
| if level1 is None or level2 is None: | |
| return None | |
| if distance_m <= 0: | |
| return None | |
| return round(abs(level1 - level2) * 1000.0 / distance_m, 6) | |
| calculate_lift = calculate_lift_value | |
| calculate_slue = calculate_slue_value | |
| calculate_cant = calculate_cant_value | |
| def check_radius_for_speed(radius_m, speed_mph, max_cant_def_mm=110.0, applied_cant_mm=0.0): | |
| """Minimum radius vs speed using NR/L2/TRK/2102 equilibrium form. | |
| R_req (m) = 30.6 * V^2 / (Ea + D) with V in mph and cant in mm. | |
| Coefficient 30.6 is the mph/mm equivalent of 11.82 * V_kph^2 / Ea. | |
| Numeric limits are not changed here; they live in NR_LIMITS. | |
| """ | |
| if radius_m is None: | |
| return False, 0 | |
| if radius_m <= 0 or speed_mph <= 0: | |
| return True, 0 | |
| from core.config import ProductionConfig | |
| coeff = ProductionConfig.RADIUS_SPEED_COEFFICIENT | |
| required = coeff * (speed_mph ** 2) / (abs(applied_cant_mm) + max_cant_def_mm) | |
| return radius_m >= required, required | |
| class TrackData: | |
| track_no: int | |
| chainages: List[float] = field(default_factory=list) | |
| lifts: Dict[float, float] = field(default_factory=dict) | |
| slues: Dict[float, float] = field(default_factory=dict) | |
| ex_cants: Dict[float, float] = field(default_factory=dict) | |
| pr_cants: Dict[float, float] = field(default_factory=dict) | |
| ex_levels: Dict[float, float] = field(default_factory=dict) | |
| pr_levels: Dict[float, float] = field(default_factory=dict) | |
| radii: Dict[float, float] = field(default_factory=dict) | |
| sixfoots: Dict[float, float] = field(default_factory=dict) | |
| pors: Dict[float, float] = field(default_factory=dict) | |
| creeps: Dict[float, float] = field(default_factory=dict) | |
| ex_left_levels: Dict[float, float] = field(default_factory=dict) | |
| pr_left_levels: Dict[float, float] = field(default_factory=dict) | |
| def to_dict(self): | |
| return { | |
| "lift": self.lifts, | |
| "slue": self.slues, | |
| "ex_cant": self.ex_cants, | |
| "pr_cant": self.pr_cants, | |
| "ex_low": self.ex_levels, | |
| "pr_low": self.pr_levels, | |
| "pr_radius": self.radii, | |
| "pr_sixfoot": self.sixfoots, | |
| "por": self.pors, | |
| "creep": self.creeps, | |
| "ex_left_level": self.ex_left_levels, | |
| "pr_left_level": self.pr_left_levels, | |
| } | |
| def get_lift(self, chainage): | |
| return self.lifts.get(chainage) | |
| def get_slue(self, chainage): | |
| return self.slues.get(chainage) | |
| def get_radius(self, chainage): | |
| return self.radii.get(chainage) | |
| def compute_track_displacements(track_data, track_no, chainages, gauge_mm=1435.0): | |
| result = TrackData(track_no=track_no, chainages=list(chainages)) | |
| sorted_ch = sorted(chainages) | |
| for ch in sorted_ch: | |
| ex_left = track_data.get("ex_left_level", {}).get(ch) | |
| pr_left = track_data.get("pr_left_level", {}).get(ch) | |
| ex_right = track_data.get("ex_right_level", {}).get(ch) | |
| pr_right = track_data.get("pr_right_level", {}).get(ch) | |
| ex_offset = track_data.get("ex_offset", {}).get(ch) | |
| pr_offset = track_data.get("pr_offset", {}).get(ch) | |
| pr_radius = track_data.get("pr_radius", {}).get(ch) | |
| if ex_left is not None: | |
| result.ex_levels[ch] = ex_left | |
| result.ex_left_levels[ch] = ex_left | |
| if pr_left is not None: | |
| result.pr_levels[ch] = pr_left | |
| result.pr_left_levels[ch] = pr_left | |
| lift = calculate_lift_value(ex_left, pr_left) | |
| if lift is not None: | |
| result.lifts[ch] = lift | |
| slue = calculate_slue_value(ex_offset, pr_offset) | |
| if slue is not None: | |
| result.slues[ch] = slue | |
| if pr_radius is not None: | |
| result.radii[ch] = pr_radius | |
| ex_cant = calculate_cant_value(ex_left, ex_right) | |
| if ex_cant is not None: | |
| result.ex_cants[ch] = ex_cant | |
| pr_cant = calculate_cant_value(pr_left, pr_right) | |
| if pr_cant is not None: | |
| result.pr_cants[ch] = pr_cant | |
| for i in range(1, len(sorted_ch)): | |
| ch0, ch1 = sorted_ch[i - 1], sorted_ch[i] | |
| dist = abs(ch1 - ch0) | |
| lvl0 = result.pr_cants.get(ch0) | |
| lvl1 = result.pr_cants.get(ch1) | |
| if lvl0 is None or lvl1 is None: | |
| lvl0 = result.pr_levels.get(ch0) | |
| lvl1 = result.pr_levels.get(ch1) | |
| twist = calculate_twist(lvl0, lvl1, dist) | |
| if twist is not None: | |
| result.creeps[ch1] = twist | |
| return result | |
| def track_data_from_dict(data, track_no, chainages=None): | |
| """Rebuild TrackData from a to_dict() payload or a simplified calc dict.""" | |
| if isinstance(data, TrackData): | |
| return data | |
| data = data or {} | |
| chs = chainages or list(data.get("lift", {}).keys()) or list(data.keys()) | |
| # Simplified orchestrator shape: {ch: {"lift": ..., "level": ...}} | |
| if chs and not isinstance(next(iter(chs), None), (int, float)) and "lift" not in data: | |
| chs = [] | |
| if data and all(isinstance(k, (int, float)) for k in data.keys()): | |
| td = TrackData(track_no=track_no, chainages=sorted(data.keys())) | |
| for ch, vals in data.items(): | |
| if not isinstance(vals, dict): | |
| continue | |
| if vals.get("lift") is not None: | |
| td.lifts[ch] = vals["lift"] | |
| if vals.get("slue") is not None: | |
| td.slues[ch] = vals["slue"] | |
| if vals.get("level") is not None: | |
| td.pr_levels[ch] = vals["level"] | |
| if vals.get("radius") is not None: | |
| td.radii[ch] = vals["radius"] | |
| return td | |
| return TrackData( | |
| track_no=track_no, | |
| chainages=list(chs), | |
| lifts=data.get("lift", {}), | |
| slues=data.get("slue", {}), | |
| ex_cants=data.get("ex_cant", {}), | |
| pr_cants=data.get("pr_cant", {}), | |
| ex_levels=data.get("ex_low", {}), | |
| pr_levels=data.get("pr_low", {}), | |
| radii=data.get("pr_radius", {}), | |
| sixfoots=data.get("pr_sixfoot", {}), | |
| pors=data.get("por", {}), | |
| creeps=data.get("creep", {}), | |
| ex_left_levels=data.get("ex_left_level", {}), | |
| pr_left_levels=data.get("pr_left_level", {}), | |
| ) | |
| def run_compliance_checks(track_data, limits, track_category="C", design_speed=75.0, track_name=""): | |
| from core.standards_loader import get_track_category_limits, get_limit | |
| if not isinstance(track_data, TrackData): | |
| track_data = track_data_from_dict(track_data, 1) | |
| cat = get_track_category_limits(track_category) or {} | |
| findings = [] | |
| limits = limits or {} | |
| lift_limit = limits.get("disp_lift", NR_LIMITS.get("disp_lift", 30.0)) | |
| slue_limit = limits.get("disp_slue", NR_LIMITS.get("disp_slue", 50.0)) | |
| min_radius = limits.get("geom_min_radius", NR_LIMITS["geom_min_radius"]) | |
| max_cant = limits.get("geom_max_cant", get_limit("geom_max_cant", 150.0)) | |
| max_cant_def = cat.get("cant_def", limits.get("geom_max_cant_def", 110.0)) | |
| twist_limit = cat.get("twist_3m", 2.5) | |
| for ch in track_data.chainages: | |
| lift_val = track_data.get_lift(ch) | |
| if lift_val is not None: | |
| evidence = f"Track {track_data.track_no} at CH {ch}: Lift = {lift_val:.1f}mm" | |
| findings.append( | |
| create_engineering_finding( | |
| "Lift/Lower", | |
| lift_val, | |
| lift_limit, | |
| "NR/L2/TRK/2500 Section 4.2.1", | |
| evidence, | |
| track_data.track_no, | |
| ch, | |
| ) | |
| ) | |
| slue_val = track_data.get_slue(ch) | |
| if slue_val is not None: | |
| evidence = f"Track {track_data.track_no} at CH {ch}: Slue = {slue_val:.1f}mm" | |
| findings.append( | |
| create_engineering_finding( | |
| "Slue/Slew", | |
| slue_val, | |
| slue_limit, | |
| "NR/L2/TRK/2500 Section 4.2.2", | |
| evidence, | |
| track_data.track_no, | |
| ch, | |
| ) | |
| ) | |
| radius = track_data.get_radius(ch) | |
| if radius is not None: | |
| evidence = f"Track {track_data.track_no} at CH {ch}: Radius = {radius:.1f}m" | |
| findings.append( | |
| create_engineering_finding( | |
| "Minimum Radius", | |
| radius, | |
| min_radius, | |
| "NR/L2/TRK/2500 Section 5.1.1", | |
| evidence, | |
| track_data.track_no, | |
| ch, | |
| limit_type="min", | |
| ) | |
| ) | |
| applied = abs(track_data.pr_cants.get(ch, 0) or 0) | |
| ok, required = check_radius_for_speed(radius, design_speed, max_cant_def, applied) | |
| findings.append( | |
| create_engineering_finding( | |
| "Radius vs Speed", | |
| radius, | |
| required, | |
| "NR/L2/TRK/2500 Section 5.2 (equilibrium cant)", | |
| f"Track {track_data.track_no} CH {ch}: R={radius:.1f}m vs {design_speed}mph (cat {track_category})", | |
| track_data.track_no, | |
| ch, | |
| limit_type="min", | |
| ) | |
| ) | |
| cant = track_data.pr_cants.get(ch) | |
| if cant is not None: | |
| findings.append( | |
| create_engineering_finding( | |
| "Cant", | |
| cant, | |
| max_cant, | |
| "NR/L2/TRK/2500 Section 5.2.1", | |
| f"Track {track_data.track_no} CH {ch}: Cant = {cant:.1f}mm", | |
| track_data.track_no, | |
| ch, | |
| ) | |
| ) | |
| twist = track_data.creeps.get(ch) | |
| if twist is not None: | |
| findings.append( | |
| create_engineering_finding( | |
| "Twist", | |
| twist, | |
| twist_limit, | |
| "NR/L2/TRK/2500 (category twist 3m)", | |
| f"Track {track_data.track_no} CH {ch}: Twist = {twist:.2f}mm/m (cat {track_category})", | |
| track_data.track_no, | |
| ch, | |
| ) | |
| ) | |
| passed = sum(1 for f in findings if f["status"] == "PASS") | |
| failed = sum(1 for f in findings if f["status"] in ["REVIEW", "FAIL"]) | |
| total = len(findings) | |
| pass_rate = (passed / total * 100) if total > 0 else 0 | |
| summary = {"total": total, "total_checks": total, "passed": passed, "failed": failed, "pass_rate": pass_rate} | |
| return { | |
| "findings": findings, | |
| "summary": summary, | |
| "failed": failed, | |
| "pass_rate": pass_rate, | |
| "track": track_data.track_no, | |
| "track_name": track_name or f"Track {track_data.track_no}", | |
| "track_category": track_category, | |
| "design_speed": design_speed, | |
| } | |
| def create_engineering_finding(parameter, value, limit, rule, evidence, track, chainage, limit_type="max"): | |
| if value is None: | |
| return { | |
| "parameter": parameter, | |
| "value": None, | |
| "limit": limit, | |
| "status": "MISSING", | |
| "rule": rule, | |
| "reason": f"{parameter} data missing", | |
| "evidence": evidence, | |
| "chainage": chainage, | |
| "track": track, | |
| "recommendation": "Check source data", | |
| "priority": "HIGH" | |
| } | |
| abs_val = abs(value) | |
| if limit_type == "min": | |
| if abs_val >= limit: | |
| status, priority = "PASS", "LOW" | |
| reason = f"{parameter} of {abs_val:.1f} meets the {limit:.1f} minimum" | |
| elif abs_val >= (limit * 0.9): | |
| status, priority = "REVIEW", "MEDIUM" | |
| reason = f"{parameter} of {abs_val:.1f} is below the {limit:.1f} minimum by {limit - abs_val:.1f}" | |
| else: | |
| status, priority = "FAIL", "HIGH" | |
| reason = f"{parameter} of {abs_val:.1f} is significantly below the {limit:.1f} minimum" | |
| else: | |
| if abs_val <= limit: | |
| status, priority = "PASS", "LOW" | |
| reason = f"{parameter} of {abs_val:.1f} is within the {limit:.1f} allowable limit" | |
| elif abs_val <= limit * 1.5: | |
| status, priority = "REVIEW", "MEDIUM" | |
| reason = f"{parameter} of {abs_val:.1f} exceeds limit of {limit:.1f} by {abs_val - limit:.1f}" | |
| else: | |
| status, priority = "FAIL", "HIGH" | |
| reason = f"{parameter} of {abs_val:.1f} significantly exceeds limit of {limit:.1f}" | |
| return { | |
| "parameter": parameter, | |
| "value": round(value, 2), | |
| "limit": limit, | |
| "status": status, | |
| "rule": rule, | |
| "reason": reason, | |
| "evidence": evidence, | |
| "chainage": chainage, | |
| "track": track, | |
| "recommendation": f"{status} - {reason}", | |
| "priority": priority | |
| } | |