-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcomprehensive_analysis.py
More file actions
1563 lines (1273 loc) · 53.1 KB
/
Copy pathcomprehensive_analysis.py
File metadata and controls
1563 lines (1273 loc) · 53.1 KB
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
#!/usr/bin/env python3
"""
Comprehensive Genetic Analysis - 1600+ Markers (v4.3.0)
Full health, pharmacogenomics, ancestry, traits, and actionable recommendations.
Works with ANY ancestry/ethnic background worldwide.
Supports:
- 23andMe (v3, v4, v5)
- AncestryDNA
- MyHeritage
- FamilyTreeDNA
- Nebula Genomics
- VCF files (whole genome/exome)
Privacy: All analysis runs locally. Zero network requests.
Output:
- Human-readable reports
- Agent-friendly JSON with actionable fields and priorities
- Polygenic risk scores for major conditions
- Evidence-based recommendations with citations
- Lifestyle recommendation engine
- Drug interaction matrix
- Interactive HTML dashboard
Categories (21 total):
1. Pharmacogenomics - Drug metabolism
2. Polygenic Risk Scores - Disease risk
3. Carrier Status - Recessive carriers
4. Health Risks - Disease susceptibility
5. Traits - Physical/behavioral
6. Nutrition - Nutrigenomics
7. Fitness - Athletic performance
8. Neurogenetics - Cognition/behavior
9. Longevity - Aging markers
10. Immunity - HLA and immune
11. Rare Diseases - Rare genetic conditions
12. Mental Health - Psychiatric genetics
13. Dermatology - Skin and hair
14. Vision & Hearing - Sensory genetics
15. Fertility - Reproductive health
Example:
$ python comprehensive_analysis.py /path/to/dna_file.txt
Or as a library:
>>> from comprehensive_analysis import analyze_dna_file
>>> results = analyze_dna_file('/path/to/dna_file.txt')
"""
from __future__ import annotations
import sys
import json
import gzip
import math
import re
import logging
import shutil
import webbrowser
from pathlib import Path
from collections import defaultdict
from datetime import datetime
from typing import (
Dict, List, Optional, Any, Tuple, Union,
TypedDict, Sequence, Mapping
)
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(levelname)s: %(message)s'
)
logger = logging.getLogger(__name__)
# =============================================================================
# TYPE DEFINITIONS
# =============================================================================
class GenotypeData(TypedDict, total=False):
"""Type definition for genotype data."""
rsid: str
chromosome: str
position: int
genotype: str
class MarkerInfo(TypedDict, total=False):
"""Type definition for marker information."""
gene: str
risk_allele: str
effect_allele: str
variant: str
name: str
condition: str
conditions: List[str]
trait: str
effect: Union[str, Dict[str, str]]
note: str
evidence: str
actionable: Dict[str, Any]
class AnalysisResult(TypedDict, total=False):
"""Type definition for category analysis results."""
category: str
total_in_database: int
found_in_data: int
risk_variants: int
findings: List[Dict[str, Any]]
actionable_items: List[Dict[str, Any]]
class APOEResult(TypedDict):
"""Type definition for APOE analysis results."""
genotype: str
risk_level: str
rs429358: str
rs7412: str
interpretation: str
actionable: bool
recommendations: List[str]
class PRSResult(TypedDict, total=False):
"""Type definition for polygenic risk score results."""
raw_score: float
snps_found: int
snps_total: int
coverage: float
percentile_estimate: Optional[int]
confidence: str
# =============================================================================
# CONSTANTS
# =============================================================================
VERSION = "4.4.0"
OUTPUT_DIR = Path.home() / "dna-analysis" / "reports"
# Valid rsID pattern
RSID_PATTERN = re.compile(r'^rs\d+$', re.IGNORECASE)
# Valid genotype pattern (1-2 alleles)
GENOTYPE_PATTERN = re.compile(r'^[ACGT]{1,2}$|^[ACGTDI]{1,2}$|^--$|^00$|^\?$', re.IGNORECASE)
# =============================================================================
# MODULE IMPORTS (with graceful fallback)
# =============================================================================
MODULES_LOADED = False
try:
from markers.pharmacogenomics import PHARMACOGENOMICS_MARKERS, DRUG_INTERACTIONS
from markers.polygenic_scores import PRS_WEIGHTS, PRS_CONDITIONS, calculate_prs
from markers.carrier_status import CARRIER_MARKERS, CARRIER_SCREENING_PANELS
from markers.health_risks import HEALTH_RISK_MARKERS
from markers.traits import TRAIT_MARKERS
from markers.nutrition import NUTRITION_MARKERS
from markers.fitness import FITNESS_MARKERS
from markers.neurogenetics import NEURO_MARKERS
from markers.longevity import LONGEVITY_MARKERS
from markers.immunity import IMMUNITY_MARKERS, HLA_DRUG_ALERTS
from markers.rare_diseases import RARE_DISEASE_MARKERS
from markers.mental_health import MENTAL_HEALTH_MARKERS
from markers.dermatology import DERMATOLOGY_MARKERS
from markers.vision_hearing import VISION_HEARING_MARKERS
from markers.fertility import FERTILITY_MARKERS
from markers.haplogroups import analyze_haplogroups
from markers.ancestry_composition import get_ancestry_summary
from markers.population_comparison import get_population_comparison_json
from markers.ancient_ancestry import get_ancient_dna_json, get_neanderthal_report
from markers.ancient_matching import get_ancient_matches_json, analyze_ancient_ancestry
from markers import get_marker_counts
MODULES_LOADED = True
except ImportError as e:
logger.warning(f"Could not load marker modules: {e}")
logger.warning("Using inline markers only.")
PHARMACOGENOMICS_MARKERS: Dict[str, MarkerInfo] = {}
DRUG_INTERACTIONS: Dict[str, Any] = {}
PRS_WEIGHTS: Dict[str, Any] = {}
PRS_CONDITIONS: Dict[str, Any] = {}
CARRIER_MARKERS: Dict[str, MarkerInfo] = {}
HEALTH_RISK_MARKERS: Dict[str, MarkerInfo] = {}
TRAIT_MARKERS: Dict[str, MarkerInfo] = {}
NUTRITION_MARKERS: Dict[str, MarkerInfo] = {}
FITNESS_MARKERS: Dict[str, MarkerInfo] = {}
NEURO_MARKERS: Dict[str, MarkerInfo] = {}
LONGEVITY_MARKERS: Dict[str, MarkerInfo] = {}
IMMUNITY_MARKERS: Dict[str, MarkerInfo] = {}
HLA_DRUG_ALERTS: Dict[str, Any] = {}
RARE_DISEASE_MARKERS: Dict[str, MarkerInfo] = {}
MENTAL_HEALTH_MARKERS: Dict[str, MarkerInfo] = {}
DERMATOLOGY_MARKERS: Dict[str, MarkerInfo] = {}
VISION_HEARING_MARKERS: Dict[str, MarkerInfo] = {}
FERTILITY_MARKERS: Dict[str, MarkerInfo] = {}
CARRIER_SCREENING_PANELS: Dict[str, Any] = {}
def get_marker_counts() -> Dict[str, int]:
return {"total": 0}
# =============================================================================
# INPUT VALIDATION
# =============================================================================
def validate_rsid(rsid: str) -> bool:
"""
Validate rsID format.
Args:
rsid: The rsID string to validate.
Returns:
True if valid rsID format, False otherwise.
Examples:
>>> validate_rsid("rs123456")
True
>>> validate_rsid("invalid")
False
"""
if not rsid or not isinstance(rsid, str):
return False
return bool(RSID_PATTERN.match(rsid))
def validate_genotype(genotype: str) -> bool:
"""
Validate genotype format.
Args:
genotype: The genotype string to validate.
Returns:
True if valid genotype format, False otherwise.
Examples:
>>> validate_genotype("AG")
True
>>> validate_genotype("XYZ")
False
"""
if not genotype or not isinstance(genotype, str):
return False
return bool(GENOTYPE_PATTERN.match(genotype))
def validate_filepath(filepath: Union[str, Path]) -> Path:
"""
Validate and resolve filepath.
Args:
filepath: Path to the file.
Returns:
Resolved Path object.
Raises:
FileNotFoundError: If file doesn't exist.
ValueError: If path is invalid.
"""
if not filepath:
raise ValueError("Filepath cannot be empty")
path = Path(filepath).expanduser().resolve()
if not path.exists():
raise FileNotFoundError(f"File not found: {path}")
if not path.is_file():
raise ValueError(f"Path is not a file: {path}")
return path
def sanitize_genotype(genotype: str) -> str:
"""
Sanitize and normalize genotype string.
Args:
genotype: Raw genotype string.
Returns:
Cleaned genotype string, or empty string if invalid.
Examples:
>>> sanitize_genotype(" AG ")
'AG'
>>> sanitize_genotype("--")
''
"""
if not genotype:
return ""
cleaned = genotype.strip().upper().replace(' ', '')
# Handle no-call values
if cleaned in ('--', '00', 'NC', 'N/A', '.', '?'):
return ""
# Normalize indels
if 'D' in cleaned or 'I' in cleaned:
return cleaned
# Filter to valid nucleotides only
valid_chars = set('ACGT')
filtered = ''.join(c for c in cleaned if c in valid_chars)
return filtered if len(filtered) in (1, 2) else ""
# =============================================================================
# FILE FORMAT DETECTION AND LOADING
# =============================================================================
def detect_format(filepath: Union[str, Path]) -> str:
"""
Detect DNA file format from file contents.
Args:
filepath: Path to the DNA data file.
Returns:
Format string: 'vcf', '23andme', 'ancestry', 'myheritage', 'ftdna', or 'generic'.
Raises:
IOError: If file cannot be read.
"""
filepath = str(filepath)
if filepath.endswith('.vcf') or filepath.endswith('.vcf.gz'):
return 'vcf'
# Determine opener based on compression
opener = gzip.open if filepath.endswith('.gz') else open
mode = 'rt' if filepath.endswith('.gz') else 'r'
try:
with opener(filepath, mode, encoding='utf-8', errors='replace') as f:
header_lines = []
for i, line in enumerate(f):
if i >= 20:
break
header_lines.append(line)
except IOError as e:
logger.error(f"Error reading file header: {e}")
raise
content = ''.join(header_lines).lower()
if '23andme' in content:
return '23andme'
elif 'ancestrydna' in content:
return 'ancestry'
elif 'myheritage' in content:
return 'myheritage'
elif 'ftdna' in content or 'family tree dna' in content:
return 'ftdna'
elif '#rsid' in content or 'rsid\t' in content:
return 'generic'
else:
return 'generic'
def load_vcf(filepath: Union[str, Path]) -> Dict[str, str]:
"""
Load VCF file into rsid -> genotype dictionary.
Args:
filepath: Path to VCF file (.vcf or .vcf.gz).
Returns:
Dictionary mapping rsIDs to genotype strings.
Raises:
IOError: If file cannot be read.
ValueError: If file format is invalid.
"""
genotypes: Dict[str, str] = {}
filepath_str = str(filepath)
opener = gzip.open if filepath_str.endswith('.gz') else open
mode = 'rt' if filepath_str.endswith('.gz') else 'r'
line_count = 0
error_count = 0
try:
with opener(filepath_str, mode, encoding='utf-8', errors='replace') as f:
for line in f:
line_count += 1
if line.startswith('#'):
continue
parts = line.strip().split('\t')
if len(parts) < 10:
continue
try:
chrom, pos, rsid, ref, alt, qual, filt, info, fmt, sample = parts[:10]
if not validate_rsid(rsid):
continue
# Parse genotype
fmt_fields = fmt.split(':')
sample_fields = sample.split(':')
gt_idx = fmt_fields.index('GT') if 'GT' in fmt_fields else 0
gt = sample_fields[gt_idx] if gt_idx < len(sample_fields) else './.'
# Convert GT to alleles
alleles = [ref] + alt.split(',')
gt_parts = gt.replace('|', '/').split('/')
a1 = alleles[int(gt_parts[0])] if gt_parts[0] not in ('.', '') else '?'
a2 = alleles[int(gt_parts[1])] if len(gt_parts) > 1 and gt_parts[1] not in ('.', '') else a1
geno = sanitize_genotype(a1 + a2)
if geno:
genotypes[rsid] = geno
except (ValueError, IndexError) as e:
error_count += 1
if error_count <= 5:
logger.debug(f"Line {line_count}: Parse error - {e}")
continue
except IOError as e:
logger.error(f"Error reading VCF file: {e}")
raise
if error_count > 5:
logger.warning(f"Skipped {error_count} lines with parse errors")
logger.info(f"Loaded {len(genotypes):,} variants from VCF")
return genotypes
def load_consumer_format(filepath: Union[str, Path]) -> Dict[str, str]:
"""
Load consumer DNA format (23andMe, Ancestry, etc.) into dictionary.
Args:
filepath: Path to DNA data file.
Returns:
Dictionary mapping rsIDs to genotype strings.
Raises:
IOError: If file cannot be read.
"""
genotypes: Dict[str, str] = {}
filepath_str = str(filepath)
opener = gzip.open if filepath_str.endswith('.gz') else open
mode = 'rt' if filepath_str.endswith('.gz') else 'r'
line_count = 0
error_count = 0
try:
with opener(filepath_str, mode, encoding='utf-8', errors='replace') as f:
for line in f:
line_count += 1
# Skip comments and empty lines
if line.startswith('#') or not line.strip():
continue
# Try tab-separated first, then comma
parts = line.strip().split('\t')
if len(parts) < 4:
parts = line.strip().split(',')
if len(parts) >= 4:
rsid = parts[0].strip()
if not validate_rsid(rsid):
continue
# Format varies:
# 4 columns: rsid, chrom, pos, genotype (23andMe)
# 5 columns: rsid, chrom, pos, allele1, allele2 (Ancestry)
if len(parts) >= 5:
# Ancestry format: combine allele1 + allele2
raw_genotype = parts[3].strip() + parts[4].strip()
else:
# 23andMe format: genotype in column 4
raw_genotype = parts[3].strip()
genotype = sanitize_genotype(raw_genotype)
if genotype:
genotypes[rsid] = genotype
elif len(parts) >= 2:
# Alternative format: rsid, genotype
rsid = parts[0].strip()
if validate_rsid(rsid):
genotype = sanitize_genotype(parts[1])
if genotype:
genotypes[rsid] = genotype
except IOError as e:
logger.error(f"Error reading DNA file: {e}")
raise
if error_count > 0:
logger.warning(f"Skipped {error_count} lines with parse errors")
logger.info(f"Loaded {len(genotypes):,} SNPs from consumer format")
return genotypes
def load_dna_file(filepath: Union[str, Path]) -> Tuple[Dict[str, str], str]:
"""
Load DNA data from any supported format.
Args:
filepath: Path to DNA data file.
Returns:
Tuple of (genotypes dict, format string).
Raises:
FileNotFoundError: If file doesn't exist.
ValueError: If file format is unsupported or data is empty.
Examples:
>>> genotypes, fmt = load_dna_file("~/dna_data.txt")
>>> print(f"Loaded {len(genotypes)} SNPs in {fmt} format")
"""
path = validate_filepath(filepath)
fmt = detect_format(path)
logger.info(f"Detected format: {fmt}")
if fmt == 'vcf':
genotypes = load_vcf(path)
else:
genotypes = load_consumer_format(path)
if not genotypes:
raise ValueError(
f"No valid genotypes found in file. "
f"Please check file format and content."
)
return genotypes, fmt
# =============================================================================
# APOE DETERMINATION
# =============================================================================
def determine_apoe(genotypes: Dict[str, str]) -> APOEResult:
"""
Determine APOE genotype from rs429358 and rs7412.
APOE alleles:
- ε2: rs429358=T, rs7412=T
- ε3: rs429358=T, rs7412=C
- ε4: rs429358=C, rs7412=C
Args:
genotypes: Dictionary mapping rsIDs to genotype strings.
Returns:
APOEResult with genotype, risk level, interpretation, and recommendations.
Examples:
>>> result = determine_apoe({"rs429358": "TT", "rs7412": "CC"})
>>> print(result["genotype"]) # "ε3/ε3"
"""
rs429358 = genotypes.get('rs429358', '')
rs7412 = genotypes.get('rs7412', '')
# Default unknown result
unknown_result: APOEResult = {
"genotype": "unknown",
"risk_level": "unknown",
"rs429358": rs429358,
"rs7412": rs7412,
"interpretation": "Unable to determine APOE status - missing marker data",
"actionable": False,
"recommendations": []
}
if not rs429358 or not rs7412:
return unknown_result
# Determine alleles
alleles: List[str] = []
for i in range(min(len(rs429358), len(rs7412))):
c1 = rs429358[i].upper()
c2 = rs7412[i].upper()
if c1 == 'T' and c2 == 'T':
alleles.append('ε2')
elif c1 == 'T' and c2 == 'C':
alleles.append('ε3')
elif c1 == 'C' and c2 == 'C':
alleles.append('ε4')
if len(alleles) == 2:
genotype = '/'.join(sorted(alleles))
elif len(alleles) == 1:
genotype = alleles[0] + '/' + alleles[0]
else:
return unknown_result
# Risk information
risk_info: Dict[str, Tuple[str, str]] = {
'ε2/ε2': ('low', 'Protective. Lower Alzheimer\'s risk, but higher triglycerides.'),
'ε2/ε3': ('low', 'Below average Alzheimer\'s risk.'),
'ε3/ε3': ('average', 'Most common genotype. Average risk.'),
'ε2/ε4': ('moderate', 'Mixed effects. ε2 partially offsets ε4.'),
'ε3/ε4': ('elevated', '~3x Alzheimer\'s risk vs ε3/ε3. Lifestyle modifications important.'),
'ε4/ε4': ('high', '~12x Alzheimer\'s risk. Exercise, diet, sleep, and cognitive engagement are protective.')
}
risk_level, interpretation = risk_info.get(genotype, ('unknown', 'Unable to interpret'))
is_actionable = risk_level in ('elevated', 'high')
recommendations: List[str] = []
if is_actionable:
recommendations = [
"Regular aerobic exercise (strongest protective factor)",
"Mediterranean diet",
"7-8 hours quality sleep",
"Cognitive engagement and social connection",
"Cardiovascular risk factor management"
]
return {
"genotype": genotype,
"risk_level": risk_level,
"rs429358": rs429358,
"rs7412": rs7412,
"interpretation": interpretation,
"actionable": is_actionable,
"recommendations": recommendations
}
# =============================================================================
# ANALYSIS FUNCTIONS
# =============================================================================
def analyze_markers(
genotypes: Dict[str, str],
markers: Dict[str, MarkerInfo],
category: str
) -> AnalysisResult:
"""
Analyze a category of genetic markers.
Args:
genotypes: Dictionary mapping rsIDs to genotype strings.
markers: Dictionary of marker definitions for this category.
category: Name of the marker category.
Returns:
AnalysisResult with findings and actionable items.
Examples:
>>> result = analyze_markers(genotypes, TRAIT_MARKERS, "traits")
>>> print(f"Found {result['found_in_data']} markers")
"""
if not isinstance(genotypes, dict):
logger.error(f"Invalid genotypes type: {type(genotypes)}")
return {
"category": category,
"total_in_database": 0,
"found_in_data": 0,
"risk_variants": 0,
"findings": [],
"actionable_items": []
}
if not isinstance(markers, dict):
logger.warning(f"Invalid markers dict for {category}")
markers = {}
results: AnalysisResult = {
"category": category,
"total_in_database": len(markers),
"found_in_data": 0,
"risk_variants": 0,
"findings": [],
"actionable_items": []
}
for rsid, info in markers.items():
if not validate_rsid(rsid):
continue
geno = genotypes.get(rsid)
if not geno:
continue
results["found_in_data"] += 1
# Determine if risk allele present
risk_allele = info.get('risk_allele') or info.get('effect_allele', '')
risk_count = 0
if risk_allele:
risk_count = geno.upper().count(risk_allele.upper())
finding: Dict[str, Any] = {
"rsid": rsid,
"gene": info.get('gene', 'Unknown'),
"genotype": geno,
"risk_allele": risk_allele,
"risk_copies": risk_count,
"is_risk": risk_count > 0
}
# Add variant-specific info
for key in ['variant', 'name', 'condition', 'conditions', 'trait', 'effect', 'note', 'evidence']:
if key in info:
finding[key] = info[key]
if risk_count > 0:
results["risk_variants"] += 1
# Check for actionable items
if 'actionable' in info and isinstance(info['actionable'], dict):
action = {
"rsid": rsid,
"gene": info.get('gene'),
"genotype": geno,
**info['actionable']
}
results["actionable_items"].append(action)
results["findings"].append(finding)
return results
def calculate_all_prs(genotypes: Dict[str, str]) -> Dict[str, PRSResult]:
"""
Calculate polygenic risk scores for all conditions.
Args:
genotypes: Dictionary mapping rsIDs to genotype strings.
Returns:
Dictionary mapping condition names to PRSResult.
Examples:
>>> prs = calculate_all_prs(genotypes)
>>> print(prs["type_2_diabetes"]["percentile_estimate"])
"""
if not PRS_WEIGHTS:
return {"error": {"raw_score": 0, "snps_found": 0, "snps_total": 0, "coverage": 0, "confidence": "none"}}
scores: Dict[str, PRSResult] = {}
conditions = set(v.get('condition', '') for v in PRS_WEIGHTS.values() if 'condition' in v)
for condition in conditions:
if not condition:
continue
condition_snps = {k: v for k, v in PRS_WEIGHTS.items() if v.get('condition') == condition}
score = 0.0
found = 0
for rsid, info in condition_snps.items():
geno = genotypes.get(rsid)
if geno:
found += 1
effect_allele = info.get('effect', '')
beta = info.get('beta', 0)
if effect_allele:
effect_count = geno.upper().count(effect_allele.upper())
score += effect_count * beta
percentile: Optional[int] = None
if found > 5:
# Rough percentile estimation using z-score approximation
z = score / math.sqrt(found * 0.5) if found > 0 else 0
percentile = min(99, max(1, int(50 + z * 15)))
coverage = round(found / len(condition_snps), 2) if condition_snps else 0
confidence = "moderate" if found > len(condition_snps) * 0.5 else "low"
scores[condition] = {
"raw_score": round(score, 3),
"snps_found": found,
"snps_total": len(condition_snps),
"coverage": coverage,
"percentile_estimate": percentile,
"confidence": confidence
}
return scores
# =============================================================================
# AGENT-FRIENDLY OUTPUT
# =============================================================================
def generate_agent_summary(all_results: Dict[str, Any]) -> Dict[str, Any]:
"""
Generate structured output optimized for AI agents.
Args:
all_results: Complete analysis results dictionary.
Returns:
Dictionary with priority-sorted actionable items and key findings.
Examples:
>>> summary = generate_agent_summary(all_results)
>>> print(len(summary["critical_alerts"]))
"""
summary: Dict[str, Any] = {
"analysis_timestamp": datetime.now().isoformat(),
"version": VERSION,
"snps_analyzed": all_results.get("total_snps", 0),
"format_detected": all_results.get("format", "unknown"),
# Priority-sorted actionable items
"critical_alerts": [],
"high_priority": [],
"medium_priority": [],
"low_priority": [],
"informational": [],
# Key health markers
"apoe_status": all_results.get("apoe", {}),
"pharmacogenomics_alerts": [],
"carrier_status": [],
"polygenic_risk_scores": all_results.get("prs", {}),
# Traits and lifestyle
"notable_traits": [],
"nutrition_insights": [],
"fitness_insights": [],
# Lifestyle recommendations
"lifestyle_recommendations": all_results.get("lifestyle_recommendations", {}),
"drug_interaction_matrix": all_results.get("drug_interaction_matrix", {}),
# Metadata
"confidence_notes": [
"Consumer arrays capture ~0.1% of genome",
"Polygenic scores are probabilistic, not deterministic",
"Many conditions depend heavily on environment and lifestyle",
"These results are not diagnostic - consult healthcare providers"
]
}
# Collect all actionable items and sort by priority
for category, results in all_results.items():
if isinstance(results, dict) and "actionable_items" in results:
for item in results["actionable_items"]:
priority = item.get("priority", "informational")
if priority == "critical":
summary["critical_alerts"].append(item)
elif priority == "high":
summary["high_priority"].append(item)
elif priority == "medium":
summary["medium_priority"].append(item)
elif priority == "low":
summary["low_priority"].append(item)
else:
summary["informational"].append(item)
# Also add to specific categories
if category == "pharmacogenomics":
summary["pharmacogenomics_alerts"].append(item)
elif category == "carrier_status":
summary["carrier_status"].append(item)
# Add notable traits
if "traits" in all_results and isinstance(all_results["traits"], dict):
for finding in all_results["traits"].get("findings", [])[:20]:
if finding.get("effect"):
summary["notable_traits"].append({
"trait": finding.get("trait") or finding.get("name"),
"gene": finding.get("gene"),
"genotype": finding.get("genotype"),
"interpretation": finding.get("effect")
})
# Add haplogroups (with LOW CONFIDENCE disclaimer)
haplogroups_data = all_results.get("haplogroups", {})
if haplogroups_data:
summary["haplogroups"] = {
"disclaimer": haplogroups_data.get("disclaimer", "Consumer arrays cannot reliably determine haplogroups"),
"mtDNA": haplogroups_data.get("mtDNA", {}),
"Y_DNA": haplogroups_data.get("Y_DNA", {}),
"methodology": haplogroups_data.get("methodology", {})
}
# Add ancestry (ancient ancestral signals, not modern ethnicity)
ancestry_data = all_results.get("ancestry", {})
if ancestry_data:
summary["ancestry"] = {
"analysis_type": "ancient_ancestral_signals",
"disclaimer": ancestry_data.get("disclaimer",
"Detects signals from ancient populations, not modern ethnicity percentages"),
"signals": ancestry_data.get("signals", {}),
"educational_note": ancestry_data.get("educational_note", ""),
"summary": ancestry_data.get("summary", "")
}
# Add population comparison (1000 Genomes)
pop_comparison = all_results.get("population_comparison", {})
if pop_comparison:
summary["population_comparison"] = {
"most_similar_populations": pop_comparison.get("most_similar_populations", []),
"superpopulation_summary": pop_comparison.get("superpopulation_summary", {}),
"marker_details": pop_comparison.get("marker_details", []),
"total_markers": pop_comparison.get("total_markers", 0),
"methodology": pop_comparison.get("methodology", {})
}
# Add ancient DNA data
ancient_dna = all_results.get("ancient_dna", {})
if ancient_dna:
summary["ancient_dna"] = ancient_dna
# Add Neanderthal analysis
neanderthal = all_results.get("neanderthal", {})
if neanderthal:
summary["neanderthal"] = neanderthal
# Add Ancient Individual Matches (YourTrueAncestry clone)
ancient_matches = all_results.get("ancient_matches", {})
if ancient_matches:
summary["ancient_matches"] = {
"top_matches": ancient_matches.get("top_matches", [])[:5],
"culture_affinities": ancient_matches.get("culture_affinities", [])[:8],
"statistics": ancient_matches.get("statistics", {}),
"methodology": ancient_matches.get("methodology", {})
}
return summary
# =============================================================================
# HUMAN-READABLE REPORT
# =============================================================================
def generate_report(all_results: Dict[str, Any], agent_summary: Dict[str, Any]) -> str:
"""
Generate human-readable text report.
Args:
all_results: Complete analysis results.
agent_summary: Agent-optimized summary.
Returns:
Formatted text report string.
"""
lines: List[str] = []
lines.append("=" * 78)
lines.append("COMPREHENSIVE GENETIC ANALYSIS REPORT")
lines.append(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
lines.append(f"Version: {VERSION}")
lines.append("=" * 78)
lines.append("")
lines.append("IMPORTANT DISCLAIMERS:")
lines.append(" * This is NOT medical advice")
lines.append(" * Consult healthcare providers before acting on results")
lines.append(" * Genetic risk does not equal destiny - lifestyle matters enormously")
lines.append(" * Consumer arrays miss rare variants and structural changes")
lines.append("")
# Summary stats
lines.append("-" * 78)
lines.append("SUMMARY")
lines.append("-" * 78)
lines.append(f"SNPs in file: {all_results.get('total_snps', 'N/A'):,}")
lines.append(f"File format: {all_results.get('format', 'Unknown')}")
lines.append(f"Critical alerts: {len(agent_summary.get('critical_alerts', []))}")
lines.append(f"High priority items: {len(agent_summary.get('high_priority', []))}")
lines.append("")
# APOE
apoe = all_results.get("apoe", {})
if apoe.get("genotype") != "unknown":
lines.append("-" * 78)
lines.append("APOE STATUS (Alzheimer's / Cardiovascular)")
lines.append("-" * 78)
lines.append(f"Genotype: {apoe.get('genotype')}")
lines.append(f"Risk level: {apoe.get('risk_level')}")
lines.append(f"Interpretation: {apoe.get('interpretation')}")
if apoe.get("recommendations"):