spatial-narrative 0.1.0

A Rust library for representing, analyzing, and working with narratives that unfold across real-world geographic space
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
# spatial-narrative: Implementation Guide

This document provides concrete code examples and implementation details to complement the main specification.

---

## Project Structure

```
spatial-narrative/
├── Cargo.toml
├── README.md
├── LICENSE-MIT
├── LICENSE-APACHE
├── src/
│   ├── lib.rs                 # Public API exports
│   ├── prelude.rs            # Commonly used imports
│   ├── core/
│   │   ├── mod.rs
│   │   ├── location.rs       # Location type
│   │   ├── timestamp.rs      # Timestamp type
│   │   ├── event.rs          # Event type
│   │   ├── narrative.rs      # Narrative type
│   │   └── traits.rs         # Core traits
│   ├── parser/
│   │   ├── mod.rs
│   │   ├── geoparser.rs      # Location extraction
│   │   ├── gazetteer.rs      # Place name database
│   │   └── patterns.rs       # Regex patterns
│   ├── index/
│   │   ├── mod.rs
│   │   ├── spatial.rs        # R-tree spatial index
│   │   ├── temporal.rs       # BTree temporal index
│   │   └── combined.rs       # Spatiotemporal index
│   ├── graph/
│   │   ├── mod.rs
│   │   ├── narrative_graph.rs
│   │   ├── edges.rs
│   │   └── rules.rs
│   ├── analysis/
│   │   ├── mod.rs
│   │   ├── spatial.rs        # Spatial metrics
│   │   ├── temporal.rs       # Temporal metrics
│   │   ├── movement.rs       # Movement analysis
│   │   └── clustering.rs     # Clustering algorithms
│   ├── io/
│   │   ├── mod.rs
│   │   ├── geojson.rs
│   │   ├── csv.rs
│   │   ├── gpx.rs
│   │   └── formats.rs
│   ├── transform/
│   │   ├── mod.rs
│   │   ├── coordinates.rs
│   │   └── distance.rs
│   └── text/
│       ├── mod.rs
│       ├── analyzer.rs
│       └── keywords.rs
├── benches/
│   ├── spatial_queries.rs
│   └── clustering.rs
├── examples/
│   ├── basic/
│   ├── intermediate/
│   └── advanced/
├── tests/
│   ├── integration/
│   └── data/
└── scripts/
    └── generate_test_data.py
```

---

## Core Implementation Examples

### src/lib.rs

```rust
//! # spatial-narrative
//!
//! A Rust library for working with spatial narratives - stories and events
//! that unfold across real-world geography.
//!
//! ## Quick Start
//!
//! ```
//! use spatial_narrative::prelude::*;
//!
//! // Create a narrative
//! let mut narrative = Narrative::builder()
//!     .title("Protest Timeline")
//!     .build();
//!
//! // Add an event
//! narrative.add_event(Event::builder()
//!     .location(Location::new(40.7128, -74.0060))
//!     .timestamp(Timestamp::now())
//!     .text("Demonstration began at City Hall")
//!     .tag("protest")
//!     .build());
//!
//! // Analyze
//! let metrics = narrative.spatial_metrics();
//! println!("Centroid: {:?}", metrics.centroid());
//! ```

pub mod core;
pub mod parser;
pub mod index;
pub mod graph;
pub mod analysis;
pub mod io;
pub mod transform;
pub mod text;

pub mod prelude;

pub use core::{Event, Location, Narrative, Timestamp};
```

### src/prelude.rs

```rust
//! Convenient imports for common use cases.

pub use crate::core::{
    Event, EventBuilder, Location, LocationBuilder, Narrative, NarrativeBuilder,
    Timestamp, TimestampBuilder, GeoBounds, TimeRange,
};

pub use crate::parser::{GeoParser, LocationMention};

pub use crate::index::{SpatialIndex, TemporalIndex, SpatiotemporalIndex};

pub use crate::analysis::{
    SpatialMetrics, TemporalMetrics, MovementAnalyzer, SpatialClustering,
};

pub use crate::io::{GeoJsonFormat, CsvFormat, Format};

pub use crate::transform::Transform;
```

### src/core/location.rs

```rust
use serde::{Deserialize, Serialize};
use std::fmt;

/// A geographic location using WGS84 coordinates.
///
/// Locations represent points on Earth's surface with optional elevation
/// and uncertainty information for real-world data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Location {
    /// Latitude in decimal degrees (-90 to +90)
    pub lat: f64,
    /// Longitude in decimal degrees (-180 to +180)
    pub lon: f64,
    /// Elevation in meters above sea level
    pub elevation: Option<f64>,
    /// Uncertainty radius in meters
    pub uncertainty_meters: Option<f64>,
    /// Optional place name
    pub name: Option<String>,
}

impl Location {
    /// Create a new location from latitude and longitude.
    ///
    /// # Panics
    ///
    /// Panics if latitude or longitude are out of valid range.
    ///
    /// # Examples
    ///
    /// ```
    /// use spatial_narrative::Location;
    ///
    /// let nyc = Location::new(40.7128, -74.0060);
    /// assert_eq!(nyc.lat, 40.7128);
    /// ```
    pub fn new(lat: f64, lon: f64) -> Self {
        assert!(lat >= -90.0 && lat <= 90.0, "Latitude out of range");
        assert!(lon >= -180.0 && lon <= 180.0, "Longitude out of range");
        
        Self {
            lat,
            lon,
            elevation: None,
            uncertainty_meters: None,
            name: None,
        }
    }

    /// Create a location with elevation.
    pub fn with_elevation(lat: f64, lon: f64, elevation: f64) -> Self {
        let mut loc = Self::new(lat, lon);
        loc.elevation = Some(elevation);
        loc
    }

    /// Check if coordinates are valid WGS84.
    pub fn is_valid(&self) -> bool {
        self.lat >= -90.0
            && self.lat <= 90.0
            && self.lon >= -180.0
            && self.lon <= 180.0
    }

    /// Create a builder for constructing locations.
    pub fn builder() -> LocationBuilder {
        LocationBuilder::default()
    }

    /// Convert to geo_types::Point for geometric operations.
    pub fn to_point(&self) -> geo_types::Point<f64> {
        geo_types::Point::new(self.lon, self.lat)
    }

    /// Create from geo_types::Point.
    pub fn from_point(point: geo_types::Point<f64>) -> Self {
        Self::new(point.y(), point.x())
    }
}

impl fmt::Display for Location {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(name) = &self.name {
            write!(f, "{} ({:.4}, {:.4})", name, self.lat, self.lon)
        } else {
            write!(f, "({:.4}, {:.4})", self.lat, self.lon)
        }
    }
}

/// Builder for constructing Location instances.
#[derive(Default)]
pub struct LocationBuilder {
    lat: Option<f64>,
    lon: Option<f64>,
    elevation: Option<f64>,
    uncertainty_meters: Option<f64>,
    name: Option<String>,
}

impl LocationBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn coordinates(mut self, lat: f64, lon: f64) -> Self {
        self.lat = Some(lat);
        self.lon = Some(lon);
        self
    }

    pub fn elevation(mut self, elevation: f64) -> Self {
        self.elevation = Some(elevation);
        self
    }

    pub fn uncertainty_meters(mut self, meters: f64) -> Self {
        self.uncertainty_meters = Some(meters);
        self
    }

    pub fn name<S: Into<String>>(mut self, name: S) -> Self {
        self.name = Some(name.into());
        self
    }

    pub fn build(self) -> Location {
        Location {
            lat: self.lat.expect("Latitude required"),
            lon: self.lon.expect("Longitude required"),
            elevation: self.elevation,
            uncertainty_meters: self.uncertainty_meters,
            name: self.name,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_new_location() {
        let loc = Location::new(40.7128, -74.0060);
        assert_eq!(loc.lat, 40.7128);
        assert_eq!(loc.lon, -74.0060);
        assert!(loc.is_valid());
    }

    #[test]
    #[should_panic(expected = "Latitude out of range")]
    fn test_invalid_latitude() {
        Location::new(100.0, 0.0);
    }

    #[test]
    fn test_builder() {
        let loc = Location::builder()
            .coordinates(40.7128, -74.0060)
            .elevation(10.0)
            .name("New York City")
            .build();
        
        assert_eq!(loc.lat, 40.7128);
        assert_eq!(loc.elevation, Some(10.0));
        assert_eq!(loc.name, Some("New York City".to_string()));
    }

    #[test]
    fn test_display() {
        let loc1 = Location::new(40.7128, -74.0060);
        assert_eq!(format!("{}", loc1), "(40.7128, -74.0060)");

        let loc2 = Location::builder()
            .coordinates(40.7128, -74.0060)
            .name("NYC")
            .build();
        assert_eq!(format!("{}", loc2), "NYC (40.7128, -74.0060)");
    }
}
```

### src/core/timestamp.rs

```rust
use chrono::{DateTime, Utc, TimeZone};
use serde::{Deserialize, Serialize};
use std::fmt;

/// Temporal precision of a timestamp.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TemporalPrecision {
    Year,
    Month,
    Day,
    Hour,
    Minute,
    Second,
    Millisecond,
}

/// A timestamp with timezone awareness and precision.
///
/// Real-world events often have varying levels of temporal precision.
/// This type captures both the datetime and how precise it is.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Timestamp {
    /// UTC datetime
    datetime: DateTime<Utc>,
    /// How precise is this timestamp?
    precision: TemporalPrecision,
}

impl Timestamp {
    /// Create a timestamp from a DateTime.
    pub fn new(datetime: DateTime<Utc>, precision: TemporalPrecision) -> Self {
        Self { datetime, precision }
    }

    /// Current time with second precision.
    pub fn now() -> Self {
        Self::new(Utc::now(), TemporalPrecision::Second)
    }

    /// Parse from ISO 8601 string.
    ///
    /// # Examples
    ///
    /// ```
    /// use spatial_narrative::Timestamp;
    ///
    /// let ts = Timestamp::parse("2024-03-15T14:30:00Z").unwrap();
    /// ```
    pub fn parse(s: &str) -> Result<Self, chrono::ParseError> {
        let dt = DateTime::parse_from_rfc3339(s)?.with_timezone(&Utc);
        let precision = Self::infer_precision(s);
        Ok(Self::new(dt, precision))
    }

    /// Get the underlying DateTime.
    pub fn datetime(&self) -> DateTime<Utc> {
        self.datetime
    }

    /// Get the precision.
    pub fn precision(&self) -> TemporalPrecision {
        self.precision
    }

    /// Create a timestamp for a specific year.
    pub fn year(year: i32) -> Self {
        let dt = Utc.with_ymd_and_hms(year, 1, 1, 0, 0, 0).unwrap();
        Self::new(dt, TemporalPrecision::Year)
    }

    /// Create a timestamp for a specific month.
    pub fn month(year: i32, month: u32) -> Self {
        let dt = Utc.with_ymd_and_hms(year, month, 1, 0, 0, 0).unwrap();
        Self::new(dt, TemporalPrecision::Month)
    }

    /// Create a timestamp for a specific day.
    pub fn day(year: i32, month: u32, day: u32) -> Self {
        let dt = Utc.with_ymd_and_hms(year, month, day, 0, 0, 0).unwrap();
        Self::new(dt, TemporalPrecision::Day)
    }

    /// Builder pattern.
    pub fn builder() -> TimestampBuilder {
        TimestampBuilder::default()
    }

    /// Infer precision from ISO 8601 string format.
    fn infer_precision(s: &str) -> TemporalPrecision {
        if s.contains('.') {
            TemporalPrecision::Millisecond
        } else if s.contains('T') && s.contains(':') {
            let parts: Vec<&str> = s.split(':').collect();
            if parts.len() >= 3 {
                TemporalPrecision::Second
            } else if parts.len() == 2 {
                TemporalPrecision::Minute
            } else {
                TemporalPrecision::Hour
            }
        } else if s.matches('-').count() == 2 {
            TemporalPrecision::Day
        } else if s.matches('-').count() == 1 {
            TemporalPrecision::Month
        } else {
            TemporalPrecision::Year
        }
    }
}

impl fmt::Display for Timestamp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.precision {
            TemporalPrecision::Year => write!(f, "{}", self.datetime.format("%Y")),
            TemporalPrecision::Month => write!(f, "{}", self.datetime.format("%Y-%m")),
            TemporalPrecision::Day => write!(f, "{}", self.datetime.format("%Y-%m-%d")),
            TemporalPrecision::Hour => write!(f, "{}", self.datetime.format("%Y-%m-%dT%H:00:00Z")),
            TemporalPrecision::Minute => write!(f, "{}", self.datetime.format("%Y-%m-%dT%H:%M:00Z")),
            TemporalPrecision::Second => write!(f, "{}", self.datetime.format("%Y-%m-%dT%H:%M:%SZ")),
            TemporalPrecision::Millisecond => write!(f, "{}", self.datetime.format("%Y-%m-%dT%H:%M:%S%.3fZ")),
        }
    }
}

impl Ord for Timestamp {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.datetime.cmp(&other.datetime)
    }
}

impl PartialOrd for Timestamp {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

#[derive(Default)]
pub struct TimestampBuilder {
    datetime: Option<DateTime<Utc>>,
    precision: Option<TemporalPrecision>,
}

impl TimestampBuilder {
    pub fn datetime(mut self, dt: DateTime<Utc>) -> Self {
        self.datetime = Some(dt);
        self
    }

    pub fn precision(mut self, p: TemporalPrecision) -> Self {
        self.precision = Some(p);
        self
    }

    pub fn build(self) -> Timestamp {
        Timestamp {
            datetime: self.datetime.expect("DateTime required"),
            precision: self.precision.unwrap_or(TemporalPrecision::Second),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse() {
        let ts = Timestamp::parse("2024-03-15T14:30:45Z").unwrap();
        assert_eq!(ts.precision, TemporalPrecision::Second);
    }

    #[test]
    fn test_year_precision() {
        let ts = Timestamp::year(2024);
        assert_eq!(ts.precision, TemporalPrecision::Year);
        assert_eq!(format!("{}", ts), "2024");
    }

    #[test]
    fn test_ordering() {
        let ts1 = Timestamp::parse("2024-01-01T00:00:00Z").unwrap();
        let ts2 = Timestamp::parse("2024-12-31T23:59:59Z").unwrap();
        assert!(ts1 < ts2);
    }
}
```

### src/core/event.rs

```rust
use super::{Location, Timestamp};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

/// Unique identifier for an event.
pub type EventId = Uuid;

/// Source reference for event data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SourceRef {
    pub source_type: SourceType,
    pub url: Option<String>,
    pub title: Option<String>,
    pub date: Option<Timestamp>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SourceType {
    Article,
    Report,
    Witness,
    Sensor,
    Social,
    Other(String),
}

impl SourceRef {
    pub fn article<S: Into<String>>(url: S) -> Self {
        Self {
            source_type: SourceType::Article,
            url: Some(url.into()),
            title: None,
            date: None,
        }
    }

    pub fn with_title<S: Into<String>>(mut self, title: S) -> Self {
        self.title = Some(title.into());
        self
    }

    pub fn with_date(mut self, date: Timestamp) -> Self {
        self.date = Some(date);
        self
    }
}

/// A single event in a spatial narrative.
///
/// Events represent things that happened at specific times and places,
/// with associated textual description and metadata.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Event {
    /// Unique identifier
    pub id: EventId,
    /// Where it happened
    pub location: Location,
    /// When it happened
    pub timestamp: Timestamp,
    /// Description of what happened
    pub text: String,
    /// Custom metadata
    pub metadata: HashMap<String, String>,
    /// Source references
    pub sources: Vec<SourceRef>,
    /// Tags for categorization
    pub tags: Vec<String>,
}

impl Event {
    /// Create a new event with generated ID.
    pub fn new(location: Location, timestamp: Timestamp, text: String) -> Self {
        Self {
            id: Uuid::new_v4(),
            location,
            timestamp,
            text,
            metadata: HashMap::new(),
            sources: Vec::new(),
            tags: Vec::new(),
        }
    }

    /// Start building an event.
    pub fn builder() -> EventBuilder {
        EventBuilder::default()
    }

    /// Add a tag.
    pub fn add_tag<S: Into<String>>(&mut self, tag: S) {
        self.tags.push(tag.into());
    }

    /// Add metadata.
    pub fn add_metadata<K, V>(&mut self, key: K, value: V)
    where
        K: Into<String>,
        V: Into<String>,
    {
        self.metadata.insert(key.into(), value.into());
    }

    /// Add a source reference.
    pub fn add_source(&mut self, source: SourceRef) {
        self.sources.push(source);
    }

    /// Check if event has a specific tag.
    pub fn has_tag(&self, tag: &str) -> bool {
        self.tags.iter().any(|t| t == tag)
    }
}

/// Builder for constructing events.
#[derive(Default)]
pub struct EventBuilder {
    id: Option<EventId>,
    location: Option<Location>,
    timestamp: Option<Timestamp>,
    text: Option<String>,
    metadata: HashMap<String, String>,
    sources: Vec<SourceRef>,
    tags: Vec<String>,
}

impl EventBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn id(mut self, id: EventId) -> Self {
        self.id = Some(id);
        self
    }

    pub fn location(mut self, location: Location) -> Self {
        self.location = Some(location);
        self
    }

    pub fn timestamp(mut self, timestamp: Timestamp) -> Self {
        self.timestamp = Some(timestamp);
        self
    }

    pub fn text<S: Into<String>>(mut self, text: S) -> Self {
        self.text = Some(text.into());
        self
    }

    pub fn tag<S: Into<String>>(mut self, tag: S) -> Self {
        self.tags.push(tag.into());
        self
    }

    pub fn metadata<K, V>(mut self, key: K, value: V) -> Self
    where
        K: Into<String>,
        V: Into<String>,
    {
        self.metadata.insert(key.into(), value.into());
        self
    }

    pub fn source(mut self, source: SourceRef) -> Self {
        self.sources.push(source);
        self
    }

    pub fn build(self) -> Event {
        Event {
            id: self.id.unwrap_or_else(Uuid::new_v4),
            location: self.location.expect("Location required"),
            timestamp: self.timestamp.expect("Timestamp required"),
            text: self.text.unwrap_or_default(),
            metadata: self.metadata,
            sources: self.sources,
            tags: self.tags,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_event_builder() {
        let event = Event::builder()
            .location(Location::new(40.7128, -74.0060))
            .timestamp(Timestamp::now())
            .text("Test event")
            .tag("test")
            .metadata("key", "value")
            .source(SourceRef::article("https://example.com"))
            .build();

        assert_eq!(event.text, "Test event");
        assert!(event.has_tag("test"));
        assert_eq!(event.metadata.get("key"), Some(&"value".to_string()));
    }
}
```

### src/transform/distance.rs

```rust
use crate::core::Location;
use geo::prelude::*;

/// Compute geodesic distance between two locations in meters.
///
/// Uses the Haversine formula for great-circle distance.
///
/// # Examples
///
/// ```
/// use spatial_narrative::{Location, transform::distance};
///
/// let nyc = Location::new(40.7128, -74.0060);
/// let la = Location::new(34.0522, -118.2437);
/// let dist = distance(&nyc, &la);
/// assert!((dist - 3936000.0).abs() < 10000.0); // ~3936km
/// ```
pub fn distance(from: &Location, to: &Location) -> f64 {
    let p1 = from.to_point();
    let p2 = to.to_point();
    p1.haversine_distance(&p2)
}

/// Compute bearing from one location to another in degrees.
///
/// Returns value in range [0, 360) where:
/// - 0° = North
/// - 90° = East
/// - 180° = South
/// - 270° = West
pub fn bearing(from: &Location, to: &Location) -> f64 {
    let p1 = from.to_point();
    let p2 = to.to_point();
    
    let lat1 = p1.y().to_radians();
    let lat2 = p2.y().to_radians();
    let dlon = (p2.x() - p1.x()).to_radians();

    let y = dlon.sin() * lat2.cos();
    let x = lat1.cos() * lat2.sin() - lat1.sin() * lat2.cos() * dlon.cos();
    
    let bearing = y.atan2(x).to_degrees();
    (bearing + 360.0) % 360.0
}

/// Compute destination point given distance and bearing.
///
/// # Arguments
///
/// * `start` - Starting location
/// * `distance` - Distance in meters
/// * `bearing` - Bearing in degrees (0 = North)
pub fn destination(start: &Location, distance: f64, bearing: f64) -> Location {
    let p = start.to_point();
    
    let lat1 = p.y().to_radians();
    let lon1 = p.x().to_radians();
    let brng = bearing.to_radians();
    
    let earth_radius = 6371000.0; // meters
    let angular_distance = distance / earth_radius;
    
    let lat2 = (lat1.sin() * angular_distance.cos()
        + lat1.cos() * angular_distance.sin() * brng.cos())
        .asin();
    
    let lon2 = lon1
        + (brng.sin() * angular_distance.sin() * lat1.cos())
            .atan2(angular_distance.cos() - lat1.sin() * lat2.sin());
    
    Location::new(lat2.to_degrees(), lon2.to_degrees())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_distance_same_point() {
        let loc = Location::new(40.7128, -74.0060);
        assert_eq!(distance(&loc, &loc), 0.0);
    }

    #[test]
    fn test_distance_nyc_la() {
        let nyc = Location::new(40.7128, -74.0060);
        let la = Location::new(34.0522, -118.2437);
        let dist = distance(&nyc, &la);
        
        // Should be approximately 3936 km
        assert!((dist - 3936000.0).abs() < 10000.0);
    }

    #[test]
    fn test_bearing_north() {
        let start = Location::new(40.0, -74.0);
        let end = Location::new(41.0, -74.0);
        let brng = bearing(&start, &end);
        
        // Should be approximately 0° (north)
        assert!((brng - 0.0).abs() < 1.0);
    }

    #[test]
    fn test_destination() {
        let start = Location::new(40.7128, -74.0060);
        let dest = destination(&start, 1000.0, 0.0); // 1km north
        
        assert!(dest.lat > start.lat);
        assert!((dest.lon - start.lon).abs() < 0.01);
    }
}
```

---

## Example: Complete Workflow

### examples/basic/analyze_events.rs

```rust
use spatial_narrative::prelude::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a narrative
    let mut narrative = Narrative::builder()
        .title("Protest Movement Timeline")
        .metadata("category", "activism")
        .build();

    // Add events
    narrative.add_event(
        Event::builder()
            .location(Location::new(40.7128, -74.0060))
            .timestamp(Timestamp::parse("2024-01-15T10:00:00Z")?)
            .text("Initial gathering at City Hall")
            .tag("protest")
            .tag("gathering")
            .source(SourceRef::article("https://news.example/story1"))
            .build(),
    );

    narrative.add_event(
        Event::builder()
            .location(Location::new(40.7589, -73.9851))
            .timestamp(Timestamp::parse("2024-01-15T14:00:00Z")?)
            .text("March reached Times Square")
            .tag("protest")
            .tag("march")
            .build(),
    );

    narrative.add_event(
        Event::builder()
            .location(Location::new(40.7614, -73.9776))
            .timestamp(Timestamp::parse("2024-01-15T16:00:00Z")?)
            .text("Final rally at Grand Central")
            .tag("protest")
            .tag("rally")
            .build(),
    );

    // Compute spatial metrics
    let spatial = SpatialMetrics::new(&narrative);
    println!("Narrative Spatial Metrics:");
    println!("  Centroid: {}", spatial.centroid());
    println!("  Total distance: {:.2} km", spatial.total_distance() / 1000.0);
    println!("  Bounds: {:?}", spatial.bounds());

    // Compute temporal metrics
    let temporal = TemporalMetrics::new(&narrative);
    println!("\nNarrative Temporal Metrics:");
    println!("  Duration: {:?}", temporal.duration());
    println!("  Event count: {}", temporal.event_count());

    // Export to GeoJSON
    let geojson = GeoJsonFormat::default();
    geojson.export(&narrative, std::fs::File::create("output.geojson")?)?;
    println!("\nExported to output.geojson");

    Ok(())
}
```

---

## Cargo.toml

```toml
[package]
name = "spatial-narrative"
version = "0.1.0"
edition = "2021"
authors = ["Your Name <you@example.com>"]
license = "MIT OR Apache-2.0"
description = "A Rust library for working with spatial narratives"
repository = "https://github.com/yourusername/spatial-narrative"
keywords = ["geospatial", "narrative", "gis", "timeline", "journalism"]
categories = ["science", "text-processing"]

[dependencies]
# Geometric types and algorithms
geo = "0.28"
geo-types = "0.7"

# Spatial indexing
rstar = "0.12"

# Date/time handling
chrono = { version = "0.4", features = ["serde"] }
chrono-tz = "0.9"

# Serialization
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

# Graph algorithms
petgraph = "0.6"

# Parallel processing
rayon = "1.10"

# Error handling
thiserror = "1.0"
anyhow = "1.0"

# IDs
uuid = { version = "1.10", features = ["v4", "serde"] }

# CSV parsing
csv = "1.3"

# Regular expressions
regex = "1.10"

[dev-dependencies]
criterion = "0.5"
proptest = "1.5"

[features]
default = []
cli = ["clap"]
gpx-support = ["gpx"]
database = ["rusqlite"]
full = ["cli", "gpx-support", "database"]

[[bench]]
name = "spatial_queries"
harness = false

[[bench]]
name = "clustering"
harness = false
```

---

## Testing Examples

### tests/integration/geojson_roundtrip.rs

```rust
use spatial_narrative::prelude::*;
use std::fs;
use tempfile::NamedTempFile;

#[test]
fn test_geojson_roundtrip() {
    // Create test narrative
    let mut original = Narrative::builder()
        .title("Test Narrative")
        .build();

    original.add_event(
        Event::builder()
            .location(Location::new(40.0, -74.0))
            .timestamp(Timestamp::now())
            .text("Test event")
            .tag("test")
            .build(),
    );

    // Export to file
    let temp_file = NamedTempFile::new().unwrap();
    let path = temp_file.path();
    
    let format = GeoJsonFormat::default();
    format
        .export(&original, fs::File::create(path).unwrap())
        .unwrap();

    // Import back
    let loaded = format
        .import(fs::File::open(path).unwrap())
        .unwrap();

    // Verify
    assert_eq!(original.title, loaded.title);
    assert_eq!(original.events().len(), loaded.events().len());
}
```

---

## Benchmark Examples

### benches/spatial_queries.rs

```rust
use criterion::{black_box, criterion_group, criterion_main, Criterion, BenchmarkId};
use spatial_narrative::prelude::*;

fn generate_test_narrative(n: usize) -> Narrative {
    let mut narrative = Narrative::builder().title("Benchmark").build();
    
    for i in 0..n {
        let lat = 40.0 + (i as f64 / n as f64);
        let lon = -74.0 + (i as f64 / n as f64);
        
        narrative.add_event(
            Event::builder()
                .location(Location::new(lat, lon))
                .timestamp(Timestamp::now())
                .text(format!("Event {}", i))
                .build(),
        );
    }
    
    narrative
}

fn bench_spatial_query(c: &mut Criterion) {
    let mut group = c.benchmark_group("spatial_query");
    
    for size in [100, 1000, 10000] {
        let narrative = generate_test_narrative(size);
        let index = SpatialIndex::from_events(narrative.events());
        let bbox = GeoBounds::new(40.2, -74.2, 40.4, -74.0);
        
        group.bench_with_input(
            BenchmarkId::new("indexed", size),
            &size,
            |b, _| {
                b.iter(|| index.query_bbox(black_box(bbox)))
            },
        );
    }
    
    group.finish();
}

criterion_group!(benches, bench_spatial_query);
criterion_main!(benches);
```

---

## CLI Tool Example

### src/bin/sn-analyze.rs

```rust
use clap::Parser;
use spatial_narrative::prelude::*;
use std::path::PathBuf;

#[derive(Parser)]
#[command(name = "sn-analyze")]
#[command(about = "Analyze spatial narratives", long_about = None)]
struct Args {
    /// Input file (GeoJSON format)
    #[arg(short, long)]
    input: PathBuf,

    /// Show spatial metrics
    #[arg(long)]
    spatial: bool,

    /// Show temporal metrics
    #[arg(long)]
    temporal: bool,

    /// Cluster events (DBSCAN epsilon in meters)
    #[arg(long)]
    cluster: Option<f64>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let args = Args::parse();

    // Load narrative
    let narrative = Narrative::from_geojson(&args.input)?;
    println!("Loaded narrative: {}", narrative.title);
    println!("Events: {}", narrative.events().len());

    // Spatial metrics
    if args.spatial {
        let metrics = SpatialMetrics::new(&narrative);
        println!("\nSpatial Metrics:");
        println!("  Centroid: {}", metrics.centroid());
        println!("  Total distance: {:.2} km", metrics.total_distance() / 1000.0);
        println!("  Dispersion: {:.2} m", metrics.dispersion());
    }

    // Temporal metrics
    if args.temporal {
        let metrics = TemporalMetrics::new(&narrative);
        println!("\nTemporal Metrics:");
        println!("  Duration: {:?}", metrics.duration());
        println!("  Time span: {} - {}", 
            metrics.start_time(), 
            metrics.end_time()
        );
    }

    // Clustering
    if let Some(eps) = args.cluster {
        let clusters = SpatialClustering::dbscan(
            narrative.events(),
            eps,
            3, // min_pts
        );
        
        println!("\nClustering (eps={}m):", eps);
        println!("  Found {} clusters", clusters.len());
        
        for (i, cluster) in clusters.iter().enumerate() {
            println!("  Cluster {}: {} events", i, cluster.len());
        }
    }

    Ok(())
}
```

---

This implementation guide provides concrete code examples that flesh out the architecture described in the main specification. The code is production-ready with proper error handling, documentation, and tests.