patient-matching 0.2.0

Patient matching algorithms for healthcare information exchange
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
//! Data models for patient demographics and identifiers.
//!
//! This module is intentionally **logic-free**: it defines the types that
//! flow through the matching engine but contains no matching code itself.
//! See [`crate::matcher`] for the engine and [`crate::normalizer`] for the
//! text transformations that the matcher applies to these fields.
//!
//! All public types here are `Serialize + Deserialize` so they round-trip
//! through JSON, MessagePack, or any other `serde` format.
//!
//! ## Building a patient
//!
//! Prefer [`Patient::builder`] over constructing the struct literal — the
//! builder accepts `impl Into<String>` so call-sites can pass `&str`,
//! `String`, or owned values interchangeably.
//!
//! ```
//! use patient_matching::{Gender, Patient};
//! use chrono::NaiveDate;
//!
//! let p = Patient::builder()
//!     .nhs_number("9434765919")
//!     .given_name("Dafydd")
//!     .family_name("Jones")
//!     .date_of_birth(NaiveDate::from_ymd_opt(1980, 5, 15).unwrap())
//!     .gender(Gender::Male)
//!     .build();
//!
//! assert_eq!(p.given_name.as_deref(), Some("Dafydd"));
//! assert_eq!(p.gender, Some(Gender::Male));
//! ```

use chrono::NaiveDate;
use serde::{Deserialize, Serialize};

/// Gender/sex classification used to compare two [`Patient`] records.
///
/// The four-arm enumeration mirrors common healthcare data dictionaries
/// (HL7 FHIR `AdministrativeGender`, NHS Data Dictionary `Person Gender`).
/// `Other` and `Unknown` are deliberately distinct: `Other` represents a
/// recorded non-binary value, whereas `Unknown` represents missing data.
///
/// # Example
///
/// ```
/// use patient_matching::Gender;
///
/// let g = Gender::Female;
/// assert_eq!(g, Gender::Female);
/// assert_ne!(g, Gender::Male);
/// ```
///
/// `Gender` is `Copy`, so it is cheap to pass by value.
///
/// ```
/// # use patient_matching::Gender;
/// fn describe(g: Gender) -> &'static str {
///     match g {
///         Gender::Male    => "male",
///         Gender::Female  => "female",
///         Gender::Other   => "other",
///         Gender::Unknown => "unknown",
///     }
/// }
/// assert_eq!(describe(Gender::Male), "male");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum Gender {
    /// Administrative gender recorded as male.
    Male,
    /// Administrative gender recorded as female.
    Female,
    /// Recorded non-binary or otherwise specified value.
    Other,
    /// No gender recorded, or gender intentionally withheld.
    Unknown,
}

/// Physical address used as supporting evidence in patient matching.
///
/// All fields are `Option<String>` so partial addresses are first-class —
/// a record with only a postcode is still useful for matching.
///
/// The matcher does **not** weight every component equally; see
/// [`crate::matcher::MatchingEngine`] for the weighted comparison rules.
///
/// # Example
///
/// ```
/// use patient_matching::Address;
///
/// let mut addr = Address::new();
/// addr.line1    = Some("10 Downing Street".into());
/// addr.city     = Some("London".into());
/// addr.postcode = Some("SW1A 2AA".into());
///
/// assert_eq!(addr.postcode.as_deref(), Some("SW1A 2AA"));
/// assert!(addr.country.is_none());
/// ```
///
/// `Address` is JSON round-trippable.
///
/// ```
/// # use patient_matching::Address;
/// let mut a = Address::new();
/// a.postcode = Some("CF10 1AA".into());
///
/// let json = serde_json::to_string(&a).unwrap();
/// let back: Address = serde_json::from_str(&json).unwrap();
/// assert_eq!(a, back);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Address {
    /// First line — typically house number and street, e.g. `"10 Downing Street"`.
    pub line1: Option<String>,
    /// Second line — typically flat, locality, or care-of details.
    pub line2: Option<String>,
    /// Town or city, e.g. `"Cardiff"`.
    pub city: Option<String>,
    /// County or administrative region, e.g. `"South Glamorgan"`.
    pub county: Option<String>,
    /// Postal code, e.g. `"CF10 1AA"`. Compared after whitespace normalisation.
    pub postcode: Option<String>,
    /// Country, e.g. `"Wales"` or `"United Kingdom"`.
    pub country: Option<String>,
}

impl Address {
    /// Construct an empty address with every field set to `None`.
    ///
    /// # Example
    ///
    /// ```
    /// use patient_matching::Address;
    ///
    /// let a = Address::new();
    /// assert!(a.line1.is_none());
    /// assert!(a.postcode.is_none());
    /// ```
    pub fn new() -> Self {
        Self {
            line1: None,
            line2: None,
            city: None,
            county: None,
            postcode: None,
            country: None,
        }
    }
}

impl Default for Address {
    /// Identical to [`Address::new`].
    fn default() -> Self {
        Self::new()
    }
}

/// Core patient demographic data structure.
///
/// Every field is optional. The matcher tolerates missing data field-by-field
/// — a `None` value never penalises a patient. See
/// [`crate::matcher::MatchingEngine::match_patients`] for how missing fields
/// affect the weighted score.
///
/// Construct via [`Patient::builder`] rather than struct literal syntax so
/// the call-site stays compact and forward-compatible if fields are added.
///
/// # Example
///
/// ```
/// use patient_matching::{Gender, Patient};
/// use chrono::NaiveDate;
///
/// let p = Patient::builder()
///     .given_name("Siân")
///     .family_name("Evans")
///     .date_of_birth(NaiveDate::from_ymd_opt(1990, 3, 10).unwrap())
///     .gender(Gender::Female)
///     .build();
///
/// assert_eq!(p.given_name.as_deref(), Some("Siân"));
/// assert!(p.nhs_number.is_none());
/// ```
///
/// `Patient` round-trips through `serde`.
///
/// ```
/// # use patient_matching::Patient;
/// let p = Patient::builder().given_name("Test").family_name("Patient").build();
/// let json = serde_json::to_string(&p).unwrap();
/// let back: Patient = serde_json::from_str(&json).unwrap();
/// assert_eq!(p, back);
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Patient {
    /// NHS-format check-digit identifier (parsed via the `nhs-number` crate)
    /// or equivalent national identifier. Whitespace is tolerated; the matcher
    /// parses the value through `NHSNumber::from_str` before comparison.
    pub nhs_number: Option<String>,

    /// Given name (sometimes called "first name" or "forename").
    pub given_name: Option<String>,

    /// Middle name(s). Currently unused in scoring — see spec OQ-1.
    pub middle_name: Option<String>,

    /// Family name (sometimes called "surname" or "last name").
    pub family_name: Option<String>,

    /// Date of birth. Compared by exact equality.
    pub date_of_birth: Option<NaiveDate>,

    /// Administrative gender. See [`Gender`].
    pub gender: Option<Gender>,

    /// Current residential address.
    pub address: Option<Address>,

    /// Previous residential addresses for historical matching. Carried on the
    /// record but not yet scored by the matcher (see spec OQ-3).
    pub previous_addresses: Vec<Address>,

    /// Primary phone number. Falls back to [`Self::mobile`] in scoring if absent.
    pub phone: Option<String>,

    /// Mobile phone number. Used as the fallback for [`Self::phone`].
    pub mobile: Option<String>,

    /// Email address. Not currently used in scoring (see spec task T-11).
    pub email: Option<String>,

    /// Local hospital or practice identifier. Not normalised — different
    /// organisations may issue colliding values.
    pub local_id: Option<String>,
}

impl Patient {
    /// Begin constructing a [`Patient`] with the [`PatientBuilder`].
    ///
    /// All fields default to `None` / empty until a setter is called.
    ///
    /// # Example
    ///
    /// ```
    /// use patient_matching::Patient;
    ///
    /// let p = Patient::builder()
    ///     .given_name("John")
    ///     .family_name("Smith")
    ///     .build();
    ///
    /// assert_eq!(p.family_name.as_deref(), Some("Smith"));
    /// ```
    pub fn builder() -> PatientBuilder {
        PatientBuilder::default()
    }

    /// Validate that the patient carries at least one identifying field.
    ///
    /// Returns `Ok(())` if any of `nhs_number`, `given_name`, or `family_name`
    /// is set; otherwise returns [`crate::MatchingError::MissingField`].
    ///
    /// This is **not** invoked automatically by the matcher — call it at the
    /// system boundary when you ingest data, not on every comparison.
    ///
    /// # Example
    ///
    /// ```
    /// use patient_matching::Patient;
    ///
    /// assert!(Patient::builder().given_name("Ada").build().validate().is_ok());
    /// assert!(Patient::builder().nhs_number("9434765919").build().validate().is_ok());
    /// assert!(Patient::builder().build().validate().is_err());
    /// ```
    pub fn validate(&self) -> crate::Result<()> {
        if self.given_name.is_none() && self.family_name.is_none() && self.nhs_number.is_none() {
            return Err(crate::MatchingError::MissingField(
                "At least one of: given_name, family_name, or nhs_number is required".to_string(),
            ));
        }
        Ok(())
    }
}

/// Fluent builder for [`Patient`].
///
/// All setters accept `impl Into<String>` so call-sites may pass `&str`,
/// `String`, or `&String` interchangeably without explicit conversion.
///
/// # Example
///
/// ```
/// use patient_matching::{Gender, Patient, PatientBuilder};
/// use chrono::NaiveDate;
///
/// let p: Patient = PatientBuilder::default()
///     .nhs_number("9434765919")
///     .given_name(String::from("Owen"))   // owned String
///     .family_name("Williams")            // &str
///     .date_of_birth(NaiveDate::from_ymd_opt(1972, 11, 4).unwrap())
///     .gender(Gender::Male)
///     .build();
///
/// assert_eq!(p.nhs_number.as_deref(), Some("9434765919"));
/// ```
#[derive(Default)]
pub struct PatientBuilder {
    nhs_number: Option<String>,
    given_name: Option<String>,
    middle_name: Option<String>,
    family_name: Option<String>,
    date_of_birth: Option<NaiveDate>,
    gender: Option<Gender>,
    address: Option<Address>,
    previous_addresses: Vec<Address>,
    phone: Option<String>,
    mobile: Option<String>,
    email: Option<String>,
    local_id: Option<String>,
}

impl PatientBuilder {
    /// Set the NHS-format check-digit identifier.
    ///
    /// The string is stored verbatim; normalisation and validation happen at
    /// match time via the `nhs-number` crate. Whitespace is permitted.
    ///
    /// ```
    /// # use patient_matching::Patient;
    /// let p = Patient::builder().nhs_number("943 476 5919").build();
    /// assert_eq!(p.nhs_number.as_deref(), Some("943 476 5919"));
    /// ```
    pub fn nhs_number<S: Into<String>>(mut self, value: S) -> Self {
        self.nhs_number = Some(value.into());
        self
    }

    /// Set the given name (forename).
    ///
    /// ```
    /// # use patient_matching::Patient;
    /// let p = Patient::builder().given_name("Carys").build();
    /// assert_eq!(p.given_name.as_deref(), Some("Carys"));
    /// ```
    pub fn given_name<S: Into<String>>(mut self, value: S) -> Self {
        self.given_name = Some(value.into());
        self
    }

    /// Set the middle name(s).
    ///
    /// Stored on the patient but not currently used in matching scoring
    /// (see spec OQ-1).
    ///
    /// ```
    /// # use patient_matching::Patient;
    /// let p = Patient::builder().middle_name("Eleri").build();
    /// assert_eq!(p.middle_name.as_deref(), Some("Eleri"));
    /// ```
    pub fn middle_name<S: Into<String>>(mut self, value: S) -> Self {
        self.middle_name = Some(value.into());
        self
    }

    /// Set the family name (surname).
    ///
    /// ```
    /// # use patient_matching::Patient;
    /// let p = Patient::builder().family_name("Pritchard").build();
    /// assert_eq!(p.family_name.as_deref(), Some("Pritchard"));
    /// ```
    pub fn family_name<S: Into<String>>(mut self, value: S) -> Self {
        self.family_name = Some(value.into());
        self
    }

    /// Set the date of birth.
    ///
    /// ```
    /// # use patient_matching::Patient;
    /// use chrono::NaiveDate;
    /// let dob = NaiveDate::from_ymd_opt(1990, 1, 1).unwrap();
    /// let p = Patient::builder().date_of_birth(dob).build();
    /// assert_eq!(p.date_of_birth, Some(dob));
    /// ```
    pub fn date_of_birth(mut self, value: NaiveDate) -> Self {
        self.date_of_birth = Some(value);
        self
    }

    /// Set the recorded gender.
    ///
    /// ```
    /// # use patient_matching::{Gender, Patient};
    /// let p = Patient::builder().gender(Gender::Female).build();
    /// assert_eq!(p.gender, Some(Gender::Female));
    /// ```
    pub fn gender(mut self, value: Gender) -> Self {
        self.gender = Some(value);
        self
    }

    /// Set the current residential address.
    ///
    /// ```
    /// # use patient_matching::{Address, Patient};
    /// let mut a = Address::new();
    /// a.postcode = Some("CF10 1AA".into());
    /// let p = Patient::builder().address(a).build();
    /// assert_eq!(p.address.unwrap().postcode.as_deref(), Some("CF10 1AA"));
    /// ```
    pub fn address(mut self, value: Address) -> Self {
        self.address = Some(value);
        self
    }

    /// Set the list of previous addresses.
    ///
    /// Stored on the patient but not yet scored (see spec OQ-3).
    ///
    /// ```
    /// # use patient_matching::{Address, Patient};
    /// let p = Patient::builder()
    ///     .previous_addresses(vec![Address::new(), Address::new()])
    ///     .build();
    /// assert_eq!(p.previous_addresses.len(), 2);
    /// ```
    pub fn previous_addresses(mut self, value: Vec<Address>) -> Self {
        self.previous_addresses = value;
        self
    }

    /// Set the primary phone number.
    ///
    /// ```
    /// # use patient_matching::Patient;
    /// let p = Patient::builder().phone("029 2034 5678").build();
    /// assert_eq!(p.phone.as_deref(), Some("029 2034 5678"));
    /// ```
    pub fn phone<S: Into<String>>(mut self, value: S) -> Self {
        self.phone = Some(value.into());
        self
    }

    /// Set the mobile phone number. Used as a fallback when `phone` is absent.
    ///
    /// ```
    /// # use patient_matching::Patient;
    /// let p = Patient::builder().mobile("07700 900123").build();
    /// assert_eq!(p.mobile.as_deref(), Some("07700 900123"));
    /// ```
    pub fn mobile<S: Into<String>>(mut self, value: S) -> Self {
        self.mobile = Some(value.into());
        self
    }

    /// Set the email address. Not currently used in scoring.
    ///
    /// ```
    /// # use patient_matching::Patient;
    /// let p = Patient::builder().email("alice@example.org").build();
    /// assert_eq!(p.email.as_deref(), Some("alice@example.org"));
    /// ```
    pub fn email<S: Into<String>>(mut self, value: S) -> Self {
        self.email = Some(value.into());
        self
    }

    /// Set the local hospital or practice identifier.
    ///
    /// ```
    /// # use patient_matching::Patient;
    /// let p = Patient::builder().local_id("MRN-12345").build();
    /// assert_eq!(p.local_id.as_deref(), Some("MRN-12345"));
    /// ```
    pub fn local_id<S: Into<String>>(mut self, value: S) -> Self {
        self.local_id = Some(value.into());
        self
    }

    /// Consume the builder and produce the [`Patient`].
    ///
    /// ```
    /// # use patient_matching::Patient;
    /// let p = Patient::builder().given_name("Eira").build();
    /// assert!(p.family_name.is_none());
    /// ```
    pub fn build(self) -> Patient {
        Patient {
            nhs_number: self.nhs_number,
            given_name: self.given_name,
            middle_name: self.middle_name,
            family_name: self.family_name,
            date_of_birth: self.date_of_birth,
            gender: self.gender,
            address: self.address,
            previous_addresses: self.previous_addresses,
            phone: self.phone,
            mobile: self.mobile,
            email: self.email,
            local_id: self.local_id,
        }
    }
}

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

    #[test]
    fn address_new_is_all_none() {
        let a = Address::new();
        assert!(a.line1.is_none());
        assert!(a.line2.is_none());
        assert!(a.city.is_none());
        assert!(a.county.is_none());
        assert!(a.postcode.is_none());
        assert!(a.country.is_none());
    }

    #[test]
    fn address_default_matches_new() {
        assert_eq!(Address::default(), Address::new());
    }

    #[test]
    fn address_round_trips_through_serde() {
        let mut a = Address::new();
        a.line1 = Some("123 High Street".into());
        a.postcode = Some("CF10 1AA".into());
        let json = serde_json::to_string(&a).expect("serialise");
        let back: Address = serde_json::from_str(&json).expect("deserialise");
        assert_eq!(a, back);
    }

    #[test]
    fn patient_builder_starts_empty() {
        let p = Patient::builder().build();
        assert!(p.nhs_number.is_none());
        assert!(p.given_name.is_none());
        assert!(p.family_name.is_none());
        assert!(p.date_of_birth.is_none());
        assert!(p.gender.is_none());
        assert!(p.address.is_none());
        assert!(p.previous_addresses.is_empty());
        assert!(p.phone.is_none());
        assert!(p.mobile.is_none());
        assert!(p.email.is_none());
        assert!(p.local_id.is_none());
    }

    #[test]
    fn patient_builder_accepts_str_and_string() {
        let p = Patient::builder()
            .given_name("Owen") // &str
            .family_name(String::from("Jones")) // String
            .build();
        assert_eq!(p.given_name.as_deref(), Some("Owen"));
        assert_eq!(p.family_name.as_deref(), Some("Jones"));
    }

    #[test]
    fn patient_validate_requires_one_of_three_fields() {
        assert!(
            Patient::builder()
                .given_name("a")
                .build()
                .validate()
                .is_ok()
        );
        assert!(
            Patient::builder()
                .family_name("a")
                .build()
                .validate()
                .is_ok()
        );
        assert!(
            Patient::builder()
                .nhs_number("9434765919")
                .build()
                .validate()
                .is_ok()
        );
        let err = Patient::builder()
            .build()
            .validate()
            .expect_err("should be missing");
        assert!(matches!(err, crate::MatchingError::MissingField(_)));
    }

    #[test]
    fn patient_round_trips_through_serde() {
        let p = Patient::builder()
            .nhs_number("9434765919")
            .given_name("Carys")
            .family_name("Pritchard")
            .date_of_birth(chrono::NaiveDate::from_ymd_opt(1990, 6, 1).unwrap())
            .gender(Gender::Female)
            .build();
        let json = serde_json::to_string(&p).expect("serialise");
        let back: Patient = serde_json::from_str(&json).expect("deserialise");
        assert_eq!(p, back);
    }

    #[test]
    fn gender_is_copy_and_eq() {
        let g = Gender::Female;
        let h = g; // Copy
        assert_eq!(g, h);
        assert_ne!(g, Gender::Male);
    }

    #[test]
    fn previous_addresses_setter_replaces_vec() {
        let mut a = Address::new();
        a.postcode = Some("CF10 1AA".into());
        let p = Patient::builder()
            .previous_addresses(vec![a.clone()])
            .build();
        assert_eq!(p.previous_addresses, vec![a]);
    }
}