Skip to main content

train_kouts/
lib.rs

1//! Explainable planning decisions where railways and roads interact.
2//!
3//! The model treats safety as a gate and keeps every conclusion tied to
4//! non-empty evidence. It is not a traffic simulation or regulatory approval.
5
6#![forbid(unsafe_code)]
7#![warn(missing_docs)]
8
9use std::collections::BTreeMap;
10use std::error::Error;
11use std::fmt;
12
13/// MLIT information about railway-crossing safety.
14pub const MLIT_CROSSING_SAFETY_URL: &str = "https://www.mlit.go.jp/tetudo/tetudo_tk9_000004.html";
15
16/// MLIT information about integrated transport terminals.
17pub const MLIT_TRANSPORT_HUB_URL: &str = "https://www.mlit.go.jp/road/busterminal/";
18
19/// A principle for evaluating the relationship between rail and road.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
21pub enum TransportPrinciple {
22    /// Prevent collisions and protect pedestrians at crossings and interfaces.
23    InterfaceSafety,
24    /// Keep transfers short, legible, and continuous across modes.
25    ConnectedJourney,
26    /// Include step-free, visible, and usable routes for diverse travelers.
27    UniversalAccess,
28    /// Balance delay and reliability without shifting harm to another mode.
29    ReliableFlow,
30    /// Reduce emissions, noise, and avoidable land consumption.
31    EnvironmentalCare,
32    /// Maintain useful alternatives during disruption or maintenance.
33    NetworkResilience,
34}
35
36impl TransportPrinciple {
37    /// Every principle in stable report order.
38    pub const ALL: [Self; 6] = [
39        Self::InterfaceSafety,
40        Self::ConnectedJourney,
41        Self::UniversalAccess,
42        Self::ReliableFlow,
43        Self::EnvironmentalCare,
44        Self::NetworkResilience,
45    ];
46}
47
48/// Evidence-based impact on one transport principle.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum Impact {
51    /// The proposal measurably improves the principle.
52    Improves,
53    /// The proposal has no material effect.
54    Neutral,
55    /// A plausible risk remains and needs mitigation.
56    NeedsMitigation,
57    /// Evidence shows material harm.
58    Harms,
59}
60
61/// An impact and its supporting evidence.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct Assessment {
64    impact: Impact,
65    evidence: String,
66}
67
68impl Assessment {
69    /// Creates an assessment, rejecting blank evidence.
70    pub fn new(impact: Impact, evidence: impl Into<String>) -> Result<Self, TransportError> {
71        let evidence = evidence.into();
72        if evidence.trim().is_empty() {
73            return Err(TransportError::EmptyEvidence);
74        }
75        Ok(Self { impact, evidence })
76    }
77
78    /// Returns the impact.
79    pub const fn impact(&self) -> Impact {
80        self.impact
81    }
82
83    /// Returns the evidence.
84    pub fn evidence(&self) -> &str {
85        &self.evidence
86    }
87}
88
89/// A railway-and-road project proposal.
90#[derive(Debug, Clone, PartialEq, Eq)]
91pub struct TransportPlan {
92    name: String,
93    assessments: BTreeMap<TransportPrinciple, Assessment>,
94}
95
96impl TransportPlan {
97    /// Creates an unassessed plan with a non-blank name.
98    pub fn new(name: impl Into<String>) -> Result<Self, TransportError> {
99        let name = name.into();
100        if name.trim().is_empty() {
101            return Err(TransportError::EmptyPlanName);
102        }
103        Ok(Self {
104            name,
105            assessments: BTreeMap::new(),
106        })
107    }
108
109    /// Adds or replaces an assessment and returns the plan for chaining.
110    pub fn assess(
111        mut self,
112        principle: TransportPrinciple,
113        impact: Impact,
114        evidence: impl Into<String>,
115    ) -> Result<Self, TransportError> {
116        self.set_assessment(principle, impact, evidence)?;
117        Ok(self)
118    }
119
120    /// Adds or replaces an assessment in place.
121    pub fn set_assessment(
122        &mut self,
123        principle: TransportPrinciple,
124        impact: Impact,
125        evidence: impl Into<String>,
126    ) -> Result<(), TransportError> {
127        self.assessments
128            .insert(principle, Assessment::new(impact, evidence)?);
129        Ok(())
130    }
131
132    /// Returns the plan name.
133    pub fn name(&self) -> &str {
134        &self.name
135    }
136
137    /// Returns an assessment when present.
138    pub fn assessment(&self, principle: TransportPrinciple) -> Option<&Assessment> {
139        self.assessments.get(&principle)
140    }
141}
142
143/// Final decision from the integrated policy.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum TransportDecision {
146    /// Known interface-safety harm is a veto.
147    Decline,
148    /// At least one principle lacks evidence.
149    NeedsEvidence,
150    /// Every principle is assessed, but mitigation or harm remains.
151    Revise,
152    /// Every principle is neutral or improved with evidence.
153    Integrated,
154}
155
156/// Strict transport policy in which safety harm cannot be traded away.
157#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
158pub struct IntegratedPolicy;
159
160impl IntegratedPolicy {
161    /// Evaluates a plan and returns an explainable report.
162    pub fn evaluate(plan: &TransportPlan) -> TransportReport {
163        let mut missing = Vec::new();
164        let mut needs_mitigation = Vec::new();
165        let mut harms = Vec::new();
166
167        for principle in TransportPrinciple::ALL {
168            match plan.assessment(principle).map(Assessment::impact) {
169                None => missing.push(principle),
170                Some(Impact::Improves | Impact::Neutral) => {}
171                Some(Impact::NeedsMitigation) => needs_mitigation.push(principle),
172                Some(Impact::Harms) => harms.push(principle),
173            }
174        }
175
176        let safety_harm = harms.contains(&TransportPrinciple::InterfaceSafety);
177        let decision = if safety_harm {
178            TransportDecision::Decline
179        } else if !missing.is_empty() {
180            TransportDecision::NeedsEvidence
181        } else if !needs_mitigation.is_empty() || !harms.is_empty() {
182            TransportDecision::Revise
183        } else {
184            TransportDecision::Integrated
185        };
186
187        TransportReport {
188            decision,
189            missing,
190            needs_mitigation,
191            harms,
192        }
193    }
194}
195
196/// Explainable decision report in stable principle order.
197#[derive(Debug, Clone, PartialEq, Eq)]
198pub struct TransportReport {
199    decision: TransportDecision,
200    missing: Vec<TransportPrinciple>,
201    needs_mitigation: Vec<TransportPrinciple>,
202    harms: Vec<TransportPrinciple>,
203}
204
205impl TransportReport {
206    /// Returns the final decision.
207    pub const fn decision(&self) -> TransportDecision {
208        self.decision
209    }
210
211    /// Returns principles without evidence.
212    pub fn missing(&self) -> &[TransportPrinciple] {
213        &self.missing
214    }
215
216    /// Returns principles requiring mitigation.
217    pub fn needs_mitigation(&self) -> &[TransportPrinciple] {
218        &self.needs_mitigation
219    }
220
221    /// Returns principles with known harm.
222    pub fn harms(&self) -> &[TransportPrinciple] {
223        &self.harms
224    }
225}
226
227/// Invalid transport-plan input.
228#[derive(Debug, Clone, Copy, PartialEq, Eq)]
229pub enum TransportError {
230    /// Plan name was blank.
231    EmptyPlanName,
232    /// Assessment evidence was blank.
233    EmptyEvidence,
234}
235
236impl fmt::Display for TransportError {
237    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
238        match self {
239            Self::EmptyPlanName => formatter.write_str("plan name must not be blank"),
240            Self::EmptyEvidence => formatter.write_str("assessment evidence must not be blank"),
241        }
242    }
243}
244
245impl Error for TransportError {}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250
251    fn integrated_plan() -> TransportPlan {
252        TransportPrinciple::ALL
253            .into_iter()
254            .try_fold(
255                TransportPlan::new("station approach").unwrap(),
256                |plan, principle| plan.assess(principle, Impact::Improves, "measured improvement"),
257            )
258            .unwrap()
259    }
260
261    #[test]
262    fn complete_positive_plan_is_integrated() {
263        assert_eq!(
264            IntegratedPolicy::evaluate(&integrated_plan()).decision(),
265            TransportDecision::Integrated
266        );
267    }
268
269    #[test]
270    fn safety_harm_is_a_veto_even_with_missing_evidence() {
271        let plan = TransportPlan::new("crossing change")
272            .unwrap()
273            .assess(
274                TransportPrinciple::InterfaceSafety,
275                Impact::Harms,
276                "pedestrian conflict increases",
277            )
278            .unwrap();
279        let report = IntegratedPolicy::evaluate(&plan);
280        assert_eq!(report.decision(), TransportDecision::Decline);
281        assert_eq!(report.harms(), &[TransportPrinciple::InterfaceSafety]);
282    }
283
284    #[test]
285    fn empty_plan_needs_all_evidence_in_stable_order() {
286        let report = IntegratedPolicy::evaluate(&TransportPlan::new("draft").unwrap());
287        assert_eq!(report.decision(), TransportDecision::NeedsEvidence);
288        assert_eq!(report.missing(), &TransportPrinciple::ALL);
289    }
290
291    #[test]
292    fn unresolved_access_risk_requires_revision() {
293        let mut plan = integrated_plan();
294        plan.set_assessment(
295            TransportPrinciple::UniversalAccess,
296            Impact::NeedsMitigation,
297            "step-free detour is too long",
298        )
299        .unwrap();
300        let report = IntegratedPolicy::evaluate(&plan);
301        assert_eq!(report.decision(), TransportDecision::Revise);
302        assert_eq!(
303            report.needs_mitigation(),
304            &[TransportPrinciple::UniversalAccess]
305        );
306    }
307
308    #[test]
309    fn blank_inputs_are_rejected() {
310        assert_eq!(TransportPlan::new(" "), Err(TransportError::EmptyPlanName));
311        assert_eq!(
312            Assessment::new(Impact::Neutral, "\t"),
313            Err(TransportError::EmptyEvidence)
314        );
315    }
316}