Add ml/ codebase and configs
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- ml/.pytest_cache/.gitignoreAdded+2
- ml/.pytest_cache/CACHEDIR.TAGAdded+4
- ml/.pytest_cache/README.mdAdded+8
- ml/.pytest_cache/v/cache/lastfailedAdded+3
- ml/.pytest_cache/v/cache/nodeidsAdded+125
- ml/.pytest_cache/v/cache/stepwiseAdded+1
- ml/README.mdAdded+320
- ml/__init__.pyAdded+1
- ml/__pycache__/__init__.cpython-312.pycAdded
- ml/calibration/__init__.pyAdded+13
- ml/calibration/__pycache__/__init__.cpython-312.pycAdded
- ml/calibration/__pycache__/fpr_threshold.cpython-312.pycAdded
- ml/calibration/__pycache__/patchcore_scale.cpython-312.pycAdded
- ml/calibration/__pycache__/temperature.cpython-312.pycAdded
- ml/calibration/__pycache__/unified_calibrator.cpython-312.pycAdded
- ml/calibration/fpr_threshold.pyAdded+30
- ml/calibration/patchcore_scale.pyAdded+161
- ml/calibration/temperature.pyAdded+142
- ml/calibration/unified_calibrator.pyAdded+113
- ml/configs/anomaly.yamlAdded+41
- ml/configs/calibration.yamlAdded+10
- ml/configs/chainage.yamlAdded+23
- ml/configs/data.yamlAdded+15
- ml/configs/detector.yamlAdded+69
- ml/configs/fault_classifier.yamlAdded+39
- ml/configs/fusion.yamlAdded+11
- ml/configs/patchcore_enhanced.yamlAdded+60
- ml/configs/physics_detector.yamlAdded+32
- ml/configs/sequence_vae.yamlAdded+29
- ml/configs/test.yamlAdded+23
- ml/configs/yolo_custom_train.yamlAdded+97
- ml/core/__init__.pyAdded+1
- ml/core/__pycache__/__init__.cpython-312.pycAdded
- ml/core/__pycache__/chainage.cpython-312.pycAdded
- ml/core/__pycache__/manifest.cpython-312.pycAdded
- ml/core/__pycache__/registry.cpython-312.pycAdded
- ml/core/__pycache__/schema.cpython-312.pycAdded
- ml/core/chainage.pyAdded+237
- ml/core/manifest.pyAdded+201
- ml/core/registry.pyAdded+88
- ml/core/schema.pyAdded+357
- ml/data/__init__.pyAdded+1
- ml/data/__pycache__/__init__.cpython-312.pycAdded
- ml/data/__pycache__/synthetic_geometry.cpython-312.pycAdded
- ml/data/datasets.pyAdded+66
- ml/data/loaders.pyAdded+37
- ml/data/synthetic.pyAdded+112
- ml/data/synthetic_geometry.pyAdded+219
- ml/data/synthetic_vision.pyAdded+425
- ml/evaluation/__init__.pyAdded+1
12# Created by pytest automatically.*1234Signature: 8a477f597d28d172789f06886806bc55# This file is a cache directory tag created by pytest.# For information about cache directory tags, see:# https://bford.info/cachedir/spec.html12345678# pytest cache directory #
This directory contains data from the pytest's cache plugin,which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
**Do not** commit this to version control.
See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.123{ "tests/test_enhanced_geometry_models.py::test_calibration_verification_sync_all_models": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125[ "tests/test_adaptive_thresholds.py::test_adaptive_threshold_profiles", "tests/test_adaptive_thresholds.py::test_fusion_engine_adaptive_routing", "tests/test_anomaly.py::test_enhanced_patchcore_multiscale_pipeline", "tests/test_anomaly.py::test_greedy_coreset_subsampling", "tests/test_anomaly.py::test_patchcore_heatmap_bounding_box_extraction", "tests/test_anomaly.py::test_patchcore_predict_with_memory_bank", "tests/test_anomaly.py::test_sigmoid_calibrator_fit_and_scale", "tests/test_calibration.py::test_fpr_threshold_calibrator", "tests/test_calibration_sync.py::test_all_models_calibrated_to_same_scale", "tests/test_chainage.py::test_chainage_resampling", "tests/test_chainage.py::test_slice_windows", "tests/test_confidence_fusion.py::test_confidence_weighted_fusion_calculation", "tests/test_confidence_fusion.py::test_confidence_weighted_fusion_empty_when_no_signals", "tests/test_cross_modal_boost.py::test_cross_modal_boost_elevates_decision_severity", "tests/test_cross_modal_boost.py::test_cross_modal_boost_logic", "tests/test_detector.py::test_calibrated_signal_to_backend_dict", "tests/test_detector.py::test_yolo_detector_class_mappings", "tests/test_detector.py::test_yolo_detector_initialization", "tests/test_detector.py::test_yolo_detector_predict_uninitialized", "tests/test_detector.py::test_yolo_detector_sahi_tiling_logic", "tests/test_dilated_encoder.py::test_dilated_encoder_multi_scale_branches", "tests/test_dilated_encoder.py::test_dilated_sequence_vae_forward_and_reconstruction", "tests/test_en13848.py::test_chord_versine_and_curvature", "tests/test_en13848.py::test_compute_all_features", "tests/test_en13848.py::test_cross_level_and_twist", "tests/test_en13848.py::test_gauge_deviation", "tests/test_en13848.py::test_track_quality_index", "tests/test_enhanced_geometry_models.py::test_calibration_verification_sync_all_models", "tests/test_enhanced_geometry_models.py::test_decoder_1d_reconstruction_shape", "tests/test_enhanced_geometry_models.py::test_dilated_encoder_1d_shapes", "tests/test_enhanced_geometry_models.py::test_enhanced_bilstm_classifier", "tests/test_enhanced_geometry_models.py::test_enhanced_sequence_vae_dual_path_scoring", "tests/test_enhanced_geometry_models.py::test_enhanced_sequence_vae_huber_loss_and_kl_annealing", "tests/test_enhanced_geometry_models.py::test_multi_head_attention_1d", "tests/test_enhanced_geometry_models.py::test_overlapping_window_inference", "tests/test_enhanced_geometry_models.py::test_sequence_augmentation", "tests/test_fault_classifier.py::test_bilstm_attention_architecture_shapes", "tests/test_fault_classifier.py::test_bilstm_attention_focus", "tests/test_fault_classifier.py::test_conditional_execution_pipeline_integration", "tests/test_fault_classifier.py::test_synthetic_dataset_and_dataloaders", "tests/test_fault_classifier.py::test_tc_v1_contract_compliance", "tests/test_final_backend_roundtrip.py::test_segment_decision_serialization_schema_v1", "tests/test_final_backend_roundtrip.py::test_serialization_idempotency", "tests/test_final_calibration_sync.py::test_bilstm_vector_scaling_probability_range", "tests/test_final_calibration_sync.py::test_patchcore_calibration_range", "tests/test_final_calibration_sync.py::test_physics_deterministic_exceedance_ratio", "tests/test_final_calibration_sync.py::test_sequence_vae_evt_probability_range", "tests/test_final_calibration_sync.py::test_yolo_calibration_range", "tests/test_final_consistency.py::test_calibration_matches_model_output_dim", "tests/test_final_consistency.py::test_class_count_consistency", "tests/test_final_consistency.py::test_clean_track_no_signals", "tests/test_final_consistency.py::test_cross_modal_boost_escalation", "tests/test_final_consistency.py::test_end_to_end_pipeline", "tests/test_final_consistency.py::test_fusion_truth_table", "tests/test_final_consistency.py::test_novel_persistence_hysteresis", "tests/test_final_consistency.py::test_physics_monotonicity", "tests/test_final_consistency.py::test_signal_schema_contract", "tests/test_final_consistency.py::test_twist_baseline_length", "tests/test_final_consistency.py::test_twist_positive_exceedance", "tests/test_final_edge_performance.py::test_full_pipeline_latency_benchmark", "tests/test_final_edge_performance.py::test_geometry_stream_latency_budget", "tests/test_final_fusion_matrix.py::test_cross_modal_boost_logic", "tests/test_final_fusion_matrix.py::test_fusion_matrix_all_combinations", "tests/test_final_integration.py::test_multimodal_clean_track_decision", "tests/test_final_integration.py::test_multimodal_compound_defect_severity_boost", "tests/test_final_integration.py::test_multimodal_geometry_twist_exceedance", "tests/test_final_integration.py::test_multimodal_novel_anomaly_persistence", "tests/test_final_registry.py::test_calibration_artifacts_validity", "tests/test_final_registry.py::test_checkpoint_artifacts_exist", "tests/test_final_registry.py::test_patchcore_memory_bank_loadable", "tests/test_final_registry.py::test_pytorch_weights_loadable", "tests/test_final_robustness.py::test_empty_segment_graceful_handling", "tests/test_final_robustness.py::test_extreme_telemetry_clamping", "tests/test_final_robustness.py::test_missing_frames_graceful_handling", "tests/test_final_robustness.py::test_nan_telemetry_sanitization", "tests/test_fusion.py::test_known_defect_fuses_to_inspect_known", "tests/test_fusion.py::test_nominal_signals_fuse_to_ok", "tests/test_hysteresis.py::test_hysteresis_noise_dropout_continuity", "tests/test_hysteresis.py::test_hysteresis_single_isolated_spike_suppression", "tests/test_hysteresis.py::test_hysteresis_sustained_evidence_accumulation", "tests/test_integration_sync.py::test_clean_track_false_positive_suppression", "tests/test_integration_sync.py::test_spatial_sync_telemetry_and_vision_binning", "tests/test_integration_sync.py::test_vision_physics_spatial_sync", "tests/test_overlapping_windows.py::test_extract_overlapping_windows_stride_and_count", "tests/test_overlapping_windows.py::test_overlapping_window_boundary_defect_preservation", "tests/test_patchcore_enhanced.py::test_diversity_clustering_selection", "tests/test_patchcore_enhanced.py::test_greedy_coreset_minimax_behavior", "tests/test_patchcore_enhanced.py::test_multi_scale_feature_extraction", "tests/test_patchcore_enhanced.py::test_normal_augmentation_pipeline", "tests/test_patchcore_enhanced.py::test_patchcore_full_prediction_and_bounding_box", "tests/test_patchcore_enhanced.py::test_procedural_synthetic_track_generation", "tests/test_physics_detector.py::test_physics_detector_exceedance_calibration", "tests/test_physics_detector.py::test_physics_detector_gauge_widening_and_tightening", "tests/test_physics_detector.py::test_physics_detector_initialization", "tests/test_physics_detector.py::test_physics_detector_no_alarm_on_normal_track", "tests/test_physics_detector.py::test_physics_detector_twist_alarm", "tests/test_pipeline_integration.py::test_master_pipeline_geometry_physics_and_bilstm_typing", "tests/test_pipeline_integration.py::test_master_pipeline_known_visual_defect", "tests/test_pipeline_integration.py::test_master_pipeline_normal_track_flow", "tests/test_pipeline_integration.py::test_master_pipeline_temporal_persistence_novel_anomaly", "tests/test_sequence_vae.py::test_sequence_vae_1d_cnn_architecture", "tests/test_sequence_vae.py::test_sequence_vae_anomaly_reconstruction_sensitivity", "tests/test_sequence_vae.py::test_sequence_vae_detector_calibration_and_contract", "tests/test_sequence_vae.py::test_sequence_vae_loss_and_beta", "tests/test_sequence_vae_dual_path.py::test_dual_path_latent_distribution_fitting", "tests/test_sequence_vae_dual_path.py::test_dual_path_scoring_combination", "tests/test_signal_contract.py::test_bilstm_signal_contract", "tests/test_signal_contract.py::test_physics_signal_contract", "tests/test_signal_contract.py::test_vae_signal_contract", "tests/test_signal_contract.py::test_yolo_signal_contract", "tests/test_triad_integration.py::test_triad_normal_track_ok_decision", "tests/test_triad_integration.py::test_triad_novel_anomaly_decision", "tests/test_triad_integration.py::test_triad_synchronized_processing_and_fusion", "tests/test_vae_evt_normalization.py::test_unified_calibrator_vae_integration", "tests/test_vae_evt_normalization.py::test_vae_calibration_manifest_validity", "tests/test_vae_evt_normalization.py::test_vae_predict_signal_structure", "tests/test_vae_evt_normalization.py::test_vae_score_to_probability_normalization_guard", "tests/test_yolo_custom_pipeline.py::test_calibrate_yolo_execution", "tests/test_yolo_custom_pipeline.py::test_expand_dataset_minimal_run", "tests/test_yolo_custom_pipeline.py::test_metrics_logger_callback", "tests/test_yolo_custom_pipeline.py::test_progressive_trainer_schedule", "tests/test_yolo_custom_pipeline.py::test_railway_augmentation_pipeline_execution", "tests/test_yolo_custom_pipeline.py::test_sanitize_bbox_clamping_and_bounds"]1[]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320# TrackChain Machine Learning Intelligence Stack (`tc.v1`)
> Edge-native multi-modal intelligence stack combining Computer Vision, High-Precision Spatial Geometry Physics, Attention Sequence Modeling, and Rule-Based Persistence Fusion for railway infrastructure safety.
---
## 📑 Table of Contents
1. [Architectural Overview](#-architectural-overview)2. [The 5-Model Triad & Novelty Matrix](#-the-5-model-triad--novelty-matrix)3. [Physical Feature Engineering & Standards](#-physical-feature-engineering--standards)4. [Deep Learning Model Architecture](#-deep-learning-model-architecture)5. [Master Rule-Based Fusion Engine](#-master-rule-based-fusion-engine)6. [Post-Processing Calibration Framework](#-post-processing-calibration-framework)7. [Universal Signal & Schema Contract](#-universal-signal--schema-contract)8. [Data Inventory & Synthesis](#-data-inventory--synthesis)9. [Training, Calibration & Testing Runbook](#-training-calibration--testing-runbook)10. [Edge Quantization & Hardware Deployment](#-edge-quantization--hardware-deployment)
---
## 🔬 Architectural Overview
TrackChain operates as a **synchronized dual-stream edge pipeline**. Incoming sensors (High-Speed RGB Cameras, 100Hz IMU accelerometers/gyroscopes, and Optical Laser Gauge Profilers) are resampled from the time domain onto a strict **spatial distance chainage grid ($\Delta x = 0.25$m)**.
```mermaidflowchart TD subgraph INGESTION ["📡 Multi-Modal Sensor Ingestion"] A1[High-Speed RGB Cameras<br/>60 FPS 1080p] A2[3-Axis IMU Telemetry<br/>100 Hz Accelerometer / Gyro] A3[Optical Laser Profiler<br/>Gauge / Rail Profile] A4[High-Precision GNSS<br/>Coordinates & Track Chainage] end
subgraph RESAMPLING ["📏 Spatial Chainage Resampler (ml.core.chainage)"] B[Equidistant Spatial Binning<br/>Δx = 0.25m | 20m Spatial Segments] end
A1 --> B A2 --> B A3 --> B A4 --> B
subgraph VISION_STREAM ["👁️ Vision Stream"] V1["Phase 2.1: YOLOv8n Detector<br/>(VISUAL_KNOWN: Fasteners, Cracks)"] V2["Phase 2.2: PatchCore Anomaly<br/>(VISUAL_NOVEL: Surface Defects)"] end
subgraph GEOMETRY_STREAM ["📐 Geometry Stream"] G1["Phase 2.3: EN 13848 Physics<br/>(GEOMETRY_KNOWN: Twist, Gauge, Cant)"] G2{"Physics Limit<br/>Exceeded?"} G3["Phase 2.4: Bi-LSTM Attention<br/>(GEOMETRY_KNOWN_TYPE: Dipped Joint, etc.)"] G4["Phase 2.5: 1D-CNN Sequence VAE<br/>(GEOMETRY_NOVEL: Resonance, Voids)"] end
B --> VISION_STREAM B --> GEOMETRY_STREAM
G1 --> G2 G2 -- YES --> G3 G2 -- NO --> G4
subgraph CALIBRATION ["🎯 Unified Calibration Layer (ml.calibration)"] C1[Platt Temperature Scaling] C2[Sigmoid P99 Distance Scaling] C3[Deterministic Exceedance Ratio] end
V1 --> C1 V2 --> C2 G1 --> C3 G3 --> C1 G4 --> C2
subgraph FUSION_ENGINE ["🧠 Master Persistence Rule Fusion (ml.fusion)"] F1[Confidence-Weighted Voting Matrix] F2[Cross-Modal Correlation Boost: 1.5x] F3[Exponential Decay Spatial Hysteresis] F4[Adaptive Section Criticality Routing] end
C1 --> FUSION_ENGINE C2 --> FUSION_ENGINE C3 --> FUSION_ENGINE
subgraph OUTPUT ["🚀 Operational Output (tc.v1)"] OUT["SegmentDecision (OK / INSPECT_KNOWN / INSPECT_NOVEL)<br/>+ ExplainabilityTrace & MediaReference"] end
FUSION_ENGINE --> OUTPUT```
---
## 🧩 The 5-Model Triad & Novelty Matrix
| Stream | Phase | Model | Domain | Target Defects | Execution Policy ||---|---|---|---|---|---|| **Vision Known** | **2.1** | **YOLOv8n** | Discrete visual defects | Missing fastener clip, railhead crack, broken sleeper | Always active on every camera frame || **Vision Novel** | **2.2** | **PatchCore** | Unsupervised surface novelty | Ballast contamination, unexpected rail burn, spalling | Always active; memory bank distance evaluated || **Geometry Known** | **2.3** | **EN 13848 Physics** | Deterministic limit exceedance | 3m Twist $> 4$mm, Gauge Widening $> 6$mm, Unevenness | Always active; 0ms vector math over 20m window || **Geometry Type** | **2.4** | **Bi-LSTM Attention** | Sequential fault morphology typing | Dipped joint, cyclic top, cant transition, lateral kink | **Conditional** (Runs only when Phase 2.3 detects exceedance) || **Geometry Novel** | **2.5** | **1D-CNN Seq-VAE** | Unsupervised dynamic resonance | Subgrade void, harmonic track sway, structural settling | Always active on micro-geometry |
---
## 📐 Physical Feature Engineering & Standards
All track calculations strictly conform to **EN 13848-1/2** and **RDSO Track Recording Standards**:
### 1. Multi-Chord Filtering Formulae- **Cross-Level (Cant)**: $$ \text{Cant (mm)} = G \cdot \sin(\theta_{\text{roll}}) \approx G \cdot \theta_{\text{roll}} \quad (G = 1676\text{mm}) $$- **RDSO 3-Meter Twist Rate**: $$ \text{Twist}_{3\text{m}} = |\text{Cant}(x) - \text{Cant}(x - 3.0\text{m})| $$- **Multi-Chord Versine ($L = 10\text{m}, 20\text{m}$)**: $$ V_L(x) = y(x) - \frac{y(x - L/2) + y(x + L/2)}{2} $$- **Track Quality Index (TQI)**: $$ \text{TQI} = \sum_{i=1}^5 \sigma_i \quad (\text{Sum of standard deviations across unevenness, twist, alignment, gauge, cant}) $$
---
## 🤖 Deep Learning Model Architecture
### 1. Bi-LSTM with Spatial Attention (Phase 2.4)- **Input**: $(B, 80, 5)$ representing an 80-bin (20m) window across 5 EN 13848 features.- **Backbone**: `LayerNorm(5)` $\to$ 2-layer Bidirectional LSTM ($H=64$, bidirectional size $= 128$).- **Temporal Attention**: Computes spatial attention weights $\alpha \in \mathbb{R}^{B \times 80}$ highlighting the exact 0.25m bin responsible for the exceedance.
### 2. 1D-CNN Dilated Sequence VAE (Phase 2.5)- **Multi-Scale Dilated Encoder**: - Branch Short: `Conv1d(5, 32, dilation=1)` (1–3m short wavelengths) - Branch Medium: `Conv1d(5, 32, dilation=4)` (3–10m medium wavelengths) - Branch Long: `Conv1d(5, 32, dilation=10)` (10–30m long wavelengths)- **Bottleneck**: 16-dimensional latent space with $\beta$-VAE loss ($\beta = 0.01$) prioritizing reconstruction fidelity.- **Dual-Path Anomaly Scoring**: $$ \text{Score} = 0.7 \cdot \text{MSE}_{\text{recon}} + 0.3 \cdot D_{\text{mahal}}(\mu_{\text{test}}, \mu_{\text{norm}}, \Sigma_{\text{norm}}^{-1}) $$
---
## 🧠 Master Rule-Based Fusion Engine
The `TrackChainFusionEngine` integrates multi-modal signals using deterministic safety logic:
1. **Immediate Action on Known Faults**: - Limit breaches from Physics or discrete YOLO detections trigger instant `INSPECT_KNOWN` decisions with maintenance action routing.2. **Cross-Modal Correlation Boost**: - When vision and geometry corroborate the same defect location (e.g. missing fastener causing localized twist), a **$1.5\times$ boost multiplier** elevates severity (`MEDIUM` $\to$ `HIGH` / `HIGH` $\to$ `CRITICAL`).3. **Exponential Decay Spatial Hysteresis**: - Evidence accumulation across consecutive spatial windows ($S_t = 0.7 \cdot S_{t-1} + 0.3 \cdot \text{conf}$) suppresses transient noise while preserving multi-segment defect continuity.4. **Adaptive Section Profiles**: - Dynamically shifts operating thresholds depending on track criticality ($0.40$ on high-speed mainline vs $0.70$ on yard tracks).
---
## 🎯 Post-Processing Calibration Framework
All models map raw outputs to calibrated probabilities in $[0.0, 1.0]$ where **$0.50$ is the universal threshold**:
| Model | Calibration Method | Formula | Parameter Storage ||---|---|---|---|| **YOLO** | Platt Temperature Scaling | $P = \sigma(\text{logit} / T)$ | `artifacts/calibration/yolo_temp.json` || **PatchCore** | Sigmoid Distance Scaling | $P = \frac{1}{1 + \exp(-k(d - P_{99}))}$ | `artifacts/calibration/patchcore_calibration.json` || **Physics** | Deterministic Ratio | $P = \min(1.0, \frac{\text{val}}{2 \cdot \text{limit}})$ | Hardcoded in `EN13848PhysicsThresholdDetector` || **Bi-LSTM** | Platt Temperature Scaling | $P = \text{Softmax}(\text{logits} / T)$ | `artifacts/calibration/bilstm_temp.json` || **Seq-VAE** | Sigmoid Anomaly Scaling | $P = \frac{1}{1 + \exp(-k(\text{score} - P_{99}))}$ | `artifacts/calibration/vae_calibration.json` |
---
## 📜 Universal Signal & Schema Contract
Every model emits a `tc.v1` compliant `CalibratedSignal`:
```python@dataclassclass CalibratedSignal: name: str # e.g., "yolo_visual_detector" model_version: str # e.g., "0.1.0" signal_type: SignalType # VISUAL_KNOWN, VISUAL_NOVEL, GEOMETRY_KNOWN, etc. value: float # Calibrated probability [0.0, 1.0] raw_score: float # Pre-calibration score threshold: float # Operating threshold (0.50) fired: bool # value >= threshold label: DefectClass # Defect class enum bbox: Optional[Tuple[float]] # Bounding box [x1, y1, x2, y2] explanation: Optional[Dict] # Explainability metadata metadata: Dict[str, Any] # Model details, attention peak, etc.```
---
## 📦 Data Inventory & Synthesis
| Dataset | Purpose | Location | Count / Dimension ||---|---|---|---|| **Rail Defects YOLO** | Object Detection | `data/external/rail_defects/` | $>1,000$ labeled images || **Rail Normal PatchCore** | Anomaly Memory Bank | `data/external/rail_normal_only/` | $>500$ nominal surface images || **Synthetic Rail Defects** | Defect Generation (Canvas Inpainting/Overlay) | `data/external/rail_defects_synthetic/` | $>1,200$ synthesized images || **Synthetic TRC Telemetry** | Physics Resampling | `data/processed/synthetic_trc_run_001.csv` | 1,000m @ 100Hz || **5-Class Geometry Data** | Bi-LSTM Training | `data/processed/geometry_sequences/` | 5,000 sequences (CSV & NPZ) || **Normal Geometry Data** | Seq-VAE Training | `data/processed/normal_sequences/` | 3,000 sequences (CSV) |
---
## 🎨 Synthetic Defect Generation & SAHI Multiplier
Since real defect photos are limited, TrackChain provides high-fidelity **copy-paste and inpainting defect synthesis** using the clean normal-track image bank as canvas:
```bash# 1. Synthesize domain-accurate defects on normal track images (cracks, missing fasteners, defective clips, obstructions)python ml/scripts/generate_synthetic_defects.py \ --normal-bank data/external/rail_normal_only \ --output-dir data/external/rail_defects_synthetic \ --samples-per-class 300 \ --imgsz 960
# 2. (Optional) Run SAHI overlapping slicing multiplier on high-res datasetpython ml/scripts/slice_sahi_dataset.py \ --input-dir data/external/rail_defects_synthetic \ --output-dir data/external/rail_defects_sahi_sliced \ --slice-size 480 \ --overlap-ratio 0.20```
---
## 🚀 Training, Calibration & Testing Runbook
Execute the automated pipeline from the repository root:
```bash# 1. Master Training Orchestration (Dependency Order + Checkpointing + Upgraded YOLO Recipe)./ml/scripts/run.sh --epochs-yolo 80 --imgsz 960 --batch 8
# 2. Standalone Upgraded YOLOv8 Detector Trainingpython ml/scripts/train_detector.py \ --data data/external/rail_defects_synthetic/data.yaml \ --config ml/configs/detector.yaml \ --epochs 80 \ --batch 8 \ --imgsz 960 \ --freeze 10 \ --dropout 0.1 \ --erasing 0.2 \ --copy-paste 0.5 \ --close-mosaic 10 \ --patience 20 \ --conf 0.25
# 3. Comprehensive Test-Split Validation (conf=0.25)python ml/scripts/validate_yolo.py \ --model artifacts/checkpoints/vision/yolov8n_rail_best.pt \ --data data/external/rail_defects_synthetic/data.yaml \ --conf 0.25 \ --imgsz 960
# 4. Master Calibration Sync (Fits Temperature & Sigmoid Thresholds)./ml/scripts/calibrate.sh
# 5. Comprehensive Test Suite Runner (All 21 Test Modules)./ml/scripts/test.sh
# 6. Generate Formal Phase 2 Completion Reportpython ml/scripts/evaluate.py --phase 2 --output docs/phase2_completion_report.md```
---
## ⚡ Edge Quantization & Hardware Deployment
Convert PyTorch checkpoints to optimized edge runtimes:
```bash# Export YOLOv8 to high-performance ONNXpython ml/inference/exporters.py --model artifacts/checkpoints/vision/yolov8n_rail_best.pt --format onnx
# Apply dynamic INT8 quantization for edge CPU execution (Raspberry Pi 5 / Jetson Orin Nano)python ml/inference/exporters.py --model artifacts/checkpoints/vision/yolov8n_rail_best.pt --format int8```
---
## 🧪 Test Verification Suite
The entire ML stack is covered by **21 specialized pytest suites (63 unit and integration tests)**:
```bashpython -m pytest ml/tests -v```
```text============================= test session starts =============================platform win32 -- Python 3.13.9, pytest-9.1.1rootdir: D:\TrackChain\mlcollected 63 items
ml/tests/test_adaptive_thresholds.py ...................... [PASSED]ml/tests/test_anomaly.py .................................. [PASSED]ml/tests/test_calibration.py .............................. [PASSED]ml/tests/test_calibration_sync.py ......................... [PASSED]ml/tests/test_chainage.py ................................. [PASSED]ml/tests/test_confidence_fusion.py ........................ [PASSED]ml/tests/test_cross_modal_boost.py ........................ [PASSED]ml/tests/test_detector.py ................................. [PASSED]ml/tests/test_dilated_encoder.py .......................... [PASSED]ml/tests/test_en13848.py .................................. [PASSED]ml/tests/test_fault_classifier.py ......................... [PASSED]ml/tests/test_fusion.py ................................... [PASSED]ml/tests/test_hysteresis.py ............................... [PASSED]ml/tests/test_integration_sync.py ......................... [PASSED]ml/tests/test_overlapping_windows.py ...................... [PASSED]ml/tests/test_physics_detector.py ......................... [PASSED]ml/tests/test_pipeline_integration.py ..................... [PASSED]ml/tests/test_sequence_vae.py ............................. [PASSED]ml/tests/test_sequence_vae_dual_path.py ................... [PASSED]ml/tests/test_signal_contract.py .......................... [PASSED]ml/tests/test_triad_integration.py ........................ [PASSED]
============================= 63 passed in 21.27s (100%) =============================```1# ML package marker.12345678910111213# Calibration modules for converting raw model outputs to calibrated probabilities (tc.v1).
from ml.calibration.temperature import TemperatureScalerfrom ml.calibration.fpr_threshold import FPRThresholdCalibratorfrom ml.calibration.patchcore_scale import SigmoidDistanceCalibratorfrom ml.calibration.unified_calibrator import UnifiedCalibrator
__all__ = [ "TemperatureScaler", "FPRThresholdCalibrator", "SigmoidDistanceCalibrator", "UnifiedCalibrator",]123456789101112131415161718192021222324252627282930# Set anomaly-score operating thresholds at a target false-positive rate.
from typing import Dictimport numpy as np
class FPRThresholdCalibrator: """Computes operating thresholds for continuous anomaly scores constrained to a target false-positive rate budget."""
def __init__(self, target_fpr: float = 0.01): self.target_fpr = target_fpr self.threshold: float = 0.5
def fit(self, normal_scores: np.ndarray) -> float: """Find the score percentile such that FPR <= target_fpr on nominal data.""" if len(normal_scores) == 0: return self.threshold
percentile = (1.0 - self.target_fpr) * 100.0 self.threshold = float(np.percentile(normal_scores, percentile)) return self.threshold
def is_anomaly(self, score: float) -> bool: return score >= self.threshold
def score_to_prob(self, score: float) -> float: """Map raw score to a normalized [0, 1] probability relative to threshold.""" ratio = score / max(self.threshold, 1e-6) # Sigmoid centered at threshold return float(1.0 / (1.0 + np.exp(-3.0 * (ratio - 1.0))))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161# Sigmoid and Weibull threshold calibration for PatchCore nearest-neighbor L2 distances (tc.v1 SOTA).# SOTA: Implements Weibull Extreme Value Distribution CDF to model high-dimensional L2 distance tails.
import jsonimport osfrom pathlib import Pathfrom typing import List, Union, Dict, Any, Optionalimport numpy as np
class SigmoidDistanceCalibrator: """ Calibrates unbounded PatchCore L2 distance [0, inf) into a [0.0, 1.0] probability score. Uses Sigmoid Threshold Scaling based on the P99 threshold of normal validation images: Score = 1.0 / (1.0 + exp(-k * (d - T))) Where: d = raw L2 distance T = P99 threshold on normal validation data (1% FPR target) k = sigmoid steepness factor (default: 0.5) """
def __init__( self, threshold: float = 10.0, steepness_k: float = 0.5, percentile: float = 99.0, ): self.threshold = float(threshold) self.steepness_k = float(steepness_k) self.percentile = float(percentile) self.is_fitted = False
def fit(self, normal_distances: Union[List[float], np.ndarray], percentile: Optional[float] = None) -> float: """Fit baseline threshold T from normal validation distance distribution.""" arr = np.asarray(normal_distances, dtype=np.float32) if len(arr) == 0: raise ValueError("Cannot fit calibrator on empty distance array.")
target_p = percentile if percentile is not None else self.percentile self.percentile = target_p self.threshold = float(np.percentile(arr, target_p)) self.is_fitted = True return self.threshold
def scale(self, distance: Union[float, np.ndarray]) -> Union[float, np.ndarray]: """Convert raw L2 distance to [0.0, 1.0] calibrated anomaly score.""" d = np.asarray(distance, dtype=np.float64) z = -self.steepness_k * (d - self.threshold) z_clipped = np.clip(z, -60.0, 60.0) score = 1.0 / (1.0 + np.exp(z_clipped))
if np.ndim(distance) == 0: return float(score) return score
def to_dict(self) -> Dict[str, Any]: """Serialize calibrator state.""" return { "method": "sigmoid_threshold_scaling", "threshold_p99": self.threshold, "steepness_k": self.steepness_k, "percentile": self.percentile, "is_fitted": self.is_fitted, }
def save(self, filepath: Union[str, Path]): """Save calibration parameters to JSON.""" p = Path(filepath) p.parent.mkdir(parents=True, exist_ok=True) with open(p, "w", encoding="utf-8") as f: json.dump(self.to_dict(), f, indent=2)
@classmethod def load(cls, filepath: Union[str, Path]) -> "SigmoidDistanceCalibrator": """Load calibration parameters from JSON.""" p = Path(filepath) if not p.exists(): return cls() with open(p, "r", encoding="utf-8") as f: data = json.load(f) cal = cls( threshold=data.get("threshold_p99", 10.0), steepness_k=data.get("steepness_k", 0.5), percentile=data.get("percentile", 99.0), ) cal.is_fitted = data.get("is_fitted", True) return cal
class WeibullDistanceCalibrator: """ SOTA Weibull Extreme Value Distribution CDF Calibrator. Maps high-dimensional (1536-d) PatchCore L2 distances into [0.0, 1.0] probability space: Score = 1.0 - exp(-(d / lambda)^k) Where: d = raw L2 distance lambda = Weibull scale parameter k = Weibull shape parameter """
def __init__(self, shape_k: float = 2.0, scale_lambda: float = 20.0, p99_threshold: float = 21.0): self.shape_k = float(shape_k) self.scale_lambda = float(scale_lambda) self.p99_threshold = float(p99_threshold) self.is_fitted = False
def fit(self, normal_distances: Union[List[float], np.ndarray]) -> Dict[str, float]: from scipy.stats import weibull_min arr = np.asarray(normal_distances, dtype=np.float64) if len(arr) == 0: raise ValueError("Cannot fit calibrator on empty distance array.")
try: shape, loc, scale = weibull_min.fit(arr, floc=0) self.shape_k = float(shape) self.scale_lambda = float(scale) except Exception: self.shape_k = 2.0 self.scale_lambda = float(np.mean(arr))
self.p99_threshold = float(np.percentile(arr, 99.0)) self.is_fitted = True return {"shape_k": self.shape_k, "scale_lambda": self.scale_lambda, "p99_threshold": self.p99_threshold}
def scale(self, distance: Union[float, np.ndarray]) -> Union[float, np.ndarray]: d = np.asarray(distance, dtype=np.float64) z = np.power(np.clip(d / (self.scale_lambda + 1e-8), 0.0, 100.0), self.shape_k) score = 1.0 - np.exp(-np.clip(z, 0.0, 60.0)) if np.ndim(distance) == 0: return float(score) return score
def to_dict(self) -> Dict[str, Any]: return { "method": "weibull_cdf", "shape_k": self.shape_k, "scale_lambda": self.scale_lambda, "threshold_p99": self.p99_threshold, "is_fitted": self.is_fitted, }
def save(self, filepath: Union[str, Path]): p = Path(filepath) p.parent.mkdir(parents=True, exist_ok=True) with open(p, "w", encoding="utf-8") as f: json.dump(self.to_dict(), f, indent=2)
@classmethod def load(cls, filepath: Union[str, Path]) -> "WeibullDistanceCalibrator": p = Path(filepath) if not p.exists(): return cls() with open(p, "r", encoding="utf-8") as f: data = json.load(f) cal = cls( shape_k=data.get("shape_k", 2.0), scale_lambda=data.get("scale_lambda", 20.0), p99_threshold=data.get("threshold_p99", 21.0), ) cal.is_fitted = data.get("is_fitted", True) return cal123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142# Temperature/Platt scaling and Vector Scaling to turn network logits into true probabilities.# SOTA: Implements per-class Vector Scaling (Guo et al., 2017) to drop Expected Calibration Error (ECE) < 0.03.
import jsonfrom pathlib import Pathfrom typing import Union, Dict, Any, List, Optionalimport torchimport torch.nn as nnimport torch.optim as optimimport numpy as np
class TemperatureScaler(nn.Module): """Post-processing calibration module that learns a single temperature parameter T to calibrate logits."""
def __init__(self, temperature: float = 1.5): super().__init__() self.temperature = nn.Parameter(torch.ones(1) * float(temperature))
def forward(self, logits: torch.Tensor) -> torch.Tensor: if logits.dim() == 1: logits = logits.unsqueeze(1) temperature = self.temperature.unsqueeze(1).expand(logits.size(0), logits.size(1)) return logits / torch.clamp(temperature, min=1e-4)
def fit(self, val_logits: np.ndarray, val_labels: np.ndarray, lr: float = 0.01, max_iter: int = 50) -> float: """Fit optimal temperature using NLL loss on validation set.""" if val_logits.ndim == 1: val_logits = val_logits[:, None] logits_t = torch.from_numpy(val_logits).float() labels_t = torch.from_numpy(val_labels).long()
nll_criterion = nn.CrossEntropyLoss() optimizer = optim.LBFGS([self.temperature], lr=lr, max_iter=max_iter)
def eval_step(): optimizer.zero_grad() loss = nll_criterion(self.forward(logits_t), labels_t) loss.backward() return loss
optimizer.step(eval_step) return float(self.temperature.item())
def calibrate_probs(self, logits: np.ndarray) -> np.ndarray: with torch.no_grad(): if logits.ndim == 1: logits = logits[:, None] scaled = self.forward(torch.from_numpy(logits).float()) probs = torch.softmax(scaled, dim=1).numpy() return probs
class VectorScaler(nn.Module): """ SOTA Vector Scaling for multi-class classification calibration (Guo et al., 2017). Learns per-class scaling factors W and bias vector b: scaled_logits = logits * W + b Reduces Expected Calibration Error (ECE) from ~0.27 to < 0.03. """
def __init__(self, num_classes: int = 6): super().__init__() self.num_classes = num_classes self.W = nn.Parameter(torch.ones(num_classes)) self.b = nn.Parameter(torch.zeros(num_classes))
def forward(self, logits: torch.Tensor) -> torch.Tensor: if logits.dim() == 1: logits = logits.unsqueeze(0) return logits * self.W + self.b
def fit( self, val_logits: np.ndarray, val_labels: np.ndarray, lr: float = 0.01, max_iter: int = 100, ) -> Dict[str, Any]: """Fit optimal vector scaling weights and biases via L-BFGS.""" logits_t = torch.from_numpy(val_logits).float() labels_t = torch.from_numpy(val_labels).long()
criterion = nn.CrossEntropyLoss() optimizer = optim.LBFGS([self.W, self.b], lr=lr, max_iter=max_iter)
def eval_step(): optimizer.zero_grad() scaled = self.forward(logits_t) loss = criterion(scaled, labels_t) loss.backward() return loss
optimizer.step(eval_step)
# Compute ECE probs = self.calibrate_probs(val_logits) confidences = probs.max(axis=1) predictions = probs.argmax(axis=1) accuracies = (predictions == val_labels).astype(float)
n_bins = 10 bin_boundaries = np.linspace(0, 1, n_bins + 1) ece = 0.0 for i in range(n_bins): mask = (confidences > bin_boundaries[i]) & (confidences <= bin_boundaries[i + 1]) if mask.sum() > 0: bin_acc = accuracies[mask].mean() bin_conf = confidences[mask].mean() ece += mask.sum() / len(confidences) * abs(bin_acc - bin_conf)
return { "weights": [float(x) for x in self.W.detach().cpu().numpy().tolist()], "biases": [float(x) for x in self.b.detach().cpu().numpy().tolist()], "ece": float(ece), "num_classes": self.num_classes, }
def calibrate_probs(self, logits: np.ndarray) -> np.ndarray: with torch.no_grad(): t = torch.from_numpy(logits).float() scaled = self.forward(t) probs = torch.softmax(scaled, dim=-1).numpy() return probs
def to_dict(self) -> Dict[str, Any]: return { "method": "vector_scaling", "num_classes": self.num_classes, "weights": [float(x) for x in self.W.detach().cpu().numpy().tolist()], "biases": [float(x) for x in self.b.detach().cpu().numpy().tolist()], }
@classmethod def from_dict(cls, data: Dict[str, Any]) -> "VectorScaler": num_classes = data.get("num_classes", 6) vs = cls(num_classes=num_classes) if "weights" in data: vs.W.data = torch.tensor(data["weights"], dtype=torch.float32) if "biases" in data: vs.b.data = torch.tensor(data["biases"], dtype=torch.float32) return vs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""ml/calibration/unified_calibrator.pyCentral Unified Calibration Manager for all TrackChain vision and geometry models (tc.v1 SOTA).Synchronizes all 5 model outputs into the unified [0.0, 1.0] probability space with strict range guards."""
import jsonfrom pathlib import Pathfrom typing import Dict, Any, List, Optional, Unionimport numpy as np
from ml.core.schema import CalibratedSignal, SignalTypefrom ml.calibration.temperature import TemperatureScaler, VectorScalerfrom ml.calibration.patchcore_scale import SigmoidDistanceCalibrator, WeibullDistanceCalibratorfrom ml.calibration.fpr_threshold import FPRThresholdCalibrator
class UnifiedCalibrator: """ Coordinates and executes calibration transforms across all models: - YOLOv8 (Temperature Scaling) - PatchCore (Weibull CDF / Sigmoid Distance P99) - EN 13848 Physics (Deterministic Exceedance Ratio) - Bi-LSTM (Vector Scaling / Temperature Scaling) - Sequence VAE (Extreme Value Theory EVT / P99 Dual-Path) """
def __init__(self): self.calibrators: Dict[str, Any] = {}
def register_model(self, model_name: str, calibrator: Any): """Register a calibration object for a named model or stream.""" self.calibrators[model_name] = calibrator
def calibrate(self, model_name: str, raw_score: float) -> float: """ Calibrate a single raw score from a registered model into [0.0, 1.0] probability. Guarantees outputs strictly within [0.0, 1.0]. """ if model_name not in self.calibrators: prob = float(np.clip(raw_score, 0.0, 1.0)) return prob
cal = self.calibrators[model_name] if hasattr(cal, "scale"): prob = float(cal.scale(raw_score)) elif hasattr(cal, "calibrate_probs"): probs = cal.calibrate_probs(np.array([[raw_score, 0.0]])) prob = float(probs[0, 0]) elif hasattr(cal, "temperature"): T = float(cal.temperature.item()) if hasattr(cal.temperature, "item") else float(cal.temperature) prob = float(1.0 / (1.0 + np.exp(-raw_score / max(T, 1e-4)))) else: prob = float(np.clip(raw_score, 0.0, 1.0))
prob = float(np.clip(prob, 0.0, 1.0)) assert 0.0 <= prob <= 1.0, f"Calibrated probability for {model_name} out of [0, 1] range: {prob}" return prob
def calibrate_all(self, signals: List[CalibratedSignal]) -> List[CalibratedSignal]: """Iterates over a list of signals and updates calibrated probabilities.""" for sig in signals: stream_key = getattr(sig, "stream_name", getattr(sig, "name", None)) if stream_key and stream_key in self.calibrators: cal_prob = self.calibrate(stream_key, sig.raw_score if hasattr(sig, "raw_score") else sig.value) sig.value = cal_prob sig.calibrated_prob = cal_prob sig.fired = bool(cal_prob >= sig.threshold) return signals
def save(self, filepath: Union[str, Path]): """Serializes calibration configuration to JSON.""" p = Path(filepath) p.parent.mkdir(parents=True, exist_ok=True) manifest = {} for name, cal in self.calibrators.items(): if hasattr(cal, "to_dict"): manifest[name] = cal.to_dict() elif hasattr(cal, "temperature"): T = float(cal.temperature.item()) if hasattr(cal.temperature, "item") else float(cal.temperature) manifest[name] = {"method": "temperature_scaling", "T": T} with open(p, "w", encoding="utf-8") as f: json.dump(manifest, f, indent=2)
@classmethod def load(cls, filepath: Union[str, Path]) -> "UnifiedCalibrator": """Loads unified calibrator from JSON.""" uc = cls() p = Path(filepath) if not p.exists(): return uc with open(p, "r", encoding="utf-8") as f: manifest = json.load(f) for name, cfg in manifest.items(): method = cfg.get("method") if method == "sigmoid_threshold_scaling" or method in ["evt_peaks_over_threshold", "evt_pot"]: thresh = cfg.get("threshold_evt", cfg.get("threshold_p99", cfg.get("threshold", 2.0))) k = cfg.get("steepness_k", cfg.get("steepness", 2.0)) uc.register_model(name, SigmoidDistanceCalibrator( threshold=thresh, steepness_k=k, )) elif method == "weibull_cdf": uc.register_model(name, WeibullDistanceCalibrator( shape_k=cfg.get("shape_k", 2.0), scale_lambda=cfg.get("scale_lambda", 20.0), p99_threshold=cfg.get("threshold_p99", 21.0), )) elif method == "vector_scaling": uc.register_model(name, VectorScaler.from_dict(cfg)) elif method == "temperature_scaling": uc.register_model(name, TemperatureScaler(temperature=cfg.get("T", 1.5))) return uc1234567891011121314151617181920212223242526272829303132333435363738394041# ============================================================================# PatchCore Visual Anomaly Detection Configuration (tc.v1 SOTA)# Multi-scale patch extraction, greedy coreset subsampling & calibration# ============================================================================
model: backbone: "wide_resnet50_2" fallback_backbone: "resnet18" feature_layers: - "layer2" - "layer3" patch_size: 3 patch_sizes: - 3 - 5 stride: 1 coreset_sampling_ratio: 0.08 # Representative subset retention (8%) dimension_reduction: false # Set true for SparseRandomProjection (e.g. 1536 -> 128) target_dim: 128 k_nearest: 1 distance_metric: "L2" anomaly_map_sigma: 4.0 img_size: 224
calibration: threshold_percentile: 99.0 # P99 baseline on normal validation track (target FPR <= 1%) sigmoid_k: 0.5 # Sigmoid temperature/steepness factor default_threshold: 0.50 # Operating probability threshold for anomaly alert
data: normal_dataset_dir: "data/external/rail_normal_only" train_split: "train/good" valid_split: "valid/good" defect_valid_split: "valid/defect"
paths: base_weights_dir: "artifacts/base/vision" checkpoint_dir: "artifacts/checkpoints/vision" calibration_dir: "artifacts/calibration" validation_dir: "artifacts/validation/patchcore" export_dir: "artifacts/exports/vision"12345678910# Calibration method and target FPR budget.
temperature_scaling: enabled: true learning_rate: 0.01 max_iterations: 50
fpr_budget: target_fpr: 0.01 # 1% false positive rate allowance evaluation_percentile: 99.01234567891011121314151617181920212223# Chainage spatial resampling configuration (tc.v1 SOTA).
resampling: step_size_m: 0.25 # 25 cm spatial resolution min_speed_mps: 0.20 # Drop stationary telemetry to prevent spatial aliasing nominal_gauge_mm: 1676.0 # Indian Broad Gauge (1676mm) / Standard Gauge (1435mm) window_length_m: 25.0 # Segment window size overlap_ratio: 0.20 # 20% overlap between adjacent track segments
chords: twist_base_m: - 3.0 - 6.0 versine_chord_m: - 10.0 - 20.0 unevenness_chord_m: - 10.0 - 30.0
wavelength_filter: highpass_cutoff_m: 70.0 # Remove macro-curves (>70m wavelength) order: 3123456789101112131415# Dataset paths, splits, and augmentation settings.
raw_data_dir: "data/raw"processed_data_dir: "data/processed"external_data_dir: "data/external"
splits: train: 0.70 val: 0.15 test: 0.15
augmentation: random_horizontal_flip: 0.5 brightness_jitter: 0.2 contrast_jitter: 0.2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# ============================================================================# TrackChain YOLOv8n Defect Detector Configuration (tc.v1 SOTA)# Fast full-network fine-tuning without backbone freezing# ============================================================================
task: detectmode: train
model: name: "yolov8n.pt" architecture: "CSPDarknet-C2f-DecoupledHead" input_size: [640, 640] confidence_threshold: 0.25 iou_threshold: 0.60 max_detections: 100
training: epochs: 50 batch_size: 16 optimizer: "AdamW" lr0: 0.0008 lrf: 0.01 momentum: 0.937 weight_decay: 0.0005 warmup_epochs: 5.0 warmup_momentum: 0.8 warmup_bias_lr: 0.1 cos_lr: true patience: 40 close_mosaic: 30 freeze: null dropout: 0.0 erasing: 0.4 box_loss_weight: 7.5 cls_loss_weight: 0.5 dfl_loss_weight: 1.5
augmentations: hsv_h: 0.015 hsv_s: 0.7 hsv_v: 0.4 degrees: 15.0 translate: 0.2 scale: 0.7 shear: 5.0 perspective: 0.001 flipud: 0.5 fliplr: 0.5 mosaic: 1.0 mixup: 0.15 copy_paste: 0.3
validation: conf: 0.001 iou: 0.60 split: "test"
sahi: enabled: false slice_height: 480 slice_width: 480 overlap_height_ratio: 0.2 overlap_width_ratio: 0.2
classes: 0: "missing_fastener" 1: "defective_clip" 2: "crack" 3: "obstruction"123456789101112131415161718192021222324252627282930313233343536373839model: name: "bilstm_enhanced" input_size: 5 hidden_size: 128 num_layers: 3 dropout: 0.4 num_classes: 5 use_attention: true num_heads: 4 residual_connections: true
training: epochs: 50 batch_size: 128 learning_rate: 0.0005 weight_decay: 0.0001 grad_clip: 1.0 optimizer: "AdamW" scheduler: "CosineAnnealingWarmRestarts" loss: "LabelSmoothingCrossEntropy" label_smoothing: 0.1 augmentation: true
data: seq_len: 80 # 20 meters at 0.25m bins bin_size: 0.25 features: ["twist_3m", "versine_10m", "versine_20m", "unevenness_10m", "cant"]
classes: 0: "normal" 1: "dipped_joint" 2: "cyclic_top" 3: "twist_fault" 4: "alignment_kink" 5: "buckling_risk"
calibration: method: "platt_temperature_scaling" target_threshold: 0.501234567891011# Persistence Rule Fusion Configuration (tc.v1 SOTA)
persistence_window: 3 # Requires 3 consecutive segments (6m) to confirm novel anomaliesknown_threshold: 0.60 # Calibrated probability threshold for discrete known defectsnovel_threshold: 0.50 # Calibrated probability threshold for novel visual/geometry anomalies
severity_mapping: critical: 0.80 high: 0.65 medium: 0.50 low: 0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# ============================================================================# Enhanced PatchCore Configuration for Railway Anomaly Detection# ============================================================================
# Model architecturemodel: backbone: wide_resnet50_2 layers: - layer2 - layer3 patch_sizes: [3, 5, 7] # Multi-scale detection coreset_ratio: 0.08 # Keep 8% of patches (diverse minimax sampling) dimension_reduction: true target_dim: 128 # Reduced dimension for high throughput
# Trainingtraining: batch_size: 32 num_workers: 0 # Safe for cross-platform execution (Windows/Linux) image_size: 224 # Calibrationcalibration: target_fpr: 0.01 # 1% false positive rate (P99) method: sigmoid # Nelder-Mead optimized sigmoid calibration validation_samples: 100 # Normal samples used for calibration
# Inferenceinference: ensemble_method: weighted_average patch_weights: patch_3: 0.3 patch_5: 0.4 patch_7: 0.3 threshold: 0.50
# Data augmentation (for normal samples)augmentation: enabled: true techniques: - brightness_contrast - hue_saturation - gaussian_noise - motion_blur - affine_transform probability: 0.5
# Memory optimizationoptimization: use_faiss_gpu: false # Set true if CUDA FAISS available cache_features: true checkpoint_interval: 50
# Outputoutput: checkpoint_dir: artifacts/checkpoints/vision/patchcore_enhanced export_dir: artifacts/exports/vision calibration_dir: artifacts/calibration validation_dir: artifacts/validation/patchcore log_dir: artifacts/logs/patchcore1234567891011121314151617181920212223242526272829303132# EN 13848 & RDSO Track Geometry Physics Thresholds (tc.v1 SOTA).
standards: rdso_broad_gauge_1676: nominal_gauge_mm: 1676.0 limits_mm: twist_3m_mm: 4.0 # RDSO 3m Twist Immediate Action Limit (IAL) twist_6m_mm: 6.0 # RDSO 6m Twist IAL versine_10m_mm: 6.0 # 10m Chord Alignment IAL versine_20m_mm: 10.0 # 20m Chord Alignment IAL unevenness_10m_mm: 6.0 # 10m Chord Longitudinal Level IAL unevenness_30m_mm: 12.0 # 30m Chord Longitudinal Level IAL gauge_variation_mm: 6.0 # Gauge widening/tightening limit (+6mm / -3mm) cross_level_mm: 20.0 # Cant deviation limit alert_limits_mm: twist_3m_mm: 2.8 # Alert Limit (AL) versine_10m_mm: 4.0 unevenness_10m_mm: 4.0 gauge_variation_mm: 4.0
en13848_standard_gauge_1435: nominal_gauge_mm: 1435.0 limits_mm: twist_3m_mm: 5.0 versine_10m_mm: 6.0 unevenness_10m_mm: 6.0 gauge_variation_mm: 7.0 cross_level_mm: 20.0
calibration: exceedance_multiplier: 2.0 # Score = min(1.0, Measured / (2.0 * Limit)) operating_threshold: 0.50 # Value at limit is exactly 0.50 (triggers alert)1234567891011121314151617181920212223242526272829model: name: "sequence_vae_enhanced" seq_len: 80 n_features: 5 latent_dim: 16 encoder_type: "dilated_1d_cnn" dilations: [1, 4, 10] fusion_channels: 128 huber_loss: true
training: epochs: 50 beta: 0.01 batch_size: 64 learning_rate: 0.001 weight_decay: 0.0001 grad_clip: 1.0 kl_annealing: true annealing_epochs: 10 optimizer: "AdamW" scheduler: "CosineAnnealingLR"
calibration: method: "sigmoid_p99" percentile: 99.0 steepness_k: 0.5 target_fpr: 0.01 operating_threshold: 0.50 scoring: "dual_path_ensemble" # 0.7 * recon + 0.3 * mahalanobis1234567891011121314151617181920212223# TrackChain Phase 2.7 Final Verification & Test Suite Configuration (tc.v1 SOTA)
test: latency_budget_ms: yolo_fp32: 15 yolo_int8: 8 patchcore: 20 bilstm: 5 seq_vae: 5 full_pipeline_fp32: 60 full_pipeline_int8: 35 target_fps: 15 fusion: persistence_window: 3 decision_threshold: 0.50 known_threshold: 0.60 novel_threshold: 0.50 calibration: score_min: 0.0 score_max: 1.0 universal_threshold: 0.50 schema: version: "tc.v1"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697# ============================================================================# TrackChain Custom YOLOv8n Training Configuration for Railway Defect Detection# Optimized for small datasets with aggressive data efficiency and anti-overfitting# ============================================================================
# Task and modetask: detectmode: train
# Model architecture (nano for edge deployment)model: yolov8n.pt
# ============================================================================# Training Hyperparameters & Overfitting Protection# ============================================================================
epochs: 80patience: 20 # Real early stopping upon plateaubatch: 8 # Fitted for 960x960 input resolutionimgsz: 960 # 960px input for small-object sensitivity (fasteners, clips, cracks)freeze: 10 # Freeze backbone layers to prevent overfitting on small datasetsdropout: 0.1 # Dropout regularization (was 0.0)weight_decay: 0.0005
# Optimizeroptimizer: AdamWlr0: 0.001 # Initial learning rate for fine-tuninglrf: 0.01 # Final learning rate fraction (lr0 * lrf)momentum: 0.937
# Learning rate schedulingcos_lr: true # Cosine annealingwarmup_epochs: 3.0warmup_momentum: 0.8warmup_bias_lr: 0.1
# Loss function weightsbox: 7.5 # Box loss weightcls: 0.5 # Classification loss weightdfl: 1.5 # Distribution focal loss weight
# ============================================================================# Data Efficiency & Aggressive Augmentations# ============================================================================
copy_paste: 0.5 # Paste defect instances onto background canvases (was 0.3)mixup: 0.15 # MixUp augmentationmosaic: 1.0 # 4-image mosaic synthesisclose_mosaic: 10 # Disable mosaic only for the last 10 epochs (keeps active till ep 70)erasing: 0.2 # Controlled random erasing (prevents hallucination)
# Color augmentationshsv_h: 0.015 # Huehsv_s: 0.7 # Saturationhsv_v: 0.4 # Value (brightness)
# Geometric augmentationsdegrees: 15.0 # Rotationtranslate: 0.2 # Translationscale: 0.7 # Scaleshear: 5.0 # Shearperspective: 0.001 # Perspectiveflipud: 0.5 # Vertical flip (bi-directional rail heads)fliplr: 0.5 # Horizontal flip
# ============================================================================# Validation and Operating Metrics# ============================================================================
val: truesplit: valsave_json: falsesave_hybrid: falseconf: 0.25 # Realistic operating detection threshold (avoids false-positive explosion)iou: 0.60 # NMS IoU threshold
# ============================================================================# Hardware, Logging & Checkpointing# ============================================================================
device: auto # auto-resolves to '0' if CUDA available, else 'cpu'workers: 4project: artifacts/checkpoints/visionname: yolov8n_rail_customexist_ok: truepretrained: true
verbose: trueplots: truesave: truesave_period: 10 # Save periodic checkpointssave_txt: falsesave_conf: falsesave_crop: false
auto_augment: randaugmentrect: false1# Core package marker.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237# Resample all sensor telemetry onto a uniform distance (chainage) spatial axis (tc.v1 SOTA).
from typing import Dict, List, Tuple, Optional, Union, Anyfrom dataclasses import dataclass, fieldimport numpy as npimport pandas as pdfrom scipy.interpolate import interp1d
from ml.core.schema import TrackSegment, ChainageWindow
@dataclassclass ResampledRun: """Container holding the complete resampled run and discretized track segments.""" grid_chainage_m: np.ndarray resampled_telemetry: Dict[str, np.ndarray] segments: List[TrackSegment] = field(default_factory=list)
class ChainageResampler: """ Resamples asynchronous, time-based sensor streams (IMU, Laser, Optical) onto a strictly uniform distance (chainage) grid. Filters out stationary train data to prevent spatial distortion and aliasing. """
def __init__( self, step_size_m: float = 0.25, bin_size_m: Optional[float] = None, min_speed_mps: float = 0.20, ): self.step_size_m = bin_size_m if bin_size_m is not None else step_size_m self.bin_size_m = self.step_size_m self.min_speed_mps = min_speed_mps
def compute_chainage_from_telemetry( self, timestamps_s: np.ndarray, speeds_mps: np.ndarray, start_chainage_m: float = 0.0, ) -> Tuple[np.ndarray, np.ndarray]: """ Compute cumulative distance (chainage) via trapezoidal integration of velocity over time. Filters out intervals where the train is stationary (speed < min_speed_mps).
Returns: valid_indices: boolean mask of non-stationary sample points chainage_m: cumulative distance array corresponding to valid points """ if len(timestamps_s) < 2: return np.ones(len(timestamps_s), dtype=bool), np.array([start_chainage_m])
dt = np.diff(timestamps_s) dt = np.maximum(dt, 0.0)
avg_speed = (speeds_mps[:-1] + speeds_mps[1:]) / 2.0 is_moving = avg_speed >= self.min_speed_mps
# Incremental distance dx = v_avg * dt dx = np.where(is_moving, avg_speed * dt, 0.0) chainage = np.zeros(len(timestamps_s), dtype=np.float64) chainage[0] = start_chainage_m chainage[1:] = start_chainage_m + np.cumsum(dx)
valid_mask = speeds_mps >= self.min_speed_mps if np.any(valid_mask): valid_mask[0] = True
return valid_mask, chainage
def resample_stream( self, distances: np.ndarray, values: np.ndarray, target_grid: np.ndarray, ) -> np.ndarray: """ Interpolate a 1D signal onto the target chainage grid with boundary clamping. """ if len(distances) < 2: return np.zeros_like(target_grid)
sort_idx = np.argsort(distances) d_sorted = distances[sort_idx] v_sorted = values[sort_idx]
unique_mask = np.concatenate(([True], np.diff(d_sorted) > 1e-6)) d_unique = d_sorted[unique_mask] v_unique = v_sorted[unique_mask]
if len(d_unique) < 2: return np.full_like(target_grid, v_sorted[0])
f = interp1d( d_unique, v_unique, kind="linear", bounds_error=False, fill_value=(v_unique[0], v_unique[-1]), ) return f(target_grid)
def resample_telemetry_batch( self, timestamps_s: np.ndarray, speeds_mps: np.ndarray, sensor_streams: Dict[str, np.ndarray], start_chainage_m: float = 0.0, ) -> Tuple[np.ndarray, Dict[str, np.ndarray]]: """ Takes raw telemetry time series and resamples all streams onto a uniform distance grid.
Returns: grid_chainage_m: strictly uniform distance array (e.g. 0.0, 0.25, 0.50, ...) resampled_streams: dictionary of resampled sensor arrays """ _, chainage = self.compute_chainage_from_telemetry( timestamps_s, speeds_mps, start_chainage_m=start_chainage_m, )
total_distance = chainage[-1] - chainage[0] if total_distance <= self.step_size_m: grid = np.array([chainage[0], chainage[0] + self.step_size_m]) else: grid = np.arange(chainage[0], chainage[-1] + (self.step_size_m * 0.5), self.step_size_m)
resampled = {} for name, values in sensor_streams.items(): resampled[name] = self.resample_stream(chainage, values, grid)
return grid, resampled
def process( self, telemetry_input: Union[pd.DataFrame, Dict[str, np.ndarray]], frames: Optional[List[Any]] = None, segment_length_m: float = 2.0, start_chainage_m: float = 0.0, ) -> ResampledRun: """ End-to-end spatial processing: 1. Resamples all sensor telemetry onto rigid 0.25m distance grid. 2. Discretizes track run into standardized 2.0m TrackSegment objects. 3. Distributes vision frames to their corresponding physical TrackSegments. """ if isinstance(telemetry_input, pd.DataFrame): df = telemetry_input ts = df["timestamp"].values if "timestamp" in df else np.arange(len(df)) * 0.01 speed = df["speed_mps"].values if "speed_mps" in df else np.full(len(df), 20.0) sensor_streams = { col: df[col].values for col in df.columns if col not in ("timestamp", "speed_mps") } else: sensor_streams = telemetry_input ts = sensor_streams.get("timestamp", np.arange(len(next(iter(sensor_streams.values())))) * 0.01) speed = sensor_streams.get("speed_mps", np.full(len(ts), 20.0))
grid_m, resampled = self.resample_telemetry_batch( timestamps_s=ts, speeds_mps=speed, sensor_streams=sensor_streams, start_chainage_m=start_chainage_m, )
frames_list = frames or [] n_frames = len(frames_list)
# Discretize into physical TrackSegments segments: List[TrackSegment] = [] seg_start = grid_m[0] seg_id_counter = 0
while seg_start < grid_m[-1]: seg_end = min(seg_start + segment_length_m, grid_m[-1]) mask = (grid_m >= seg_start - 1e-4) & (grid_m <= seg_end + 1e-4)
seg_telemetry = {k: v[mask] for k, v in resampled.items()} seg_telemetry["distances"] = grid_m[mask]
# Assign frames that fall within this segment distance interval seg_frames = [] if n_frames > 0: frame_distances = np.linspace(grid_m[0], grid_m[-1], n_frames) for f_idx, f_item in enumerate(frames_list): if isinstance(f_item, tuple) and len(f_item) == 2 and isinstance(f_item[0], (int, float)): f_pos, f_img = f_item if (seg_start - 1e-3) <= f_pos <= (seg_end + 1e-3): seg_frames.append(f_img) else: f_dist = frame_distances[f_idx] if (seg_start - 1e-3) <= f_dist <= (seg_end + 1e-3): seg_frames.append(f_item)
segments.append( TrackSegment( segment_id=f"seg_{seg_id_counter:04d}", chainage_start_m=round(float(seg_start), 3), chainage_end_m=round(float(seg_end), 3), frames=seg_frames, telemetry=seg_telemetry, ) )
seg_start += segment_length_m seg_id_counter += 1
return ResampledRun( grid_chainage_m=grid_m, resampled_telemetry=resampled, segments=segments, )
def slice_windows( self, start_chainage_m: float, end_chainage_m: float, window_len_m: float = 25.0, overlap_pct: float = 0.2, ) -> List[Tuple[float, float]]: """ Compute overlapping track segment window bounds [start, end] across a track section. """ step = window_len_m * (1.0 - overlap_pct) windows = [] curr = start_chainage_m while curr < end_chainage_m: w_end = min(curr + window_len_m, end_chainage_m) windows.append((round(curr, 3), round(w_end, 3))) curr += step if w_end >= end_chainage_m: break return windows123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201"""TrackChain Manifest & Checkpoint Fingerprinting Engine (tc.v1 SOTA).Provides cryptographically verified skip-logic based on SHA-256 config hashes,dataset label fingerprints, source weight hashes, and minimum metric quality gates."""
import osimport sysimport jsonimport hashlibfrom pathlib import Pathfrom typing import Dict, Any, Tuple, Optional, List, Unionimport yaml
def compute_file_sha256(filepath: Union[str, Path]) -> str: """Compute SHA-256 hash of a file.""" p = Path(filepath) if not p.exists() or not p.is_file(): return "" hasher = hashlib.sha256() with open(p, "rb") as f: while chunk := f.read(65536): hasher.update(chunk) return hasher.hexdigest()
def compute_config_hash(config_path: Optional[Union[str, Path]] = None, overrides: Optional[Dict[str, Any]] = None) -> str: """ Compute SHA-256 hash of a configuration YAML/JSON combined with CLI hyperparameters. """ hasher = hashlib.sha256()
if config_path: p = Path(config_path) if p.exists() and p.is_file(): with open(p, "rb") as f: hasher.update(f.read())
if overrides: # Sort keys for deterministic hashing overrides_str = json.dumps(overrides, sort_keys=True) hasher.update(overrides_str.encode("utf-8"))
return hasher.hexdigest()
def compute_dataset_hash(data_yaml_path: Union[str, Path]) -> str: """ Compute SHA-256 fingerprint of a dataset without reading all image pixels. Hashes: - The data.yaml configuration - Sorted list of label files, their counts, and file sizes across train/val/test splits. """ p = Path(data_yaml_path) if not p.exists(): return ""
hasher = hashlib.sha256()
with open(p, "r", encoding="utf-8") as f: try: data_cfg = yaml.safe_load(f) or {} except Exception: data_cfg = {}
hasher.update(json.dumps(data_cfg, sort_keys=True).encode("utf-8"))
# Resolve dataset root path raw_path = data_cfg.get("path", "") data_root = Path(raw_path) if Path(raw_path).is_absolute() else p.parent / raw_path
for split_key in ["train", "val", "validation", "test"]: split_val = data_cfg.get(split_key) if not split_val: continue
split_dir = data_root / split_val if not Path(split_val).is_absolute() else Path(split_val) # Search for corresponding labels folder labels_dir = split_dir.parent / "labels" if split_dir.name == "images" else split_dir / "labels"
if labels_dir.exists() and labels_dir.is_dir(): label_files = sorted(list(labels_dir.glob("*.txt"))) hasher.update(f"{split_key}_count:{len(label_files)}".encode("utf-8")) for lf in label_files: try: stat = lf.stat() hasher.update(f"{lf.name}:{stat.st_size}".encode("utf-8")) except Exception: continue elif split_dir.exists(): # For image folders (e.g. PatchCore normal good images) img_files = sorted(list(split_dir.glob("*.jpg")) + list(split_dir.glob("*.png"))) hasher.update(f"{split_key}_imgs:{len(img_files)}".encode("utf-8")) for img in img_files[:200]: # Hash first 200 filenames/sizes for speed try: hasher.update(f"{img.name}:{img.stat().st_size}".encode("utf-8")) except Exception: continue
return hasher.hexdigest()
def load_manifest(manifest_path: Union[str, Path]) -> Dict[str, Any]: """Load JSON manifest file safely.""" p = Path(manifest_path) if not p.exists(): return {} try: with open(p, "r", encoding="utf-8") as f: return json.load(f) except Exception: return {}
def save_manifest(manifest_path: Union[str, Path], data: Dict[str, Any]): """Save JSON manifest file atomically.""" p = Path(manifest_path) p.parent.mkdir(parents=True, exist_ok=True) with open(p, "w", encoding="utf-8") as f: json.dump(data, f, indent=2)
def check_training_skip( manifest_path: Union[str, Path], checkpoint_path: Union[str, Path], current_config_hash: str, current_dataset_hash: str, min_metrics: Optional[Dict[str, float]] = None, force: bool = False,) -> Tuple[bool, str]: """ Evaluate if training can be safely skipped based on manifest fingerprinting. Returns (should_skip, reason). """ if force: return False, "Force flag enabled (--force / --force-retrain)"
ckpt = Path(checkpoint_path) if not ckpt.exists(): return False, f"Checkpoint does not exist at {ckpt}"
manifest = load_manifest(manifest_path) if not manifest: return False, "Manifest file not found or invalid"
# Verify config hash saved_config_hash = manifest.get("config_hash", "") if saved_config_hash != current_config_hash: return False, f"Config hash changed ({saved_config_hash[:8]} -> {current_config_hash[:8]})"
# Verify dataset hash saved_dataset_hash = manifest.get("dataset_hash", "") if saved_dataset_hash != current_dataset_hash: return False, f"Dataset hash changed ({saved_dataset_hash[:8]} -> {current_dataset_hash[:8]})"
# Verify minimum metric quality gate if min_metrics: saved_metrics = manifest.get("metrics", {}) for metric_key, min_val in min_metrics.items(): actual_val = saved_metrics.get(metric_key, 0.0) if actual_val < min_val: return False, f"Metric gate failed: {metric_key}={actual_val:.4f} < minimum {min_val:.4f}"
return True, f"Manifest fingerprints match and quality gates passed (mAP50={manifest.get('metrics', {}).get('mAP50', 'N/A')})"
def check_export_skip( manifest_path: Union[str, Path], export_path: Union[str, Path], source_model_path: Union[str, Path], export_format: str = "onnx", force: bool = False,) -> Tuple[bool, str]: """ Evaluate if model export can be safely skipped based on source weight hash. Returns (should_skip, reason). """ if force: return False, "Force flag enabled (--force)"
exp_p = Path(export_path) if not exp_p.exists(): return False, f"Exported file does not exist at {exp_p}"
src_p = Path(source_model_path) if not src_p.exists(): return False, f"Source model does not exist at {src_p}"
current_src_hash = compute_file_sha256(src_p) manifest = load_manifest(manifest_path)
saved_export_entry = manifest.get(export_format, {}) if not saved_export_entry: return False, f"No manifest entry found for format '{export_format}'"
saved_src_hash = saved_export_entry.get("source_model_hash", "") if saved_src_hash != current_src_hash: return False, f"Source model weight hash changed ({saved_src_hash[:8]} -> {current_src_hash[:8]})"
return True, f"Export matches source model hash ({current_src_hash[:8]})"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788# Central Model Registry & Asset Librarian for TrackChain (tc.v1 SOTA).
import osfrom pathlib import Pathfrom typing import Any, Dict, Optional
_MODEL_REGISTRY: Dict[str, Any] = {}
def get_repo_root() -> Path: """Return the absolute path to the TrackChain repository root.""" return Path(__file__).resolve().parent.parent.parent
class ModelRegistry: """ Central librarian for model architectures, base weights, trained checkpoints, and quantized edge deployment exports. """ ROOT: Path = get_repo_root() ARTIFACTS_DIR: Path = ROOT / "artifacts" BASE_DIR: Path = ARTIFACTS_DIR / "base" CHECKPOINTS_DIR: Path = ARTIFACTS_DIR / "checkpoints" EXPORTS_DIR: Path = ARTIFACTS_DIR / "exports" CALIBRATION_DIR: Path = ARTIFACTS_DIR / "calibration"
@classmethod def get_base_weights(cls, domain: str, model_name: str) -> Path: """Return path to frozen/pretrained base weights (e.g. artifacts/base/vision/yolov8n.pt).""" target = cls.BASE_DIR / domain / model_name target.parent.mkdir(parents=True, exist_ok=True) return target
@classmethod def get_trained_weights(cls, domain: str, model_name: str, version: Optional[str] = None) -> Path: """Return path to trained checkpoint (e.g. artifacts/checkpoints/vision/yolo_rail_v0.1.pt).""" suffix = f"_{version}" if version else "" stem, ext = os.path.splitext(model_name) fname = f"{stem}{suffix}{ext}" if ext else f"{model_name}{suffix}.pt" target = cls.CHECKPOINTS_DIR / domain / fname target.parent.mkdir(parents=True, exist_ok=True) return target
@classmethod def get_export_path(cls, domain: str, model_name: str, fmt: str = "onnx") -> Path: """Return path to edge deployment artifact (e.g. artifacts/exports/vision/yolo_rail_v0.1_int8.onnx).""" stem, _ = os.path.splitext(model_name) fname = f"{stem}.{fmt}" target = cls.EXPORTS_DIR / domain / fname target.parent.mkdir(parents=True, exist_ok=True) return target
@classmethod def get_calibration_path(cls, model_name: str) -> Path: """Return path to calibration metadata (e.g. artifacts/calibration/yolo_temp_scale.json).""" stem, _ = os.path.splitext(model_name) target = cls.CALIBRATION_DIR / f"{stem}_calibration.json" target.parent.mkdir(parents=True, exist_ok=True) return target
def register_model(name: str): """Decorator to register a model class or factory function.""" def decorator(cls_or_fn): _MODEL_REGISTRY[name] = cls_or_fn return cls_or_fn return decorator
def load_model( model_name: str, checkpoint_path: Optional[str] = None, **kwargs,) -> Any: """Instantiate and load weights for any model registered by name.""" if model_name not in _MODEL_REGISTRY: raise ValueError( f"Model '{model_name}' not found in registry. Available: {list(_MODEL_REGISTRY.keys())}" )
model_cls = _MODEL_REGISTRY[model_name] instance = model_cls(**kwargs)
if checkpoint_path and os.path.exists(checkpoint_path): if hasattr(instance, "load_weights"): instance.load_weights(checkpoint_path)
return instance123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357# Shared contracts: ChainageWindow, TrackSegment, GeometryFeatures, CalibratedSignal, SegmentDecision (tc.v1).
from dataclasses import dataclass, fieldfrom typing import List, Optional, Dict, Any, Tuple, Unionfrom enum import Enumimport numpy as np
SCHEMA_VERSION = "tc.v1"
class DecisionType(str, Enum): OK = "OK" INSPECT_KNOWN = "INSPECT_KNOWN" INSPECT_NOVEL = "INSPECT_NOVEL"
Decision = DecisionType
class SeverityLevel(str, Enum): NORMAL = "normal" LOW = "low" MEDIUM = "medium" HIGH = "high" CRITICAL = "critical"
Severity = SeverityLevel
class DefectFamily(str, Enum): VISUAL_COMPONENT = "visual_component" VISUAL_SURFACE = "visual_surface" GEOMETRY = "geometry" NOVEL_ANOMALY = "novel_anomaly" OBSTRUCTION = "obstruction"
class DefectClass(str, Enum): NORMAL = "normal" MISSING_FASTENER = "missing_fastener" DAMAGED_FASTENER = "damaged_fastener" CRACK = "crack" CORRUGATION = "corrugation" SPALLING = "spalling" SQUAT = "squat" GAUGE_WIDENING = "gauge_widening" ALIGNMENT_FAULT = "alignment_fault" TWIST_EXCEEDANCE = "twist_exceedance" ROUGH_TRACK = "rough_track" DIPPED_JOINT = "dipped_joint" CYCLIC_TOP = "cyclic_top" TWIST_FAULT = "twist_fault" ALIGNMENT_KINK = "alignment_kink" BUCKLING_RISK = "buckling_risk" OBSTRUCTION = "obstruction" VISUAL_ANOMALY = "visual_anomaly" GEOMETRY_ANOMALY = "geometry_anomaly" UNCLASSIFIED = "unclassified_anomaly"
class SignalType(str, Enum): VISUAL_KNOWN = "visual_known" VISUAL_NOVEL = "visual_novel" GEOMETRY_KNOWN = "geometry_known" GEOMETRY_NOVEL = "geometry_novel" GEOMETRY_FAULT_TYPE = "geometry_known_type" GEOMETRY_KNOWN_TYPE = "geometry_known_type"
@dataclassclass ChainageWindow: """Represents a discrete physical distance window along the railway track.""" start_chainage_m: float end_chainage_m: float timestamps: np.ndarray distances: np.ndarray raw_telemetry: Dict[str, np.ndarray] = field(default_factory=dict) frames: List[np.ndarray] = field(default_factory=list)
@dataclassclass TrackSegment: """Unified physical track segment bundling spatial coordinates, vision frames, and telemetry.""" segment_id: str chainage_start_m: float chainage_end_m: float timestamp: Optional[Any] = None frames: List[np.ndarray] = field(default_factory=list) telemetry: Dict[str, np.ndarray] = field(default_factory=dict) section_type: str = "mainline_standard"
@dataclassclass ExplainabilityTrace: """Detailed explainability trace linking an ML decision back to raw model signals and spatial bins.""" model_name: str signal_type: SignalType raw_score: float calibrated_score: float threshold: float fired: bool spatial_bin: int = 0 attention_peak: Optional[int] = None reconstruction_error: Optional[float] = None
@dataclassclass GeometryFeatures: """Deterministic track geometry metrics compliant with EN 13848-1.""" chainage_m: float gauge_dev_mm: float cant_mm: float twist_3m_mm_per_m: float vertical_profile_d1_mm: float alignment_d1_mm: float rms_vibration_g: float
@dataclassclass CalibratedSignal: """Output of a model after temperature scaling or threshold calibration.""" stream_name: str = "signal" raw_score: float = 0.0 calibrated_prob: float = 0.0 predicted_class: Optional[DefectClass] = None is_anomaly: bool = False signal_type: SignalType = SignalType.VISUAL_KNOWN threshold: float = 0.5 bbox: Optional[Tuple[float, float, float, float]] = None # (x1, y1, x2, y2) explanation: Optional[Union[str, Dict[str, Any]]] = None metadata: Dict[str, Any] = field(default_factory=dict)
def __init__( self, stream_name: Optional[str] = None, raw_score: float = 0.0, calibrated_prob: Optional[float] = None, predicted_class: Optional[DefectClass] = None, is_anomaly: Optional[bool] = None, signal_type: SignalType = SignalType.VISUAL_KNOWN, threshold: float = 0.5, bbox: Optional[Tuple[float, float, float, float]] = None, explanation: Optional[Union[str, Dict[str, Any]]] = None, metadata: Optional[Dict[str, Any]] = None, name: Optional[str] = None, value: Optional[float] = None, label: Optional[DefectClass] = None, fired: Optional[bool] = None, model_version: Optional[str] = None, **kwargs, ): self.stream_name = stream_name or name or "signal" self.raw_score = float(raw_score) self.calibrated_prob = float(calibrated_prob if calibrated_prob is not None else (value if value is not None else 0.0)) self.predicted_class = predicted_class if predicted_class is not None else label self.is_anomaly = is_anomaly if is_anomaly is not None else (fired if fired is not None else False) self.signal_type = signal_type self.threshold = float(threshold) self.bbox = bbox self.explanation = explanation self.metadata = metadata or {} if model_version: self.metadata["model_version"] = model_version if kwargs: self.metadata.update(kwargs)
@property def name(self) -> str: return self.stream_name
@property def value(self) -> float: return self.calibrated_prob
@property def fired(self) -> bool: return self.is_anomaly
@property def label(self) -> Optional[DefectClass]: return self.predicted_class
def to_dict(self) -> Dict[str, Any]: return { "name": self.stream_name, "stream_name": self.stream_name, "model_version": self.metadata.get("model_version", "0.1.0"), "signal_type": self.signal_type.value if hasattr(self.signal_type, "value") else str(self.signal_type), "value": float(self.calibrated_prob), "raw_score": float(self.raw_score), "calibrated_prob": float(self.calibrated_prob), "threshold": float(self.threshold), "fired": bool(self.is_anomaly), "is_anomaly": bool(self.is_anomaly), "predicted_class": self.predicted_class.value if hasattr(self.predicted_class, "value") else str(self.predicted_class) if self.predicted_class else None, "bbox": list(self.bbox) if self.bbox else None, "explanation": self.explanation, "metadata": self.metadata, }
@dataclassclass SegmentSignals: """Unified collection of multi-modal signals associated with a TrackSegment.""" v_known: List[CalibratedSignal] = field(default_factory=list) v_novel: List[CalibratedSignal] = field(default_factory=list) g_known: List[CalibratedSignal] = field(default_factory=list) g_novel: List[CalibratedSignal] = field(default_factory=list) g_type: List[CalibratedSignal] = field(default_factory=list)
@property def all_signals(self) -> List[CalibratedSignal]: return self.v_known + self.v_novel + self.g_known + self.g_novel + self.g_type
def get_primary(self, signal_type: SignalType) -> CalibratedSignal: """Extract the most prominent CalibratedSignal matching the given stream type.""" matching = [s for s in self.all_signals if s.signal_type == signal_type] if matching: # Return signal with highest calibrated probability or fired status return max(matching, key=lambda s: (s.is_anomaly, s.calibrated_prob)) return CalibratedSignal( stream_name=signal_type.value, raw_score=0.0, calibrated_prob=0.0, signal_type=signal_type, is_anomaly=False, predicted_class=DefectClass.NORMAL, )
@dataclassclass MediaReference: """Metadata pointing to S3 media asset associated with an ML inference result.""" media_id: Optional[str] = None s3_key: Optional[str] = None offset_seconds: float = 0.0 frame_index: Optional[int] = None
@dataclassclass SegmentDecision: """Final operational decision emitted by the persistence rule fusion engine for a track segment.""" window_id: str = "win-00000" start_chainage_m: float = 0.0 end_chainage_m: float = 0.0 decision: DecisionType = DecisionType.OK confidence: float = 0.98 primary_fault: Optional[Union[DefectClass, str]] = None defect_family: DefectFamily = DefectFamily.VISUAL_COMPONENT severity: SeverityLevel = SeverityLevel.LOW signals: List[CalibratedSignal] = field(default_factory=list) evidence: Optional[MediaReference] = None timestamp: Optional[str] = None schema_version: str = SCHEMA_VERSION source: Optional[str] = None cross_modal_boost: float = 1.0 action: str = "Routine inspection cycle maintained." traces: List[ExplainabilityTrace] = field(default_factory=list)
def __init__( self, decision: Optional[DecisionType] = None, primary_fault: Optional[Union[DefectClass, str]] = None, severity: Optional[SeverityLevel] = None, window_id: str = "win-00000", start_chainage_m: float = 0.0, end_chainage_m: float = 0.0, confidence: float = 0.98, defect_family: DefectFamily = DefectFamily.VISUAL_COMPONENT, signals: Optional[List[CalibratedSignal]] = None, evidence: Optional[MediaReference] = None, timestamp: Optional[str] = None, schema_version: str = SCHEMA_VERSION, source: Optional[str] = None, cross_modal_boost: float = 1.0, action: str = "Routine inspection cycle maintained.", traces: Optional[List[ExplainabilityTrace]] = None, **kwargs, ): self.decision = decision if decision is not None else DecisionType.OK self.primary_fault = primary_fault or kwargs.get("primary_defect") self.severity = severity if severity is not None else SeverityLevel.LOW self.window_id = window_id self.start_chainage_m = float(start_chainage_m if start_chainage_m != 0.0 else kwargs.get("chainage_start_m", 0.0)) self.end_chainage_m = float(end_chainage_m if end_chainage_m != 0.0 else kwargs.get("chainage_end_m", 0.0)) self.confidence = float(confidence) self.defect_family = defect_family self.signals = signals if signals is not None else [] self.evidence = evidence self.timestamp = timestamp self.schema_version = schema_version self.source = source self.cross_modal_boost = float(cross_modal_boost) self.action = str(action or kwargs.get("action", "Routine inspection cycle maintained.")) self.traces = traces if traces is not None else [] for k, v in kwargs.items(): if k in ("chainage_start_m", "start_chainage_m"): self.start_chainage_m = float(v) elif k in ("chainage_end_m", "end_chainage_m"): self.end_chainage_m = float(v) elif k in ("primary_defect", "primary_fault"): self.primary_fault = v else: setattr(self, k, v)
@property def primary_defect(self) -> Optional[Union[DefectClass, str]]: return self.primary_fault
@primary_defect.setter def primary_defect(self, value: Optional[Union[DefectClass, str]]) -> None: self.primary_fault = value
@property def chainage_start_m(self) -> float: return self.start_chainage_m
@chainage_start_m.setter def chainage_start_m(self, value: float) -> None: self.start_chainage_m = float(value)
@property def chainage_end_m(self) -> float: return self.end_chainage_m
@chainage_end_m.setter def chainage_end_m(self, value: float) -> None: self.end_chainage_m = float(value)
def to_dict(self) -> Dict[str, Any]: prim_def = self.primary_fault if hasattr(prim_def, "value"): prim_def_str = prim_def.value elif prim_def is not None: prim_def_str = str(prim_def) else: prim_def_str = None
return { "schema_version": self.schema_version, "window_id": self.window_id, "chainage_start_m": float(self.start_chainage_m), "chainage_end_m": float(self.end_chainage_m), "start_chainage_m": float(self.start_chainage_m), "end_chainage_m": float(self.end_chainage_m), "decision": self.decision.value if hasattr(self.decision, "value") else str(self.decision), "severity": self.severity.value if hasattr(self.severity, "value") else str(self.severity), "confidence": round(float(self.confidence), 4), "primary_defect": prim_def_str, "primary_fault": prim_def_str, "action": getattr(self, "action", "Routine inspection cycle maintained."), "section_type": getattr(self, "section_type", "mainline_standard"), "cross_modal_boost": float(self.cross_modal_boost), "signals": [s.to_dict() if hasattr(s, "to_dict") else s for s in self.signals], "timestamp": self.timestamp, }1# Data package marker.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566# PyTorch Datasets for RSDDs, NEU, and fastener imagery.
import osfrom typing import Callable, List, Optional, Tupleimport numpy as npimport torchfrom torch.utils.data import Dataset
class RailSurfaceDefectDataset(Dataset): """PyTorch dataset for RSDDs and NEU rail surface defect images."""
def __init__( self, image_paths: List[str], labels: Optional[List[int]] = None, transform: Optional[Callable] = None, is_normal_only: bool = False, ): self.image_paths = image_paths self.labels = labels if labels is not None else [0] * len(image_paths) self.transform = transform self.is_normal_only = is_normal_only
if self.is_normal_only and labels is not None: normal_indices = [i for i, l in enumerate(labels) if l == 0] self.image_paths = [self.image_paths[i] for i in normal_indices] self.labels = [0] * len(self.image_paths)
def __len__(self) -> int: return len(self.image_paths)
def __getitem__(self, idx: int) -> Tuple[torch.Tensor, int]: path = self.image_paths[idx] # Generate dummy array if file doesn't exist on disk yet if os.path.exists(path): import cv2 img = cv2.imread(path) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) else: img = np.zeros((224, 224, 3), dtype=np.uint8)
if self.transform: img_tensor = self.transform(img) else: img_tensor = torch.from_numpy(img).permute(2, 0, 1).float() / 255.0
return img_tensor, self.labels[idx]
class GeometrySequenceDataset(Dataset): """PyTorch dataset for EN 13848 multi-channel geometry sequence windows."""
def __init__( self, features: np.ndarray, # shape: [N, window_len, num_channels] labels: np.ndarray, # shape: [N] ): self.features = torch.from_numpy(features).float() self.labels = torch.from_numpy(labels).long()
def __len__(self) -> int: return len(self.features)
def __getitem__(self, idx: int) -> Tuple[torch.Tensor, torch.Tensor]: return self.features[idx], self.labels[idx]12345678910111213141516171819202122232425262728293031323334353637# DataLoader builders with train/val splits and augmentation.
from typing import Tuplefrom torch.utils.data import DataLoader, random_split, Dataset
def build_dataloaders( dataset: Dataset, batch_size: int = 32, val_split: float = 0.2, num_workers: int = 0, seed: int = 42,) -> Tuple[DataLoader, DataLoader]: """Create reproducible training and validation data loaders.""" val_size = int(len(dataset) * val_split) train_size = len(dataset) - val_size
train_set, val_set = random_split( dataset, [train_size, val_size], generator=None, )
train_loader = DataLoader( train_set, batch_size=batch_size, shuffle=True, num_workers=num_workers, ) val_loader = DataLoader( val_set, batch_size=batch_size, shuffle=False, num_workers=num_workers, )
return train_loader, val_loader123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112"""Generate synthetic vision and geometry data with known fault signatures (tc.v1 SOTA).Provides multi-modal generation for: - Continuous track geometry conforming to EN 13848-1 - Procedural vision defect injection (crack, missing fastener, defective clip, obstruction)"""
from typing import Dict, List, Tuple, Optional, Anyimport numpy as npimport cv2
from ml.data.synthetic_vision import ( SyntheticRailDefectGenerator, sanitize_bbox, CLASS_MAPPING, CLASS_NAMES,)
def generate_synthetic_geometry( length_m: float = 1000.0, step_m: float = 0.25, fault_probability: float = 0.05, random_seed: int = 42,) -> Dict[str, np.ndarray]: """Generate synthetic continuous track geometry conforming to EN 13848-1.""" np.random.seed(random_seed) n_points = int(length_m / step_m) chainage = np.linspace(0, length_m, n_points)
# Base nominal signals gauge = 1435.0 + np.random.normal(0, 0.8, n_points) cant = 10.0 * np.sin(chainage / 200.0) + np.random.normal(0, 1.2, n_points) twist = np.gradient(cant, step_m) * 3.0 + np.random.normal(0, 0.2, n_points) unevenness = 0.5 * np.sin(chainage / 15.0) + np.random.normal(0, 0.3, n_points) alignment = 0.6 * np.cos(chainage / 25.0) + np.random.normal(0, 0.3, n_points) vibration_rms = 0.8 + 0.2 * np.abs(np.random.normal(0, 1.0, n_points))
# Inject discrete fault signatures labels = np.zeros(n_points, dtype=int) n_faults = int(length_m * fault_probability / 50.0)
for _ in range(n_faults): center_idx = np.random.randint(50, n_points - 50) fault_type = np.random.choice([1, 2, 3]) # 1: Gauge widening, 2: Twist, 3: Corrugation window_size = np.random.randint(10, 40) idx_range = slice(center_idx - window_size // 2, center_idx + window_size // 2)
if fault_type == 1: gauge[idx_range] += np.random.uniform(8.0, 18.0) labels[idx_range] = 1 elif fault_type == 2: twist[idx_range] += np.random.uniform(3.5, 6.0) * np.sign(np.random.randn()) labels[idx_range] = 2 elif fault_type == 3: unevenness[idx_range] += 3.0 * np.sin(np.arange(window_size) * 0.8) vibration_rms[idx_range] += np.random.uniform(1.8, 3.5) labels[idx_range] = 3
return { "chainage_m": chainage, "gauge_mm": gauge, "cant_mm": cant, "twist_mm_per_m": twist, "vertical_unevenness_mm": unevenness, "alignment_mm": alignment, "vibration_rms_g": vibration_rms, "fault_labels": labels, }
def generate_synthetic_defect_image( defect_type: str = "crack", height: int = 640, width: int = 640,) -> Tuple[np.ndarray, Optional[List[float]]]: """ Generate high-fidelity synthetic rail surface patch with specific defect and YOLO bounding box. """ # Create base track texture base = np.zeros((height, width, 3), dtype=np.uint8) ballast = np.array([80, 75, 65], dtype=np.float32) noise = np.random.normal(0, 15, (height, width, 3)) base[:] = np.clip(ballast + noise, 0, 255).astype(np.uint8)
# Add rails rail_w = int(width * 0.08) for offset in [int(width * 0.32), int(width * 0.68)]: cv2.rectangle(base, (offset - rail_w // 2, 0), (offset + rail_w // 2, height), (55, 55, 60), -1) cv2.line(base, (offset, 0), (offset, height), (140, 140, 150), 3)
gen = SyntheticRailDefectGenerator() if defect_type == "crack": return gen.inject_crack(base) elif defect_type in ["missing_fastener", "fastener"]: return gen.inject_missing_fastener(base) elif defect_type in ["defective_clip", "damaged_fastener", "clip"]: return gen.inject_defective_clip(base) elif defect_type in ["obstruction", "debris"]: return gen.inject_obstruction(base) else: return gen.inject_crack(base)
__all__ = [ "generate_synthetic_geometry", "generate_synthetic_defect_image", "SyntheticRailDefectGenerator", "sanitize_bbox", "CLASS_MAPPING", "CLASS_NAMES",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219"""ml/data/synthetic_geometry.pyGenerates EN 13848-compliant synthetic geometry sequences for Bi-LSTM training and evaluation."""
from typing import Dict, Tuple, List, Optional, Union, Anyfrom enum import IntEnumimport numpy as npfrom scipy.ndimage import gaussian_filter1dimport torchfrom torch.utils.data import Dataset, DataLoader
from ml.core.schema import DefectClass
class GeometryFaultType(IntEnum): NORMAL = 0 DIPPED_JOINT = 1 CYCLIC_TOP = 2 TWIST_FAULT = 3 ALIGNMENT_KINK = 4 BUCKLING_RISK = 5
CLASS_MAP = { 0: "NORMAL", 1: "DIPPED_JOINT", 2: "CYCLIC_TOP", 3: "TWIST_FAULT", 4: "ALIGNMENT_KINK", 5: "BUCKLING_RISK",}
CLASS_TO_DEFECT_ENUM = { 0: DefectClass.NORMAL, 1: DefectClass.DIPPED_JOINT, 2: DefectClass.CYCLIC_TOP, 3: DefectClass.TWIST_FAULT, 4: DefectClass.ALIGNMENT_KINK, 5: DefectClass.BUCKLING_RISK,}
DEFECT_ENUM_TO_CLASS = {v: k for k, v in CLASS_TO_DEFECT_ENUM.items()}FAULT_TYPES = CLASS_MAP
class SyntheticGeometryDataset(Dataset): """ Parametric synthetic dataset generating 5-channel EN 13848 track geometry sequences (0: Twist_3m, 1: Versine_10m, 2: Versine_20m, 3: Unevenness_10m, 4: Cant). """
FAULT_TYPES = CLASS_MAP
def __init__( self, num_samples: int = 2000, seq_len: int = 80, bin_size: float = 0.25, noise_std: float = 0.5, num_classes: int = 6, random_seed: Optional[int] = None, ): self.num_samples = num_samples self.seq_len = seq_len self.bin_size = bin_size self.noise_std = noise_std self.num_classes = num_classes self.rng = np.random.RandomState(random_seed) self.data, self.labels = self._generate_dataset()
def _generate_psd_noise(self, length: int) -> np.ndarray: """Generates 1D track noise based on EN 13848-2 PSD decay.""" freqs = np.fft.rfftfreq(length, d=self.bin_size) freqs[0] = 1e-6 psd = 0.005 / (freqs**2 + 0.001) phase = self.rng.uniform(0, 2 * np.pi, len(freqs)) profile = np.fft.irfft(np.sqrt(psd) * np.exp(1j * phase), n=length) return profile * 100.0 * self.noise_std # Scaled to physical mm
def _generate_dataset(self) -> Tuple[torch.Tensor, torch.Tensor]: X = np.zeros((self.num_samples, self.seq_len, 5), dtype=np.float32) y = np.zeros(self.num_samples, dtype=np.int64)
# Features: 0:Twist, 1:Versine10m, 2:Versine20m, 3:Unevenness, 4:Cant for i in range(self.num_samples): # Base noise for all 5 channels base_noise = np.column_stack([self._generate_psd_noise(self.seq_len) for _ in range(5)]) X[i] = base_noise
# Assign class (balanced distribution) fault_type = i % self.num_classes y[i] = fault_type
if fault_type == GeometryFaultType.NORMAL: continue # Just baseline PSD track noise
# Inject parametric fault shape at a random location in the window center = int(self.rng.randint(20, self.seq_len - 20))
if fault_type == GeometryFaultType.DIPPED_JOINT: # Gaussian dip in Unevenness (Channel 3) x_vals = np.arange(self.seq_len, dtype=np.float32) dip = -8.0 * np.exp(-0.5 * ((x_vals - center) / 2.0) ** 2) X[i, :, 3] += dip
elif fault_type == GeometryFaultType.CYCLIC_TOP: # Sine wave in Unevenness (Channel 3) x_vals = np.arange(self.seq_len, dtype=np.float32) * self.bin_size wave = 5.0 * np.sin(2 * np.pi * x_vals / 6.0) # 5mm amp, 6m wavelength window = np.exp(-0.5 * ((x_vals - center * self.bin_size) / 4.0) ** 2) X[i, :, 3] += wave * window
elif fault_type == GeometryFaultType.TWIST_FAULT: # Tanh step in Cant (Channel 4) and Twist (Channel 0) x_vals = np.arange(self.seq_len, dtype=np.float32) ramp = 4.0 * np.tanh((x_vals - center) / 1.5) X[i, :, 4] += ramp # Twist is spatial derivative of cant over 3m base X[i, :, 0] += np.gradient(ramp, self.bin_size) * 3.0
elif fault_type == GeometryFaultType.ALIGNMENT_KINK: # Step function in Versine (Channels 1 & 2) x_vals = np.arange(self.seq_len, dtype=np.float32) kink = 6.0 * np.tanh((x_vals - center) / 0.5) X[i, :, 1] += kink X[i, :, 2] += kink * 0.8 # 20m chord sees it slightly smoothed
elif fault_type == GeometryFaultType.BUCKLING_RISK: # Broad lateral bow in Versine (Channels 1 & 2) x_vals = np.arange(self.seq_len, dtype=np.float32) bow = 10.0 * np.exp(-0.5 * ((x_vals - center) / 8.0) ** 2) X[i, :, 1] += bow X[i, :, 2] += bow * 1.2
return torch.tensor(X, dtype=torch.float32), torch.tensor(y, dtype=torch.long)
def __len__(self) -> int: return self.num_samples
def __getitem__(self, idx: int) -> Tuple[torch.Tensor, torch.Tensor]: return self.data[idx], self.labels[idx]
class ParametricGeometryGenerator: """Convenience generator for single parametric geometry windows with metadata."""
def __init__( self, window_length_m: float = 20.0, step_m: float = 0.25, random_seed: Optional[int] = None, ): self.window_length_m = window_length_m self.step_m = step_m self.seq_len = int(round(window_length_m / step_m)) self.rng = np.random.RandomState(random_seed)
def generate_window( self, defect_class: Union[int, DefectClass] = 0, spatial_shift_m: Optional[float] = None, amplitude_scale: float = 1.0, noise_level_mm: float = 0.5, ) -> Tuple[np.ndarray, int, Dict[str, Any]]: if isinstance(defect_class, DefectClass): cid = DEFECT_ENUM_TO_CLASS.get(defect_class, 0) else: cid = int(defect_class)
center_bin = int(round(spatial_shift_m / self.step_m)) if spatial_shift_m is not None else int(self.rng.randint(20, self.seq_len - 20)) center_bin = int(np.clip(center_bin, 10, self.seq_len - 10))
ds = SyntheticGeometryDataset( num_samples=max(6, cid + 1), seq_len=self.seq_len, bin_size=self.step_m, noise_std=noise_level_mm, num_classes=6, random_seed=int(self.rng.randint(0, 100000)), ) # Inject exact requested class feat, _ = ds[cid] feat_np = feat.numpy().copy()
metadata = { "class_id": cid, "class_name": CLASS_MAP.get(cid, "UNKNOWN"), "defect_center_bin": center_bin, "defect_center_m": float(center_bin * self.step_m), "amplitude_mm": float(amplitude_scale), } return feat_np, cid, metadata
def create_synthetic_data_loaders( train_samples_per_class: int = 250, val_samples_per_class: int = 50, batch_size: int = 32, num_classes: int = 5, random_seed: int = 42,) -> Tuple[DataLoader, DataLoader]: """Factory creating Train and Validation DataLoaders.""" train_dataset = SyntheticGeometryDataset( num_samples=train_samples_per_class * num_classes, num_classes=num_classes, random_seed=random_seed, ) val_dataset = SyntheticGeometryDataset( num_samples=val_samples_per_class * num_classes, num_classes=num_classes, random_seed=random_seed + 999, )
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True) val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)
return train_loader, val_loader123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425"""TrackChain Synthetic Visual Defect Generation Engine (tc.v1 SOTA).Generates photorealistic railway defects on normal track imagery or procedural canvases: - Class 0: missing_fastener (fastener removal, empty tie socket inpainting, rust residue) - Class 1: defective_clip (deformed, fractured, or displaced Pandrol elastic clips) - Class 2: crack (rolling-contact fatigue, branching cracks, transverse fissures on rail heads) - Class 3: obstruction (ballast rocks, metal tools, debris, wooden blocks on trackbed)
Outputs standard YOLO-format annotations [class_id, x_center, y_center, width, height]."""
import mathimport randomfrom typing import List, Dict, Tuple, Optional, Union, Anyfrom pathlib import Pathimport numpy as npimport cv2
CLASS_MAPPING = { "missing_fastener": 0, "defective_clip": 1, "crack": 2, "obstruction": 3,}
CLASS_NAMES = ["missing_fastener", "defective_clip", "crack", "obstruction"]
def sanitize_bbox(bbox: List[float]) -> Optional[List[float]]: """Sanitize and clamp YOLO bbox coordinates [x_center, y_center, width, height].""" if len(bbox) < 4: return None x, y, w, h = float(bbox[0]), float(bbox[1]), float(bbox[2]), float(bbox[3]) if w <= 0.005 or h <= 0.005: return None x = max(0.01, min(0.99, x)) y = max(0.01, min(0.99, y)) w = max(0.01, min(1.0, w)) h = max(0.01, min(1.0, h))
half_w = w / 2.0 half_h = h / 2.0 x1 = max(0.0, x - half_w) y1 = max(0.0, y - half_h) x2 = min(1.0, x + half_w) y2 = min(1.0, y + half_h)
new_w = x2 - x1 new_h = y2 - y1 if new_w <= 0.005 or new_h <= 0.005: return None
new_x = (x1 + x2) / 2.0 new_y = (y1 + y2) / 2.0 return [round(new_x, 6), round(new_y, 6), round(new_w, 6), round(new_h, 6)]
class SyntheticRailDefectGenerator: """ Photorealistic synthetic defect injection system for railway infrastructure. Uses normal track imagery as canvas to synthesize domain-accurate defect signatures. """
def __init__(self, random_seed: Optional[int] = None): if random_seed is not None: random.seed(random_seed) np.random.seed(random_seed)
# ------------------------------------------------------------------------- # 1. Crack Generation (Railhead surface defect - Class 2) # ------------------------------------------------------------------------- def generate_crack_patch( self, width: int = 120, height: int = 120, crack_type: str = "branching" ) -> Tuple[np.ndarray, np.ndarray]: """ Generate an alpha-masked crack patch with branching, irregular width, and realistic shadow/highlight edges. """ patch = np.zeros((height, width, 3), dtype=np.uint8) alpha = np.zeros((height, width), dtype=np.float32)
start_x = random.randint(int(width * 0.3), int(width * 0.7)) start_y = random.randint(10, 25) curr_x, curr_y = start_x, start_y
main_points = [(curr_x, curr_y)] angle = random.uniform(0.35 * math.pi, 0.65 * math.pi) # downwards with jitter
while curr_y < height - 15: step_len = random.randint(4, 9) angle += random.uniform(-0.4, 0.4) curr_x += int(step_len * math.cos(angle)) curr_y += int(step_len * math.sin(angle)) curr_x = max(5, min(width - 5, curr_x)) curr_y = max(5, min(height - 5, curr_y)) main_points.append((curr_x, curr_y))
# Render main fissure with variable thickness and dark core for i in range(len(main_points) - 1): pt1 = main_points[i] pt2 = main_points[i + 1] thickness = random.choice([2, 3, 2, 1]) darkness = random.randint(15, 45) cv2.line(patch, pt1, pt2, (darkness, darkness, darkness + 5), thickness) cv2.line(alpha, pt1, pt2, 1.0, thickness + 1)
# Highlight edge (specular rail reflection next to fissure) offset_pt1 = (pt1[0] + 1, pt1[1]) offset_pt2 = (pt2[0] + 1, pt2[1]) cv2.line(patch, offset_pt1, offset_pt2, (180, 185, 190), 1) cv2.line(alpha, offset_pt1, offset_pt2, 0.4, 1)
# Add secondary branching fissures if crack_type == "branching" and len(main_points) > 4: num_branches = random.randint(1, 3) branch_origins = random.sample(main_points[2:-2], min(num_branches, len(main_points) - 4)) for bx, by in branch_origins: branch_angle = angle + random.choice([-1.0, 1.0]) * random.uniform(0.6, 1.2) bx_curr, by_curr = bx, by for _ in range(random.randint(3, 6)): b_step = random.randint(3, 7) bx_curr += int(b_step * math.cos(branch_angle)) by_curr += int(b_step * math.sin(branch_angle)) bx_curr = max(3, min(width - 3, bx_curr)) by_curr = max(3, min(height - 3, by_curr)) cv2.line(patch, (bx, by), (bx_curr, by_curr), (25, 25, 30), 1) cv2.line(alpha, (bx, by), (bx_curr, by_curr), 0.8, 1) bx, by = bx_curr, by
# Smooth alpha mask for seamless blending alpha = cv2.GaussianBlur(alpha, (3, 3), 0.5) return patch, alpha
def inject_crack( self, image: np.ndarray, bbox_loc: Optional[Tuple[int, int, int, int]] = None ) -> Tuple[np.ndarray, Optional[List[float]]]: """ Inject synthetic crack onto rail head region. Returns modified image and normalized YOLO bbox. """ h, w = image.shape[:2] img = image.copy()
if bbox_loc is not None: x1, y1, x2, y2 = bbox_loc cw, ch = max(30, x2 - x1), max(30, y2 - y1) else: # Place crack along rail head area (typically vertical strip ~30% to 70% width) cw = random.randint(int(w * 0.08), int(w * 0.22)) ch = random.randint(int(h * 0.12), int(h * 0.35)) # Pick left or right rail zone rail_center_x = random.choice([int(w * 0.32), int(w * 0.68)]) x1 = max(5, min(w - cw - 5, rail_center_x - cw // 2 + random.randint(-15, 15))) y1 = random.randint(int(h * 0.10), max(10, h - ch - int(h * 0.10))) x2, y2 = x1 + cw, y1 + ch
crack_patch, alpha = self.generate_crack_patch(cw, ch) alpha_3d = np.expand_dims(alpha, axis=-1)
roi = img[y1:y2, x1:x2].astype(np.float32) blended = roi * (1.0 - alpha_3d) + crack_patch.astype(np.float32) * alpha_3d img[y1:y2, x1:x2] = np.clip(blended, 0, 255).astype(np.uint8)
# Compute YOLO normalized bbox [x_center, y_center, width, height] xc = (x1 + x2) / (2.0 * w) yc = (y1 + y2) / (2.0 * h) bw = (x2 - x1) / float(w) bh = (y2 - y1) / float(h) clean_box = sanitize_bbox([xc, yc, bw, bh]) return img, clean_box
# ------------------------------------------------------------------------- # 2. Missing Fastener Generation (Class 0) # ------------------------------------------------------------------------- def inject_missing_fastener( self, image: np.ndarray, bbox_loc: Optional[Tuple[int, int, int, int]] = None ) -> Tuple[np.ndarray, Optional[List[float]]]: """ Simulate missing Pandrol fastener / clip. Inpaints the clip area with empty tie socket, rust ring, and exposed baseplate/sleeper. """ h, w = image.shape[:2] img = image.copy()
if bbox_loc is not None: x1, y1, x2, y2 = bbox_loc fw, fh = max(25, x2 - x1), max(25, y2 - y1) else: # Fasteners sit adjacent to rails on sleepers fw = random.randint(int(w * 0.07), int(w * 0.14)) fh = random.randint(int(h * 0.07), int(h * 0.14)) # Typical fastener locations on baseplate (left/right of rail lines) x_band = random.choice([int(w * 0.22), int(w * 0.42), int(w * 0.58), int(w * 0.78)]) x1 = max(5, min(w - fw - 5, x_band - fw // 2 + random.randint(-10, 10))) y1 = random.randint(int(h * 0.15), max(10, h - fh - int(h * 0.15))) x2, y2 = x1 + fw, y1 + fh
roi = img[y1:y2, x1:x2] # Inpaint: replace clip with sleeper/baseplate texture + dark vacant socket cavity mask = np.zeros((fh, fw), dtype=np.uint8) cx, cy = fw // 2, fh // 2 rx, ry = int(fw * 0.35), int(fh * 0.35) cv2.ellipse(mask, (cx, cy), (rx, ry), 0, 0, 360, 255, -1)
# Baseplate background color sampled from surrounding sleeper surrounding_color = np.median(roi, axis=(0, 1)).astype(np.float32) # Empty cavity texture (dark hole with rust ring) cavity = np.zeros((fh, fw, 3), dtype=np.uint8) cavity[:] = np.clip(surrounding_color * 0.85, 0, 255).astype(np.uint8)
# Rust ring around hole rust_color = (random.randint(25, 45), random.randint(55, 85), random.randint(110, 150)) cv2.ellipse(cavity, (cx, cy), (rx, ry), 0, 0, 360, rust_color, 3) # Dark void / bolt hole void_color = (random.randint(15, 30), random.randint(15, 30), random.randint(20, 35)) cv2.ellipse(cavity, (cx, cy), (int(rx * 0.6), int(ry * 0.6)), 0, 0, 360, void_color, -1)
# Add noise noise = np.random.normal(0, 12, (fh, fw, 3)) cavity = np.clip(cavity.astype(np.float32) + noise, 0, 255).astype(np.uint8)
# Blend cavity into ROI using smoothed mask mask_f = cv2.GaussianBlur(mask.astype(np.float32) / 255.0, (5, 5), 1.0) mask_3d = np.expand_dims(mask_f, axis=-1) blended = roi.astype(np.float32) * (1.0 - mask_3d) + cavity.astype(np.float32) * mask_3d img[y1:y2, x1:x2] = np.clip(blended, 0, 255).astype(np.uint8)
xc = (x1 + x2) / (2.0 * w) yc = (y1 + y2) / (2.0 * h) bw = (x2 - x1) / float(w) bh = (y2 - y1) / float(h) clean_box = sanitize_bbox([xc, yc, bw, bh]) return img, clean_box
# ------------------------------------------------------------------------- # 3. Defective / Damaged Clip Generation (Class 1) # ------------------------------------------------------------------------- def inject_defective_clip( self, image: np.ndarray, bbox_loc: Optional[Tuple[int, int, int, int]] = None ) -> Tuple[np.ndarray, Optional[List[float]]]: """ Simulate deformed, cracked, broken, or misaligned Pandrol clip. Renders damaged clip geometry (sheared toe, fractured leg, heavy corrosion). """ h, w = image.shape[:2] img = image.copy()
if bbox_loc is not None: x1, y1, x2, y2 = bbox_loc cw, ch = max(30, x2 - x1), max(30, y2 - y1) else: cw = random.randint(int(w * 0.08), int(w * 0.15)) ch = random.randint(int(h * 0.08), int(h * 0.15)) x_band = random.choice([int(w * 0.24), int(w * 0.40), int(w * 0.60), int(w * 0.76)]) x1 = max(5, min(w - cw - 5, x_band - cw // 2 + random.randint(-10, 10))) y1 = random.randint(int(h * 0.15), max(10, h - ch - int(h * 0.15))) x2, y2 = x1 + cw, y1 + ch
roi = img[y1:y2, x1:x2] patch = np.zeros((ch, cw, 3), dtype=np.uint8) alpha = np.zeros((ch, cw), dtype=np.float32)
# Draw deformed / severed e-clip loop clip_metal_color = (random.randint(60, 100), random.randint(65, 110), random.randint(80, 130)) rust_color = (random.randint(20, 45), random.randint(45, 80), random.randint(120, 170))
# Fractured loop arcs pts = np.array([ [int(cw * 0.2), int(ch * 0.8)], [int(cw * 0.25), int(ch * 0.3)], [int(cw * 0.6), int(ch * 0.2)], [int(cw * 0.85), int(ch * 0.45)], [int(cw * 0.7), int(ch * 0.7)], ], np.int32)
# Break the clip: omit middle section or deform angle break_idx = random.randint(1, 3) pts1 = pts[:break_idx] pts2 = pts[break_idx:]
if len(pts1) >= 2: cv2.polylines(patch, [pts1], False, clip_metal_color, thickness=random.choice([4, 5])) cv2.polylines(alpha, [pts1], False, 0.95, thickness=random.choice([4, 5])) if len(pts2) >= 2: # Shift fractured piece (sheared/displaced) pts2_shifted = pts2 + np.array([random.randint(4, 10), random.randint(-6, 6)]) cv2.polylines(patch, [pts2_shifted], False, rust_color, thickness=random.choice([4, 5])) cv2.polylines(alpha, [pts2_shifted], False, 0.95, thickness=random.choice([4, 5]))
# Corrosion & fracture highlights noise = np.random.normal(0, 15, (ch, cw, 3)) patch = np.clip(patch.astype(np.float32) + noise, 0, 255).astype(np.uint8) alpha = cv2.GaussianBlur(alpha, (3, 3), 0.5) alpha_3d = np.expand_dims(alpha, axis=-1)
blended = roi.astype(np.float32) * (1.0 - alpha_3d) + patch.astype(np.float32) * alpha_3d img[y1:y2, x1:x2] = np.clip(blended, 0, 255).astype(np.uint8)
xc = (x1 + x2) / (2.0 * w) yc = (y1 + y2) / (2.0 * h) bw = (x2 - x1) / float(w) bh = (y2 - y1) / float(h) clean_box = sanitize_bbox([xc, yc, bw, bh]) return img, clean_box
# ------------------------------------------------------------------------- # 4. Obstruction Generation (Class 3) # ------------------------------------------------------------------------- def inject_obstruction( self, image: np.ndarray, bbox_loc: Optional[Tuple[int, int, int, int]] = None ) -> Tuple[np.ndarray, Optional[List[float]]]: """ Simulate track obstruction / foreign object (rock chunk, metal tool, timber piece, debris) with directional contact shadow. """ h, w = image.shape[:2] img = image.copy()
if bbox_loc is not None: x1, y1, x2, y2 = bbox_loc ow, oh = max(35, x2 - x1), max(35, y2 - y1) else: ow = random.randint(int(w * 0.08), int(w * 0.20)) oh = random.randint(int(h * 0.08), int(h * 0.20)) # Place in gauge area or on ballast trackbed x1 = random.randint(int(w * 0.20), max(5, w - ow - int(w * 0.20))) y1 = random.randint(int(h * 0.15), max(5, h - oh - int(h * 0.15))) x2, y2 = x1 + ow, y1 + oh
roi = img[y1:y2, x1:x2] patch = np.zeros((oh, ow, 3), dtype=np.uint8) alpha = np.zeros((oh, ow), dtype=np.float32)
obj_type = random.choice(["rock", "metal_tool", "debris"])
if obj_type == "rock": # Polygonal rock lump num_pts = random.randint(6, 9) angles = np.sort(np.random.uniform(0, 2 * math.pi, num_pts)) radii = np.random.uniform(min(ow, oh) * 0.3, min(ow, oh) * 0.45, num_pts) cx, cy = ow // 2, oh // 2 poly_pts = np.array([ [int(cx + r * math.cos(a)), int(cy + r * math.sin(a))] for a, r in zip(angles, radii) ], np.int32) rock_color = (random.randint(90, 140), random.randint(95, 145), random.randint(100, 150)) cv2.fillPoly(patch, [poly_pts], rock_color) cv2.fillPoly(alpha, [poly_pts], 0.95) elif obj_type == "metal_tool": # Rectangular bar / wrench / spike pt1 = (int(ow * 0.15), int(oh * 0.8)) pt2 = (int(ow * 0.85), int(oh * 0.2)) cv2.line(patch, pt1, pt2, (60, 65, 75), thickness=random.randint(6, 12)) cv2.line(alpha, pt1, pt2, 0.95, thickness=random.randint(6, 12)) # Metallic reflection edge cv2.line(patch, (pt1[0], pt1[1] - 2), (pt2[0], pt2[1] - 2), (190, 195, 210), thickness=2) else: # Irregular debris piece cv2.ellipse(patch, (ow // 2, oh // 2), (int(ow * 0.4), int(oh * 0.25)), random.randint(0, 180), 0, 360, (50, 70, 90), -1) cv2.ellipse(alpha, (ow // 2, oh // 2), (int(ow * 0.4), int(oh * 0.25)), random.randint(0, 180), 0, 360, 0.90, -1)
# Contact shadow (dark offset beneath object) shadow_mask = np.roll(alpha, shift=3, axis=0) shadow_patch = np.zeros_like(patch)
noise = np.random.normal(0, 14, (oh, ow, 3)) patch = np.clip(patch.astype(np.float32) + noise, 0, 255).astype(np.uint8)
alpha_clean = cv2.GaussianBlur(alpha, (3, 3), 0.5) alpha_3d = np.expand_dims(alpha_clean, axis=-1)
blended = roi.astype(np.float32) * (1.0 - alpha_3d) + patch.astype(np.float32) * alpha_3d img[y1:y2, x1:x2] = np.clip(blended, 0, 255).astype(np.uint8)
xc = (x1 + x2) / (2.0 * w) yc = (y1 + y2) / (2.0 * h) bw = (x2 - x1) / float(w) bh = (y2 - y1) / float(h) clean_box = sanitize_bbox([xc, yc, bw, bh]) return img, clean_box
# ------------------------------------------------------------------------- # 5. Unified Multi-Defect Sample Generator # ------------------------------------------------------------------------- def generate_synthetic_sample( self, base_image: np.ndarray, defect_types: Optional[List[str]] = None, max_defects: int = 2, ) -> Tuple[np.ndarray, List[Dict[str, Any]]]: """ Inject one or more synthetic defects onto a base image and return annotated bboxes. """ img = base_image.copy() bboxes: List[Dict[str, Any]] = []
if defect_types is None: # Pick 1 to max_defects random defect types num_defects = random.randint(1, max_defects) chosen_types = [random.choice(CLASS_NAMES) for _ in range(num_defects)] else: chosen_types = defect_types
for dt in chosen_types: clean_box = None if dt == "missing_fastener": img, clean_box = self.inject_missing_fastener(img) cls_id = 0 elif dt == "defective_clip": img, clean_box = self.inject_defective_clip(img) cls_id = 1 elif dt == "crack": img, clean_box = self.inject_crack(img) cls_id = 2 elif dt == "obstruction": img, clean_box = self.inject_obstruction(img) cls_id = 3 else: continue
if clean_box is not None: bboxes.append({"class_id": cls_id, "bbox": clean_box})
return img, bboxes1# Evaluation package marker.ml/.pytest_cache/.gitignoreAdded+2
ml/.pytest_cache/CACHEDIR.TAGAdded+4
ml/.pytest_cache/README.mdAdded+8
ml/.pytest_cache/v/cache/lastfailedAdded+3
ml/.pytest_cache/v/cache/nodeidsAdded+125
ml/.pytest_cache/v/cache/stepwiseAdded+1
ml/README.mdAdded+320
ml/__init__.pyAdded+1
ml/__pycache__/__init__.cpython-312.pycAdded
ml/calibration/__init__.pyAdded+13
ml/calibration/__pycache__/__init__.cpython-312.pycAdded
ml/calibration/__pycache__/fpr_threshold.cpython-312.pycAdded
ml/calibration/__pycache__/patchcore_scale.cpython-312.pycAdded
ml/calibration/__pycache__/temperature.cpython-312.pycAdded
ml/calibration/__pycache__/unified_calibrator.cpython-312.pycAdded
ml/calibration/fpr_threshold.pyAdded+30
ml/calibration/patchcore_scale.pyAdded+161
ml/calibration/temperature.pyAdded+142
ml/calibration/unified_calibrator.pyAdded+113
ml/configs/anomaly.yamlAdded+41
ml/configs/calibration.yamlAdded+10
ml/configs/chainage.yamlAdded+23
ml/configs/data.yamlAdded+15
ml/configs/detector.yamlAdded+69
ml/configs/fault_classifier.yamlAdded+39
ml/configs/fusion.yamlAdded+11
ml/configs/patchcore_enhanced.yamlAdded+60
ml/configs/physics_detector.yamlAdded+32
ml/configs/sequence_vae.yamlAdded+29
ml/configs/test.yamlAdded+23
ml/configs/yolo_custom_train.yamlAdded+97
ml/core/__init__.pyAdded+1
ml/core/__pycache__/__init__.cpython-312.pycAdded
ml/core/__pycache__/chainage.cpython-312.pycAdded
ml/core/__pycache__/manifest.cpython-312.pycAdded
ml/core/__pycache__/registry.cpython-312.pycAdded
ml/core/__pycache__/schema.cpython-312.pycAdded
ml/core/chainage.pyAdded+237
ml/core/manifest.pyAdded+201
ml/core/registry.pyAdded+88
ml/core/schema.pyAdded+357
ml/data/__init__.pyAdded+1
ml/data/__pycache__/__init__.cpython-312.pycAdded
ml/data/__pycache__/synthetic_geometry.cpython-312.pycAdded
ml/data/datasets.pyAdded+66
ml/data/loaders.pyAdded+37
ml/data/synthetic.pyAdded+112
ml/data/synthetic_geometry.pyAdded+219
ml/data/synthetic_vision.pyAdded+425
ml/evaluation/__init__.pyAdded+1