rvdna 0.3.0

rvDNA — AI-native genomic analysis. 20-SNP biomarker risk scoring, streaming anomaly detection, 64-dim profile vectors, 23andMe genotyping, CYP2D6/CYP2C19 pharmacogenomics, variant calling, protein prediction, and HNSW vector search in pure Rust.
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
//! Health variant analysis for genotyping data
//!
//! Clinically significant variant interpretation for 17+ health-relevant
//! SNPs commonly found in 23andMe/genotyping panels. Covers APOE, BRCA1/2,
//! TP53, MTHFR, COMT, OPRM1, CYP1A2, and more.
//!
//! Based on: <https://github.com/ericporres/rvdna-bridge>

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Result of analyzing a single health variant
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HealthVariantResult {
    /// rsid identifier
    pub rsid: String,
    /// Gene name
    pub gene: String,
    /// Variant common name
    pub name: String,
    /// Observed genotype
    pub genotype: String,
    /// Risk allele
    pub risk_allele: char,
    /// Human-readable interpretation
    pub interpretation: String,
    /// Clinical significance
    pub clinical_significance: String,
}

/// APOE genotype determination result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApoeResult {
    /// Full APOE genotype string (e.g., "e2/e3")
    pub genotype: String,
    /// rs429358 genotype
    pub rs429358: String,
    /// rs7412 genotype
    pub rs7412: String,
}

/// MTHFR compound status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MthfrResult {
    /// C677T genotype (rs1801133)
    pub c677t: String,
    /// A1298C genotype (rs1801131)
    pub a1298c: String,
    /// Compound risk score (0-4)
    pub score: u8,
    /// Clinical assessment text
    pub assessment: String,
}

/// Pain sensitivity profile (COMT + OPRM1)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PainProfile {
    /// COMT genotype (rs4680)
    pub comt: String,
    /// OPRM1 genotype (rs1799971)
    pub oprm1: String,
    /// Combined pain score (0-4)
    pub score: u8,
    /// Sensitivity label
    pub label: String,
    /// COMT interpretation
    pub comt_note: String,
    /// OPRM1 interpretation
    pub oprm1_note: String,
}

// ── Internal definition type ──

struct VDef {
    rsid: &'static str,
    gene: &'static str,
    name: &'static str,
    risk_allele: char,
    // (genotype, description, significance)
    interps: &'static [(&'static str, &'static str, &'static str)],
}

static HEALTH_VARIANTS: &[VDef] = &[
    // ── APOE (Alzheimer's) ──
    VDef {
        rsid: "rs429358",
        gene: "APOE",
        name: "APOE e4 determinant",
        risk_allele: 'C',
        interps: &[
            (
                "TT",
                "APOE e3/e3 or e2/e3 (depends on rs7412)",
                "Protective/Normal",
            ),
            (
                "CT",
                "One e4 allele present",
                "Increased Alzheimer's risk (~3x)",
            ),
            (
                "CC",
                "Two e4 alleles present",
                "Significantly increased Alzheimer's risk (~12x)",
            ),
        ],
    },
    VDef {
        rsid: "rs7412",
        gene: "APOE",
        name: "APOE e2 determinant",
        risk_allele: 'T',
        interps: &[
            ("CC", "No e2 allele", "Normal"),
            (
                "CT",
                "One e2 allele present",
                "Protective - reduced Alzheimer's risk",
            ),
            ("TT", "Two e2 alleles (e2/e2)", "Protective; monitor lipids"),
        ],
    },
    // ── TP53 (cancer) ──
    VDef {
        rsid: "rs1042522",
        gene: "TP53",
        name: "p53 Pro72Arg (R72P)",
        risk_allele: 'G',
        interps: &[
            (
                "CC",
                "Pro/Pro homozygous",
                "Normal apoptosis; slightly increased cancer survival",
            ),
            (
                "CG",
                "Pro/Arg heterozygous",
                "Mixed - Arg allele has stronger apoptotic activity",
            ),
            (
                "GG",
                "Arg/Arg homozygous",
                "Stronger apoptotic response; variable cancer risk",
            ),
        ],
    },
    // ── BRCA1 ──
    VDef {
        rsid: "rs80357906",
        gene: "BRCA1",
        name: "BRCA1 5382insC (Ashkenazi founder)",
        risk_allele: 'I',
        interps: &[
            (
                "DD",
                "No insertion detected",
                "Normal - no BRCA1 5382insC mutation",
            ),
            (
                "DI",
                "Heterozygous carrier",
                "INCREASED breast/ovarian cancer risk - genetic counseling recommended",
            ),
            (
                "II",
                "Homozygous insertion",
                "HIGH breast/ovarian cancer risk - urgent genetic counseling",
            ),
        ],
    },
    VDef {
        rsid: "rs28897696",
        gene: "BRCA1",
        name: "BRCA1 missense variant",
        risk_allele: 'A',
        interps: &[
            ("GG", "Reference genotype", "Normal"),
            (
                "AG",
                "Heterozygous",
                "Variant of uncertain significance - consult genetic counselor",
            ),
            ("AA", "Homozygous variant", "Consult genetic counselor"),
        ],
    },
    // ── BRCA2 ──
    VDef {
        rsid: "rs11571833",
        gene: "BRCA2",
        name: "BRCA2 K3326X",
        risk_allele: 'T',
        interps: &[
            ("AA", "Reference genotype", "Normal"),
            (
                "AT",
                "Heterozygous",
                "Modestly increased cancer risk (OR ~1.3)",
            ),
            (
                "TT",
                "Homozygous variant",
                "Increased cancer risk - genetic counseling recommended",
            ),
        ],
    },
    // ── MTHFR (folate metabolism) ──
    VDef {
        rsid: "rs1801133",
        gene: "MTHFR",
        name: "C677T",
        risk_allele: 'A',
        interps: &[
            (
                "GG",
                "CC genotype (normal)",
                "Normal MTHFR enzyme activity (100%)",
            ),
            (
                "AG",
                "CT heterozygous",
                "Reduced enzyme activity (~65%). Consider methylfolate.",
            ),
            (
                "AA",
                "TT homozygous",
                "Significantly reduced activity (~30%). Methylfolate recommended.",
            ),
        ],
    },
    VDef {
        rsid: "rs1801131",
        gene: "MTHFR",
        name: "A1298C",
        risk_allele: 'T',
        interps: &[
            ("GG", "CC homozygous variant", "Reduced enzyme activity"),
            ("GT", "AC heterozygous", "Mildly reduced enzyme activity"),
            (
                "TT",
                "AA reference",
                "Normal MTHFR activity at this position",
            ),
        ],
    },
    // ── COMT (dopamine/pain) ──
    VDef {
        rsid: "rs4680",
        gene: "COMT",
        name: "Val158Met",
        risk_allele: 'A',
        interps: &[
            (
                "GG",
                "Val/Val",
                "Higher COMT activity, lower dopamine. Better stress resilience.",
            ),
            (
                "AG",
                "Val/Met heterozygous",
                "Intermediate COMT activity. Balanced dopamine.",
            ),
            (
                "AA",
                "Met/Met",
                "Lower COMT activity, higher dopamine. Higher pain sensitivity.",
            ),
        ],
    },
    // ── OPRM1 (opioid receptor) ──
    VDef {
        rsid: "rs1799971",
        gene: "OPRM1",
        name: "A118G (Asn40Asp)",
        risk_allele: 'G',
        interps: &[
            ("AA", "Asn/Asn", "Normal opioid sensitivity"),
            (
                "AG",
                "Asn/Asp heterozygous",
                "Reduced opioid sensitivity; may need higher doses.",
            ),
            ("GG", "Asp/Asp", "Significantly reduced opioid sensitivity."),
        ],
    },
    // ── CYP1A2 (caffeine) ──
    VDef {
        rsid: "rs762551",
        gene: "CYP1A2",
        name: "Caffeine metabolism",
        risk_allele: 'C',
        interps: &[
            (
                "AA",
                "Fast metabolizer",
                "Rapid caffeine clearance. Coffee may REDUCE heart disease risk.",
            ),
            (
                "AC",
                "Intermediate",
                "Moderate caffeine clearance. Moderate coffee intake recommended.",
            ),
            (
                "CC",
                "Slow metabolizer",
                "Slow caffeine clearance. Excess coffee may INCREASE heart risk.",
            ),
        ],
    },
    // ── Lactose ──
    VDef {
        rsid: "rs4988235",
        gene: "MCM6/LCT",
        name: "Lactase persistence (European)",
        risk_allele: 'G',
        interps: &[
            (
                "AA",
                "Lactase persistent",
                "Likely lactose TOLERANT into adulthood",
            ),
            (
                "AG",
                "Heterozygous",
                "Likely lactose tolerant (persistence is dominant)",
            ),
            (
                "GG",
                "Lactase non-persistent",
                "Likely lactose INTOLERANT in adulthood",
            ),
        ],
    },
    // ── OXTR (oxytocin receptor) ──
    VDef {
        rsid: "rs53576",
        gene: "OXTR",
        name: "Oxytocin receptor",
        risk_allele: 'A',
        interps: &[
            (
                "GG",
                "GG genotype",
                "Higher empathy scores; better social cognition.",
            ),
            (
                "AG",
                "AG heterozygous",
                "Intermediate empathy and social cognition.",
            ),
            (
                "AA",
                "AA genotype",
                "May have lower empathy; potentially more resilient to social stress.",
            ),
        ],
    },
    // ── HTR2A (serotonin) ──
    VDef {
        rsid: "rs6311",
        gene: "HTR2A",
        name: "Serotonin 2A receptor (-1438G/A)",
        risk_allele: 'T',
        interps: &[
            ("CC", "GG genotype", "Normal serotonin receptor expression"),
            (
                "CT",
                "GA heterozygous",
                "Slightly altered serotonin signaling",
            ),
            (
                "TT",
                "AA genotype",
                "Altered serotonin receptor density; may affect SSRI response",
            ),
        ],
    },
    // ── ANKK1/DRD2 (dopamine) ──
    VDef {
        rsid: "rs1800497",
        gene: "ANKK1/DRD2",
        name: "Taq1A (dopamine receptor)",
        risk_allele: 'A',
        interps: &[
            ("GG", "A2/A2", "Normal dopamine receptor density"),
            (
                "AG",
                "A1/A2 heterozygous",
                "Reduced D2 receptor density (~30% less). Reward-seeking.",
            ),
            (
                "AA",
                "A1/A1",
                "Significantly reduced D2 receptor density. Higher addiction risk.",
            ),
        ],
    },
    // ── SLCO1B1 (statin metabolism) ──
    VDef {
        rsid: "rs4363657",
        gene: "SLCO1B1",
        name: "Statin transporter",
        risk_allele: 'C',
        interps: &[
            (
                "TT",
                "Reference",
                "Normal statin metabolism. Standard dosing.",
            ),
            (
                "CT",
                "Heterozygous",
                "Increased statin myopathy risk (~4.5x). Consider lower dose.",
            ),
            (
                "CC",
                "Homozygous variant",
                "High statin myopathy risk (~17x). Use lowest effective dose.",
            ),
        ],
    },
    // ── NQO1 (oxidative stress) ──
    VDef {
        rsid: "rs1800566",
        gene: "NQO1",
        name: "Pro187Ser (oxidative stress)",
        risk_allele: 'T',
        interps: &[
            ("CC", "Pro/Pro (reference)", "Normal NQO1 enzyme activity"),
            (
                "CT",
                "Pro/Ser heterozygous",
                "Reduced NQO1 activity (~3x lower). Impaired detox.",
            ),
            (
                "TT",
                "Ser/Ser",
                "No NQO1 activity. Significantly impaired quinone detoxification.",
            ),
        ],
    },
];

/// Analyze health variants from a genotype map (rsid -> genotype string).
pub fn analyze_health_variants(genotypes: &HashMap<String, String>) -> Vec<HealthVariantResult> {
    let mut results = Vec::new();

    for def in HEALTH_VARIANTS {
        if let Some(gt) = genotypes.get(def.rsid) {
            let (desc, sig) = def
                .interps
                .iter()
                .find(|(g, _, _)| *g == gt.as_str())
                .map(|(_, d, s)| (d.to_string(), s.to_string()))
                .unwrap_or_else(|| {
                    (
                        format!("Genotype {} - not in standard table", gt),
                        "Consult genetic counselor".to_string(),
                    )
                });

            results.push(HealthVariantResult {
                rsid: def.rsid.to_string(),
                gene: def.gene.to_string(),
                name: def.name.to_string(),
                genotype: gt.clone(),
                risk_allele: def.risk_allele,
                interpretation: desc,
                clinical_significance: sig,
            });
        }
    }

    results
}

/// Determine APOE genotype from rs429358 + rs7412 combination.
pub fn determine_apoe(genotypes: &HashMap<String, String>) -> ApoeResult {
    let gt1 = genotypes.get("rs429358").cloned().unwrap_or_default();
    let gt2 = genotypes.get("rs7412").cloned().unwrap_or_default();

    if gt1.is_empty() || gt2.is_empty() {
        return ApoeResult {
            genotype: "Unable to determine (missing data)".into(),
            rs429358: gt1,
            rs7412: gt2,
        };
    }

    // e4 alleles = count of 'C' at rs429358
    let e4 = gt1.chars().filter(|&c| c == 'C').count();
    // e2 alleles = count of 'T' at rs7412
    let e2 = gt2.chars().filter(|&c| c == 'T').count();

    let genotype = match (e4, e2) {
        (0, 0) => "e3/e3 (most common, baseline risk)".into(),
        (0, 1) => "e2/e3 (PROTECTIVE - reduced Alzheimer's risk)".into(),
        (0, 2) => "e2/e2 (protective; monitor for type III hyperlipoproteinemia)".into(),
        (1, 0) => "e3/e4 (increased Alzheimer's risk ~3x)".into(),
        (1, 1) => "e2/e4 (mixed - e2 partially offsets e4 risk)".into(),
        (2, _) => "e4/e4 (significantly increased Alzheimer's risk ~12x)".into(),
        _ => format!("Unusual combination: rs429358={}, rs7412={}", gt1, gt2),
    };

    ApoeResult {
        genotype,
        rs429358: gt1,
        rs7412: gt2,
    }
}

/// Analyze MTHFR compound status from C677T + A1298C.
pub fn analyze_mthfr(genotypes: &HashMap<String, String>) -> MthfrResult {
    let c677t = genotypes.get("rs1801133").cloned().unwrap_or_default();
    let a1298c = genotypes.get("rs1801131").cloned().unwrap_or_default();

    if c677t.is_empty() || a1298c.is_empty() {
        return MthfrResult {
            c677t,
            a1298c,
            score: 0,
            assessment: "Incomplete MTHFR data".into(),
        };
    }

    let c_risk = match c677t.as_str() {
        "GG" => 0u8,
        "AG" => 1,
        "AA" => 2,
        _ => 0,
    };
    let a_risk = match a1298c.as_str() {
        "TT" => 0u8,
        "GT" => 1,
        "GG" => 2,
        _ => 0,
    };
    let score = c_risk + a_risk;

    let assessment = match score {
        0 => "Normal MTHFR function. No supplementation needed.",
        1 => "Mildly reduced MTHFR. Consider methylfolate if homocysteine elevated.",
        2 => "Moderately reduced MTHFR. Methylfolate (L-5-MTHF) recommended.",
        3 => "Significantly reduced MTHFR (compound heterozygote). Methylfolate strongly recommended.",
        _ => "Severely reduced MTHFR. Methylfolate essential. Regular homocysteine monitoring.",
    };

    MthfrResult {
        c677t,
        a1298c,
        score,
        assessment: assessment.into(),
    }
}

/// Analyze pain sensitivity profile from COMT + OPRM1.
pub fn analyze_pain(genotypes: &HashMap<String, String>) -> Option<PainProfile> {
    let comt = genotypes.get("rs4680")?;
    let oprm1 = genotypes.get("rs1799971")?;

    let mut score = 0u8;
    if comt == "AA" {
        score += 2;
    } else if comt == "AG" {
        score += 1;
    }
    if oprm1 == "GG" {
        score += 2;
    } else if oprm1 == "AG" {
        score += 1;
    }

    let label = match score {
        0 => "Low",
        1 => "Low-Moderate",
        2 => "Moderate",
        3 => "Moderate-High",
        _ => "High",
    };

    let comt_note = if comt.contains('A') {
        "Higher pain sensitivity"
    } else {
        "Lower pain sensitivity"
    };
    let oprm1_note = if oprm1.contains('G') {
        "Reduced opioid response"
    } else {
        "Normal opioid response"
    };

    Some(PainProfile {
        comt: comt.clone(),
        oprm1: oprm1.clone(),
        score,
        label: label.into(),
        comt_note: comt_note.into(),
        oprm1_note: oprm1_note.into(),
    })
}

/// Category groupings for health variant display
pub fn variant_categories() -> Vec<(&'static str, Vec<&'static str>)> {
    vec![
        ("Cancer Risk", vec!["TP53", "BRCA1", "BRCA2", "NQO1"]),
        ("Cardiovascular", vec!["SLCO1B1"]),
        (
            "Neurological",
            vec!["APOE", "COMT", "OPRM1", "OXTR", "HTR2A", "ANKK1/DRD2"],
        ),
        ("Metabolism", vec!["MTHFR", "CYP1A2", "MCM6/LCT"]),
    ]
}

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

    fn make_map(pairs: &[(&str, &str)]) -> HashMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect()
    }

    #[test]
    fn test_apoe_e3e3() {
        let gts = make_map(&[("rs429358", "TT"), ("rs7412", "CC")]);
        let r = determine_apoe(&gts);
        assert!(r.genotype.contains("e3/e3"));
    }

    #[test]
    fn test_apoe_e2e3() {
        let gts = make_map(&[("rs429358", "TT"), ("rs7412", "CT")]);
        let r = determine_apoe(&gts);
        assert!(r.genotype.contains("e2/e3"));
    }

    #[test]
    fn test_apoe_e4e4() {
        let gts = make_map(&[("rs429358", "CC"), ("rs7412", "CC")]);
        let r = determine_apoe(&gts);
        assert!(r.genotype.contains("e4/e4"));
    }

    #[test]
    fn test_mthfr_normal() {
        let gts = make_map(&[("rs1801133", "GG"), ("rs1801131", "TT")]);
        let r = analyze_mthfr(&gts);
        assert_eq!(r.score, 0);
        assert!(r.assessment.contains("Normal"));
    }

    #[test]
    fn test_mthfr_compound() {
        let gts = make_map(&[("rs1801133", "AG"), ("rs1801131", "GG")]);
        let r = analyze_mthfr(&gts);
        assert_eq!(r.score, 3);
        assert!(r.assessment.contains("compound"));
    }

    #[test]
    fn test_pain_low() {
        let gts = make_map(&[("rs4680", "GG"), ("rs1799971", "AA")]);
        let p = analyze_pain(&gts).unwrap();
        assert_eq!(p.score, 0);
        assert_eq!(p.label, "Low");
    }

    #[test]
    fn test_pain_high() {
        let gts = make_map(&[("rs4680", "AA"), ("rs1799971", "GG")]);
        let p = analyze_pain(&gts).unwrap();
        assert_eq!(p.score, 4);
        assert_eq!(p.label, "High");
    }

    #[test]
    fn test_health_variants_lookup() {
        let gts = make_map(&[("rs762551", "AA"), ("rs4680", "AG")]);
        let results = analyze_health_variants(&gts);
        assert_eq!(results.len(), 2);
        assert_eq!(results[0].gene, "COMT");
        assert_eq!(results[1].gene, "CYP1A2");
    }
}