Skip to main content

neighborhood_equality/
lib.rs

1//! Deterministic train-access equality analysis for coworking spaces.
2//!
3//! Every space is evaluated against the same walking boundary. Reachable
4//! station scores combine proximity, trains per hour, and step-free access
5//! using integer arithmetic.
6//!
7//! ```
8//! use neighborhood_equality::{
9//!     AccessPolicy, CoworkingSpace, GridPoint, NeighborhoodEquality, TrainStation,
10//! };
11//!
12//! let spaces = [CoworkingSpace::new("work", GridPoint::new(0, 0))?];
13//! let stations = [
14//!     TrainStation::new("station", GridPoint::new(100, 0), 8)?.with_step_free(true),
15//! ];
16//! let report = NeighborhoodEquality::analyze(
17//!     &spaces,
18//!     &stations,
19//!     AccessPolicy::new(1_000)?,
20//! )?;
21//! assert!(report.spaces()[0].access_units() > 0);
22//! # Ok::<(), neighborhood_equality::EqualityError>(())
23//! ```
24
25use std::collections::BTreeSet;
26use std::error::Error;
27use std::fmt::{self, Display, Formatter};
28use std::num::NonZeroU64;
29
30/// A deterministic grid position measured in meters.
31#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
32pub struct GridPoint {
33    east_meters: i64,
34    north_meters: i64,
35}
36
37impl GridPoint {
38    /// Creates a grid position.
39    pub const fn new(east_meters: i64, north_meters: i64) -> Self {
40        Self {
41            east_meters,
42            north_meters,
43        }
44    }
45
46    /// East-west coordinate in meters.
47    pub const fn east_meters(self) -> i64 {
48        self.east_meters
49    }
50
51    /// North-south coordinate in meters.
52    pub const fn north_meters(self) -> i64 {
53        self.north_meters
54    }
55
56    /// Manhattan distance to another point.
57    pub fn walking_distance(self, other: Self) -> Result<u64, EqualityError> {
58        self.east_meters
59            .abs_diff(other.east_meters)
60            .checked_add(self.north_meters.abs_diff(other.north_meters))
61            .ok_or(EqualityError::DistanceOverflow)
62    }
63}
64
65/// A coworking-space location to evaluate.
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub struct CoworkingSpace {
68    id: String,
69    location: GridPoint,
70}
71
72impl CoworkingSpace {
73    /// Creates a workspace with a non-empty identifier.
74    pub fn new(id: impl Into<String>, location: GridPoint) -> Result<Self, EqualityError> {
75        let id = id.into();
76        if id.trim().is_empty() {
77            return Err(EqualityError::EmptySpaceId);
78        }
79        Ok(Self { id, location })
80    }
81
82    /// Workspace identifier.
83    pub fn id(&self) -> &str {
84        &self.id
85    }
86
87    /// Workspace grid position.
88    pub const fn location(&self) -> GridPoint {
89        self.location
90    }
91}
92
93/// A train station and its service level.
94#[derive(Clone, Debug, PartialEq, Eq)]
95pub struct TrainStation {
96    id: String,
97    location: GridPoint,
98    trains_per_hour: u32,
99    step_free: bool,
100}
101
102impl TrainStation {
103    /// Creates a station with a positive service frequency.
104    pub fn new(
105        id: impl Into<String>,
106        location: GridPoint,
107        trains_per_hour: u32,
108    ) -> Result<Self, EqualityError> {
109        let id = id.into();
110        if id.trim().is_empty() {
111            return Err(EqualityError::EmptyStationId);
112        }
113        if trains_per_hour == 0 {
114            return Err(EqualityError::ZeroFrequency);
115        }
116        Ok(Self {
117            id,
118            location,
119            trains_per_hour,
120            step_free: false,
121        })
122    }
123
124    /// Sets whether step-free access is available.
125    pub const fn with_step_free(mut self, step_free: bool) -> Self {
126        self.step_free = step_free;
127        self
128    }
129
130    /// Station identifier.
131    pub fn id(&self) -> &str {
132        &self.id
133    }
134
135    /// Station grid position.
136    pub const fn location(&self) -> GridPoint {
137        self.location
138    }
139
140    /// Scheduled service frequency used by the model.
141    pub const fn trains_per_hour(&self) -> u32 {
142        self.trains_per_hour
143    }
144
145    /// Whether the station is step-free.
146    pub const fn is_step_free(&self) -> bool {
147        self.step_free
148    }
149}
150
151/// Shared scoring policy for every workspace.
152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
153pub struct AccessPolicy {
154    max_walk_meters: NonZeroU64,
155    non_step_free_weight_basis_points: u16,
156}
157
158impl AccessPolicy {
159    /// Creates a policy with a walking boundary and a 25% non-step-free weight.
160    pub fn new(max_walk_meters: u64) -> Result<Self, EqualityError> {
161        Ok(Self {
162            max_walk_meters: NonZeroU64::new(max_walk_meters)
163                .ok_or(EqualityError::ZeroWalkingBoundary)?,
164            non_step_free_weight_basis_points: 2_500,
165        })
166    }
167
168    /// Sets the weight for stations without step-free access.
169    ///
170    /// Ten thousand basis points means full weight; zero means no score.
171    pub fn with_non_step_free_weight(mut self, basis_points: u16) -> Result<Self, EqualityError> {
172        if basis_points > 10_000 {
173            return Err(EqualityError::AccessibilityWeightTooHigh(basis_points));
174        }
175        self.non_step_free_weight_basis_points = basis_points;
176        Ok(self)
177    }
178
179    /// Walking boundary in meters.
180    pub const fn max_walk_meters(self) -> u64 {
181        self.max_walk_meters.get()
182    }
183
184    /// Weight for stations without step-free access.
185    pub const fn non_step_free_weight_basis_points(self) -> u16 {
186        self.non_step_free_weight_basis_points
187    }
188}
189
190impl Default for AccessPolicy {
191    fn default() -> Self {
192        Self::new(1_200).expect("default walking boundary is non-zero")
193    }
194}
195
196/// Contribution made by one reachable station.
197#[derive(Clone, Debug, PartialEq, Eq)]
198pub struct StationAccess {
199    station_id: String,
200    distance_meters: u64,
201    trains_per_hour: u32,
202    step_free: bool,
203    access_units: u128,
204}
205
206impl StationAccess {
207    /// Station identifier.
208    pub fn station_id(&self) -> &str {
209        &self.station_id
210    }
211
212    /// Modeled walking distance.
213    pub const fn distance_meters(&self) -> u64 {
214        self.distance_meters
215    }
216
217    /// Service frequency used in this contribution.
218    pub const fn trains_per_hour(&self) -> u32 {
219        self.trains_per_hour
220    }
221
222    /// Whether the station is step-free.
223    pub const fn is_step_free(&self) -> bool {
224        self.step_free
225    }
226
227    /// Integer contribution to workspace access.
228    pub const fn access_units(&self) -> u128 {
229        self.access_units
230    }
231}
232
233/// Explainable access score for one coworking space.
234#[derive(Clone, Debug, PartialEq, Eq)]
235pub struct SpaceAccess {
236    space_id: String,
237    access_units: u128,
238    connections: Vec<StationAccess>,
239}
240
241impl SpaceAccess {
242    /// Workspace identifier.
243    pub fn space_id(&self) -> &str {
244        &self.space_id
245    }
246
247    /// Sum of all reachable station contributions.
248    pub const fn access_units(&self) -> u128 {
249        self.access_units
250    }
251
252    /// Reachable stations ordered by distance, then identifier.
253    pub fn connections(&self) -> &[StationAccess] {
254        &self.connections
255    }
256
257    /// Whether no station contributes access.
258    pub const fn is_unserved(&self) -> bool {
259        self.access_units == 0
260    }
261}
262
263/// Comparison across all supplied coworking spaces.
264#[derive(Clone, Debug, PartialEq, Eq)]
265pub struct EqualityReport {
266    spaces: Vec<SpaceAccess>,
267    equality_basis_points: u16,
268    gap_units: u128,
269    served_spaces: usize,
270}
271
272impl EqualityReport {
273    /// Workspace reports ordered by identifier.
274    pub fn spaces(&self) -> &[SpaceAccess] {
275        &self.spaces
276    }
277
278    /// Ratio of the lowest score to the highest, in basis points.
279    ///
280    /// Ten thousand means equal. If all spaces are unserved, they are equally
281    /// scored and this value is also ten thousand.
282    pub const fn equality_basis_points(&self) -> u16 {
283        self.equality_basis_points
284    }
285
286    /// Difference between the highest and lowest access scores.
287    pub const fn gap_units(&self) -> u128 {
288        self.gap_units
289    }
290
291    /// Number of workspaces with a positive access score.
292    pub const fn served_spaces(&self) -> usize {
293        self.served_spaces
294    }
295
296    /// Whether every workspace has a zero access score.
297    pub const fn all_unserved(&self) -> bool {
298        self.served_spaces == 0
299    }
300
301    /// First highest-scoring space; ties follow identifier order.
302    pub fn most_accessible(&self) -> &SpaceAccess {
303        self.spaces
304            .iter()
305            .reduce(|best, candidate| {
306                if candidate.access_units > best.access_units {
307                    candidate
308                } else {
309                    best
310                }
311            })
312            .expect("reports always contain at least one space")
313    }
314
315    /// First lowest-scoring space; ties follow identifier order.
316    pub fn least_accessible(&self) -> &SpaceAccess {
317        self.spaces
318            .iter()
319            .reduce(|best, candidate| {
320                if candidate.access_units < best.access_units {
321                    candidate
322                } else {
323                    best
324                }
325            })
326            .expect("reports always contain at least one space")
327    }
328}
329
330/// Implements coworking-space and train equality analysis.
331#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
332pub struct NeighborhoodEquality;
333
334impl NeighborhoodEquality {
335    /// Scores and compares all supplied coworking spaces.
336    pub fn analyze(
337        spaces: &[CoworkingSpace],
338        stations: &[TrainStation],
339        policy: AccessPolicy,
340    ) -> Result<EqualityReport, EqualityError> {
341        if spaces.is_empty() {
342            return Err(EqualityError::NoSpaces);
343        }
344        ensure_unique(spaces.iter().map(CoworkingSpace::id), true)?;
345        ensure_unique(stations.iter().map(TrainStation::id), false)?;
346
347        let mut reports = Vec::with_capacity(spaces.len());
348        for space in spaces {
349            let mut connections = Vec::new();
350            let mut access_units = 0u128;
351            for station in stations {
352                let distance = space.location.walking_distance(station.location)?;
353                if distance >= policy.max_walk_meters() {
354                    continue;
355                }
356                let remaining = policy.max_walk_meters() - distance;
357                let proximity_basis_points =
358                    u128::from(remaining) * 10_000 / u128::from(policy.max_walk_meters());
359                let mut contribution = u128::from(station.trains_per_hour) * proximity_basis_points;
360                if !station.step_free {
361                    contribution = contribution
362                        .checked_mul(u128::from(policy.non_step_free_weight_basis_points))
363                        .ok_or(EqualityError::ScoreOverflow)?
364                        / 10_000;
365                }
366                access_units = access_units
367                    .checked_add(contribution)
368                    .ok_or(EqualityError::ScoreOverflow)?;
369                connections.push(StationAccess {
370                    station_id: station.id.clone(),
371                    distance_meters: distance,
372                    trains_per_hour: station.trains_per_hour,
373                    step_free: station.step_free,
374                    access_units: contribution,
375                });
376            }
377            connections.sort_by(|left, right| {
378                left.distance_meters
379                    .cmp(&right.distance_meters)
380                    .then_with(|| left.station_id.cmp(&right.station_id))
381            });
382            reports.push(SpaceAccess {
383                space_id: space.id.clone(),
384                access_units,
385                connections,
386            });
387        }
388        reports.sort_by(|left, right| left.space_id.cmp(&right.space_id));
389
390        let minimum = reports
391            .iter()
392            .map(SpaceAccess::access_units)
393            .min()
394            .expect("non-empty input produces non-empty reports");
395        let maximum = reports
396            .iter()
397            .map(SpaceAccess::access_units)
398            .max()
399            .expect("non-empty input produces non-empty reports");
400        let scaled_minimum = minimum
401            .checked_mul(10_000)
402            .ok_or(EqualityError::ScoreOverflow)?;
403        let equality_basis_points = match scaled_minimum.checked_div(maximum) {
404            Some(scaled) => u16::try_from(scaled).map_err(|_| EqualityError::ScoreOverflow)?,
405            None => 10_000,
406        };
407        let served_spaces = reports.iter().filter(|space| !space.is_unserved()).count();
408
409        Ok(EqualityReport {
410            spaces: reports,
411            equality_basis_points,
412            gap_units: maximum - minimum,
413            served_spaces,
414        })
415    }
416}
417
418fn ensure_unique<'a>(
419    ids: impl Iterator<Item = &'a str>,
420    spaces: bool,
421) -> Result<(), EqualityError> {
422    let mut seen = BTreeSet::new();
423    for id in ids {
424        if !seen.insert(id) {
425            return Err(if spaces {
426                EqualityError::DuplicateSpaceId(id.to_string())
427            } else {
428                EqualityError::DuplicateStationId(id.to_string())
429            });
430        }
431    }
432    Ok(())
433}
434
435/// Input validation or checked-arithmetic failure.
436#[derive(Clone, Debug, PartialEq, Eq)]
437#[non_exhaustive]
438pub enum EqualityError {
439    /// Workspace identifier was empty.
440    EmptySpaceId,
441    /// Station identifier was empty.
442    EmptyStationId,
443    /// Station frequency was zero.
444    ZeroFrequency,
445    /// Walking boundary was zero.
446    ZeroWalkingBoundary,
447    /// Non-step-free weight exceeded 100%.
448    AccessibilityWeightTooHigh(u16),
449    /// No coworking spaces were supplied.
450    NoSpaces,
451    /// Workspace identifier was repeated.
452    DuplicateSpaceId(String),
453    /// Station identifier was repeated.
454    DuplicateStationId(String),
455    /// Manhattan-distance arithmetic overflowed.
456    DistanceOverflow,
457    /// Access-score arithmetic overflowed.
458    ScoreOverflow,
459}
460
461impl Display for EqualityError {
462    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
463        match self {
464            Self::EmptySpaceId => f.write_str("coworking-space identifier cannot be empty"),
465            Self::EmptyStationId => f.write_str("station identifier cannot be empty"),
466            Self::ZeroFrequency => f.write_str("trains per hour must be greater than zero"),
467            Self::ZeroWalkingBoundary => f.write_str("walking boundary must be greater than zero"),
468            Self::AccessibilityWeightTooHigh(value) => {
469                write!(f, "accessibility weight {value} exceeds 10000 basis points")
470            }
471            Self::NoSpaces => f.write_str("at least one coworking space is required"),
472            Self::DuplicateSpaceId(id) => write!(f, "duplicate coworking-space identifier: {id}"),
473            Self::DuplicateStationId(id) => write!(f, "duplicate station identifier: {id}"),
474            Self::DistanceOverflow => f.write_str("walking-distance arithmetic overflowed"),
475            Self::ScoreOverflow => f.write_str("access-score arithmetic overflowed"),
476        }
477    }
478}
479
480impl Error for EqualityError {}
481
482#[cfg(test)]
483mod tests {
484    use super::*;
485
486    fn sample() -> (Vec<CoworkingSpace>, Vec<TrainStation>) {
487        (
488            vec![
489                CoworkingSpace::new("central", GridPoint::new(0, 0)).unwrap(),
490                CoworkingSpace::new("east", GridPoint::new(800, 0)).unwrap(),
491            ],
492            vec![
493                TrainStation::new("hub", GridPoint::new(100, 0), 12)
494                    .unwrap()
495                    .with_step_free(true),
496                TrainStation::new("east-stop", GridPoint::new(700, 0), 4).unwrap(),
497            ],
498        )
499    }
500
501    #[test]
502    fn scores_all_reachable_stations_deterministically() {
503        let (spaces, stations) = sample();
504        let report =
505            NeighborhoodEquality::analyze(&spaces, &stations, AccessPolicy::new(1_000).unwrap())
506                .unwrap();
507
508        assert_eq!(report.spaces()[0].space_id(), "central");
509        assert_eq!(report.spaces()[0].access_units(), 111_000);
510        assert_eq!(report.spaces()[1].access_units(), 45_000);
511        assert_eq!(report.equality_basis_points(), 4_054);
512        assert_eq!(report.gap_units(), 66_000);
513        assert_eq!(report.served_spaces(), 2);
514    }
515
516    #[test]
517    fn reports_best_and_worst_spaces() {
518        let (spaces, stations) = sample();
519        let report =
520            NeighborhoodEquality::analyze(&spaces, &stations, AccessPolicy::new(1_000).unwrap())
521                .unwrap();
522        assert_eq!(report.most_accessible().space_id(), "central");
523        assert_eq!(report.least_accessible().space_id(), "east");
524    }
525
526    #[test]
527    fn all_unserved_spaces_are_equally_scored() {
528        let spaces = [
529            CoworkingSpace::new("a", GridPoint::new(0, 0)).unwrap(),
530            CoworkingSpace::new("b", GridPoint::new(1, 1)).unwrap(),
531        ];
532        let report = NeighborhoodEquality::analyze(&spaces, &[], AccessPolicy::default()).unwrap();
533        assert!(report.all_unserved());
534        assert_eq!(report.equality_basis_points(), 10_000);
535        assert_eq!(report.gap_units(), 0);
536    }
537
538    #[test]
539    fn inaccessible_weight_changes_only_affected_station() {
540        let spaces = [CoworkingSpace::new("a", GridPoint::new(0, 0)).unwrap()];
541        let stations = [TrainStation::new("s", GridPoint::new(0, 0), 10).unwrap()];
542        let policy = AccessPolicy::new(1_000)
543            .unwrap()
544            .with_non_step_free_weight(5_000)
545            .unwrap();
546        let report = NeighborhoodEquality::analyze(&spaces, &stations, policy).unwrap();
547        assert_eq!(report.spaces()[0].access_units(), 50_000);
548    }
549
550    #[test]
551    fn duplicate_identifiers_are_rejected() {
552        let spaces = [
553            CoworkingSpace::new("same", GridPoint::new(0, 0)).unwrap(),
554            CoworkingSpace::new("same", GridPoint::new(1, 1)).unwrap(),
555        ];
556        assert_eq!(
557            NeighborhoodEquality::analyze(&spaces, &[], AccessPolicy::default()).unwrap_err(),
558            EqualityError::DuplicateSpaceId("same".to_string())
559        );
560    }
561
562    #[test]
563    fn invalid_inputs_are_rejected() {
564        assert_eq!(
565            CoworkingSpace::new("", GridPoint::default()).unwrap_err(),
566            EqualityError::EmptySpaceId
567        );
568        assert_eq!(
569            TrainStation::new("s", GridPoint::default(), 0).unwrap_err(),
570            EqualityError::ZeroFrequency
571        );
572        assert_eq!(
573            AccessPolicy::new(0).unwrap_err(),
574            EqualityError::ZeroWalkingBoundary
575        );
576        assert_eq!(
577            AccessPolicy::default()
578                .with_non_step_free_weight(10_001)
579                .unwrap_err(),
580            EqualityError::AccessibilityWeightTooHigh(10_001)
581        );
582    }
583
584    #[test]
585    fn distance_overflow_is_detected() {
586        let left = GridPoint::new(i64::MIN, i64::MIN);
587        let right = GridPoint::new(i64::MAX, i64::MAX);
588        assert_eq!(
589            left.walking_distance(right).unwrap_err(),
590            EqualityError::DistanceOverflow
591        );
592    }
593}