-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1047 lines (849 loc) · 43.2 KB
/
Copy pathapp.py
File metadata and controls
1047 lines (849 loc) · 43.2 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
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import io
import re
from datetime import datetime, timedelta
import json
from typing import Dict, List, Tuple
import hashlib
# Configure page
st.set_page_config(
page_title="💖 EternaHeart - DNA-to-Destiny Health Platform",
page_icon="💖",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS
st.markdown("""
<style>
.main-header {
background: linear-gradient(90deg, #FF6B6B 0%, #4ECDC4 50%, #45B7D1 100%);
padding: 2rem;
border-radius: 10px;
text-align: center;
margin-bottom: 2rem;
}
.metric-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 1.5rem;
border-radius: 10px;
color: white;
text-align: center;
margin: 1rem 0;
}
.risk-low { border-left: 5px solid #28a745; }
.risk-medium { border-left: 5px solid #ffc107; }
.risk-high { border-left: 5px solid #dc3545; }
.dna-sequence {
font-family: 'Courier New', monospace;
background: #1e1e1e;
color: #00ff00;
padding: 1rem;
border-radius: 5px;
font-size: 12px;
}
</style>
""", unsafe_allow_html=True)
class GenomicAnalyzer:
"""Advanced genomic analysis engine"""
def __init__(self):
# Simulated heart-related genes database
self.heart_genes = {
'APOE': {'variants': ['e2', 'e3', 'e4'], 'cardiac_risk': [0.8, 1.0, 1.3]},
'LDLR': {'variants': ['normal', 'variant'], 'cardiac_risk': [1.0, 2.1]},
'PCSK9': {'variants': ['normal', 'LOF'], 'cardiac_risk': [1.0, 0.6]},
'ABCA1': {'variants': ['normal', 'variant'], 'cardiac_risk': [1.0, 1.4]},
'CYP2D6': {'variants': ['normal', 'poor'], 'cardiac_risk': [1.0, 1.2]},
'FOXO3': {'variants': ['normal', 'longevity'], 'cardiac_risk': [1.0, 0.7]}
}
def parse_genomic_file(self, file_content: str, file_type: str) -> Dict:
"""Parse uploaded genomic files"""
results = {
'total_variants': 0,
'heart_genes_found': [],
'protective_alleles': [],
'risk_variants': [],
'quality_score': 0
}
if file_type == "VCF":
# Simulate VCF parsing
lines = file_content.split('\n')
variants_found = len([l for l in lines if not l.startswith('#') and l.strip()])
results['total_variants'] = variants_found
results['quality_score'] = min(95, variants_found / 1000 * 100)
elif file_type == "FASTA":
# Simulate FASTA sequence analysis
sequence_length = len(re.sub(r'[^ATCG]', '', file_content.upper()))
results['total_variants'] = sequence_length // 1000
results['quality_score'] = 85
# Simulate finding heart-related genes
for gene in ['APOE', 'LDLR', 'PCSK9', 'FOXO3']:
if gene.lower() in file_content.lower() or np.random.random() > 0.3:
variant = np.random.choice(self.heart_genes[gene]['variants'])
risk_factor = self.heart_genes[gene]['cardiac_risk'][
self.heart_genes[gene]['variants'].index(variant)
]
gene_data = {
'gene': gene,
'variant': variant,
'risk_factor': risk_factor,
'confidence': np.random.uniform(0.85, 0.99)
}
results['heart_genes_found'].append(gene_data)
if risk_factor < 1.0:
results['protective_alleles'].append(gene_data)
elif risk_factor > 1.2:
results['risk_variants'].append(gene_data)
return results
def calculate_genetic_risk_score(self, genomic_data: Dict) -> float:
"""Calculate comprehensive genetic heart risk score"""
base_risk = 1.0
for gene_data in genomic_data['heart_genes_found']:
weight = gene_data['confidence']
base_risk *= (gene_data['risk_factor'] ** weight)
# Normalize to 0-100 scale
genetic_risk_score = (base_risk - 0.5) * 50
return max(0, min(100, genetic_risk_score))
class BiomarkerAnalyzer:
"""Advanced biomarker interpretation system"""
def analyze_biomarkers(self, df: pd.DataFrame) -> Dict:
"""Comprehensive biomarker analysis"""
results = {
'metabolic_age': 0,
'cardiac_age': 0,
'inflammation_score': 0,
'longevity_score': 0,
'risk_factors': [],
'protective_factors': []
}
# Calculate metabolic age
glucose = df.get('glucose', pd.Series([90])).iloc[0] if 'glucose' in df else 90
insulin = df.get('insulin', pd.Series([10])).iloc[0] if 'insulin' in df else 10
hba1c = df.get('hba1c', pd.Series([5.2])).iloc[0] if 'hba1c' in df else 5.2
metabolic_score = (glucose - 80) * 0.5 + (insulin - 8) * 2 + (hba1c - 5.0) * 10
results['metabolic_age'] = max(20, min(80, 30 + metabolic_score))
# Calculate cardiac age
ldl = df.get('ldl', pd.Series([120])).iloc[0] if 'ldl' in df else 120
hdl = df.get('hdl', pd.Series([50])).iloc[0] if 'hdl' in df else 50
triglycerides = df.get('triglycerides', pd.Series([150])).iloc[0] if 'triglycerides' in df else 150
systolic_bp = df.get('systolic_bp', pd.Series([120])).iloc[0] if 'systolic_bp' in df else 120
cardiac_score = (ldl - 100) * 0.3 + (150 - hdl) * 0.2 + (triglycerides - 100) * 0.1 + (systolic_bp - 110) * 0.4
results['cardiac_age'] = max(20, min(80, 35 + cardiac_score * 0.5))
# Inflammation score
crp = df.get('crp', pd.Series([1.0])).iloc[0] if 'crp' in df else 1.0
results['inflammation_score'] = min(100, crp * 33.3)
# Longevity score (inverse of risk factors)
longevity_factors = []
if hdl > 60: longevity_factors.append(10)
if ldl < 100: longevity_factors.append(15)
if crp < 1.0: longevity_factors.append(20)
if systolic_bp < 120: longevity_factors.append(15)
results['longevity_score'] = sum(longevity_factors)
return results
class DigitalHeartTwin:
"""Revolutionary digital heart simulation engine"""
def create_heart_model(self, genetic_risk: float, biomarker_data: Dict, current_age: int) -> Dict:
"""Create personalized digital heart twin"""
# Base heart age calculation
base_heart_age = current_age
genetic_modifier = (genetic_risk - 50) * 0.3
biomarker_modifier = (biomarker_data['cardiac_age'] - current_age)
current_heart_age = base_heart_age + genetic_modifier + biomarker_modifier
# Simulate aging curve
ages = list(range(current_age, min(120, current_age + 60), 5))
# Current trajectory (no intervention)
current_trajectory = []
deterioration_rate = 1 + (genetic_risk / 100) * 0.02 + (biomarker_data['inflammation_score'] / 100) * 0.01
for age in ages:
years_ahead = age - current_age
projected_heart_age = current_heart_age + (years_ahead * deterioration_rate)
current_trajectory.append({
'age': age,
'heart_age': projected_heart_age,
'risk_level': min(100, (projected_heart_age - age) * 2)
})
# Optimized trajectory (with interventions)
optimized_trajectory = []
improvement_rate = 0.7 # 30% improvement with interventions
for age in ages:
years_ahead = age - current_age
optimized_heart_age = current_heart_age + (years_ahead * deterioration_rate * improvement_rate)
optimized_trajectory.append({
'age': age,
'heart_age': optimized_heart_age,
'risk_level': min(100, max(0, (optimized_heart_age - age) * 2))
})
return {
'current_heart_age': current_heart_age,
'current_trajectory': current_trajectory,
'optimized_trajectory': optimized_trajectory,
'potential_years_gained': (current_trajectory[-1]['heart_age'] - optimized_trajectory[-1]['heart_age']) / deterioration_rate
}
class InterventionEngine:
"""Personalized intervention recommendation system"""
def generate_interventions(self, genetic_data: Dict, biomarker_data: Dict) -> Dict:
"""Generate personalized intervention plan"""
interventions = {
'nutrition': [],
'exercise': [],
'supplements': [],
'lifestyle': [],
'monitoring': []
}
# Genetic-based interventions
for gene_info in genetic_data.get('heart_genes_found', []):
gene = gene_info['gene']
if gene == 'APOE' and gene_info['variant'] == 'e4':
interventions['nutrition'].append("Reduce saturated fat to <7% of calories")
interventions['supplements'].append("Omega-3 EPA/DHA 2000mg daily")
elif gene == 'LDLR' and gene_info['risk_factor'] > 1.5:
interventions['nutrition'].append("Plant sterol supplements 2g daily")
interventions['monitoring'].append("Monthly lipid panels")
elif gene == 'FOXO3' and gene_info['variant'] == 'longevity':
interventions['lifestyle'].append("Intermittent fasting 16:8 protocol")
interventions['exercise'].append("High-intensity interval training 3x/week")
# Biomarker-based interventions
if biomarker_data.get('inflammation_score', 0) > 50:
interventions['nutrition'].append("Anti-inflammatory Mediterranean diet")
interventions['supplements'].append("Curcumin 500mg daily")
if biomarker_data.get('cardiac_age', 30) > biomarker_data.get('metabolic_age', 30):
interventions['exercise'].append("Moderate cardio 150 minutes/week")
interventions['supplements'].append("CoQ10 100mg daily")
# Universal longevity interventions
interventions['lifestyle'].extend([
"Sleep optimization: 7-9 hours nightly",
"Stress management: Daily meditation 20 minutes",
"Cold exposure therapy 2x/week"
])
return interventions
def main():
# App header
st.markdown("""
<div class="main-header">
<h1>💖 EternaHeart</h1>
<h3>Revolutionary DNA-to-Destiny Health Platform</h3>
<p>Upload your genome + biomarkers → Get your complete longevity blueprint</p>
</div>
""", unsafe_allow_html=True)
# Initialize session state
if 'analysis_complete' not in st.session_state:
st.session_state.analysis_complete = False
# Sidebar navigation
st.sidebar.title("🧭 Navigation")
tab = st.sidebar.radio("Select Module", [
"🏠 Home",
"🧬 Genomic Upload",
"📊 Biomarker Input",
"🔬 AI Analysis",
"🫀 Digital Heart Twin",
"💊 Interventions",
"📈 Future Predictions"
])
if tab == "🏠 Home":
col1, col2, col3 = st.columns(3)
with col1:
st.markdown("""
<div class="metric-card">
<h3>🧬 Genomic Analysis</h3>
<p>Deep dive into your DNA for heart disease risk factors and protective variants</p>
</div>
""", unsafe_allow_html=True)
with col2:
st.markdown("""
<div class="metric-card">
<h3>🩺 Biomarker Intelligence</h3>
<p>AI interpretation of blood work, vitals, and metabolic markers</p>
</div>
""", unsafe_allow_html=True)
with col3:
st.markdown("""
<div class="metric-card">
<h3>🔮 Future Simulation</h3>
<p>Predict your health trajectory and optimize for longevity</p>
</div>
""", unsafe_allow_html=True)
st.markdown("---")
# Sample data demo
if st.button("🚀 Try Demo with Sample Data"):
# Generate sample genomic data
sample_genomic = {
'total_variants': 4500000,
'heart_genes_found': [
{'gene': 'APOE', 'variant': 'e3/e4', 'risk_factor': 1.2, 'confidence': 0.95},
{'gene': 'LDLR', 'variant': 'normal', 'risk_factor': 1.0, 'confidence': 0.88},
{'gene': 'FOXO3', 'variant': 'longevity', 'risk_factor': 0.8, 'confidence': 0.92}
],
'quality_score': 92
}
# Generate sample biomarker data
sample_biomarkers = {
'metabolic_age': 38,
'cardiac_age': 42,
'inflammation_score': 35,
'longevity_score': 65
}
st.session_state.genomic_data = sample_genomic
st.session_state.biomarker_data = sample_biomarkers
st.session_state.analysis_complete = True
st.success("Demo data loaded! Navigate to other tabs to explore.")
elif tab == "🧬 Genomic Upload":
st.header("🧬 Genomic Data Analysis")
st.write("Upload your genomic files for comprehensive DNA analysis")
# File upload
uploaded_file = st.file_uploader(
"Choose genomic file",
type=['vcf', 'fasta', 'fa', 'txt'],
help="Supported formats: VCF, FASTA, TXT"
)
if uploaded_file:
# Determine file type
file_type = uploaded_file.name.split('.')[-1].upper()
if file_type in ['FA', 'FASTA']:
file_type = 'FASTA'
elif file_type == 'VCF':
file_type = 'VCF'
else:
file_type = 'TXT'
# Read file content
file_content = str(uploaded_file.read(), 'utf-8')
st.info(f"Processing {file_type} file: {uploaded_file.name}")
# Initialize analyzer
analyzer = GenomicAnalyzer()
with st.spinner("🧬 Analyzing your DNA..."):
genomic_results = analyzer.parse_genomic_file(file_content, file_type)
genetic_risk_score = analyzer.calculate_genetic_risk_score(genomic_results)
# Store in session state
st.session_state.genomic_data = genomic_results
st.session_state.genetic_risk_score = genetic_risk_score
# Display results
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Variants Analyzed", f"{genomic_results['total_variants']:,}")
with col2:
st.metric("Heart Genes Found", len(genomic_results['heart_genes_found']))
with col3:
st.metric("Quality Score", f"{genomic_results['quality_score']:.1f}%")
# Gene details
if genomic_results['heart_genes_found']:
st.subheader("🎯 Heart-Related Genes Detected")
for gene_data in genomic_results['heart_genes_found']:
risk_class = "risk-low" if gene_data['risk_factor'] < 1.0 else "risk-medium" if gene_data['risk_factor'] < 1.3 else "risk-high"
st.markdown(f"""
<div class="{risk_class}" style="padding: 1rem; margin: 0.5rem 0; border-radius: 5px;">
<strong>{gene_data['gene']}</strong> - {gene_data['variant']}
(Risk Factor: {gene_data['risk_factor']:.2f}, Confidence: {gene_data['confidence']:.1%})
</div>
""", unsafe_allow_html=True)
# Risk score visualization
fig = go.Figure(go.Indicator(
mode = "gauge+number+delta",
value = genetic_risk_score,
domain = {'x': [0, 1], 'y': [0, 1]},
title = {'text': "Genetic Heart Risk Score"},
delta = {'reference': 50},
gauge = {
'axis': {'range': [None, 100]},
'bar': {'color': "darkblue"},
'steps': [
{'range': [0, 25], 'color': "lightgreen"},
{'range': [25, 50], 'color': "yellow"},
{'range': [50, 75], 'color': "orange"},
{'range': [75, 100], 'color': "red"}
],
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 75
}
}
))
st.plotly_chart(fig)
st.success("✅ Genomic analysis complete!")
elif tab == "📊 Biomarker Input":
st.header("📊 Health Biomarker Analysis")
st.write("Input your latest blood work and vital signs")
# Manual input option
st.subheader("Manual Biomarker Entry")
col1, col2 = st.columns(2)
with col1:
st.markdown("**Lipid Panel**")
ldl = st.number_input("LDL Cholesterol (mg/dL)", min_value=30, max_value=300, value=120)
hdl = st.number_input("HDL Cholesterol (mg/dL)", min_value=20, max_value=100, value=50)
triglycerides = st.number_input("Triglycerides (mg/dL)", min_value=50, max_value=500, value=150)
st.markdown("**Metabolic Markers**")
glucose = st.number_input("Glucose (mg/dL)", min_value=60, max_value=200, value=90)
hba1c = st.number_input("HbA1c (%)", min_value=4.0, max_value=12.0, value=5.2, step=0.1)
insulin = st.number_input("Insulin (μIU/mL)", min_value=2, max_value=50, value=10)
with col2:
st.markdown("**Vitals & Inflammation**")
systolic_bp = st.number_input("Systolic BP (mmHg)", min_value=80, max_value=200, value=120)
diastolic_bp = st.number_input("Diastolic BP (mmHg)", min_value=50, max_value=120, value=80)
resting_hr = st.number_input("Resting Heart Rate (bpm)", min_value=40, max_value=120, value=70)
crp = st.number_input("C-Reactive Protein (mg/L)", min_value=0.1, max_value=10.0, value=1.0, step=0.1)
st.markdown("**Additional Metrics**")
weight = st.number_input("Weight (kg)", min_value=40, max_value=200, value=75)
age = st.number_input("Age (years)", min_value=18, max_value=120, value=35)
# CSV upload option
st.subheader("Or Upload CSV File")
uploaded_csv = st.file_uploader("Upload biomarker CSV", type=['csv'])
if st.button("🔬 Analyze Biomarkers") or uploaded_csv:
# Create dataframe from inputs
if uploaded_csv:
df = pd.read_csv(uploaded_csv)
else:
df = pd.DataFrame({
'ldl': [ldl], 'hdl': [hdl], 'triglycerides': [triglycerides],
'glucose': [glucose], 'hba1c': [hba1c], 'insulin': [insulin],
'systolic_bp': [systolic_bp], 'diastolic_bp': [diastolic_bp],
'resting_hr': [resting_hr], 'crp': [crp], 'weight': [weight], 'age': [age]
})
# Analyze biomarkers
analyzer = BiomarkerAnalyzer()
biomarker_results = analyzer.analyze_biomarkers(df)
# Store in session state
st.session_state.biomarker_data = biomarker_results
st.session_state.current_age = age
# Display results
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Metabolic Age", f"{biomarker_results['metabolic_age']:.0f} years",
delta=f"{biomarker_results['metabolic_age']-age:.0f}")
with col2:
st.metric("Cardiac Age", f"{biomarker_results['cardiac_age']:.0f} years",
delta=f"{biomarker_results['cardiac_age']-age:.0f}")
with col3:
st.metric("Inflammation Score", f"{biomarker_results['inflammation_score']:.0f}/100")
with col4:
st.metric("Longevity Score", f"{biomarker_results['longevity_score']:.0f}/100")
# Biomarker visualization
categories = ['Metabolic Health', 'Cardiac Health', 'Inflammation', 'Longevity']
values = [
100 - abs(biomarker_results['metabolic_age'] - age) * 2,
100 - abs(biomarker_results['cardiac_age'] - age) * 2,
100 - biomarker_results['inflammation_score'],
biomarker_results['longevity_score']
]
fig = go.Figure(data=go.Scatterpolar(
r=values,
theta=categories,
fill='toself',
name='Your Health Profile'
))
fig.update_layout(
polar=dict(
radialaxis=dict(
visible=True,
range=[0, 100]
)),
showlegend=True,
title="Health Biomarker Radar"
)
st.plotly_chart(fig)
st.success("✅ Biomarker analysis complete!")
elif tab == "🔬 AI Analysis":
st.header("🔬 Comprehensive AI Health Analysis")
if not st.session_state.get('analysis_complete') and (
'genomic_data' not in st.session_state or 'biomarker_data' not in st.session_state
):
st.warning("⚠️ Please complete genomic upload and biomarker input first, or try the demo.")
return
if 'genomic_data' in st.session_state and 'biomarker_data' in st.session_state:
genomic_data = st.session_state.genomic_data
biomarker_data = st.session_state.biomarker_data
current_age = st.session_state.get('current_age', 35)
st.subheader("🧬 Genomic Risk Profile")
# Create genomic summary
protective_genes = len([g for g in genomic_data.get('heart_genes_found', []) if g['risk_factor'] < 1.0])
risk_genes = len([g for g in genomic_data.get('heart_genes_found', []) if g['risk_factor'] > 1.2])
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Protective Variants", protective_genes, delta="Good")
with col2:
st.metric("Risk Variants", risk_genes, delta="Monitor")
with col3:
genetic_risk = st.session_state.get('genetic_risk_score',
GenomicAnalyzer().calculate_genetic_risk_score(genomic_data))
st.metric("Genetic Risk Score", f"{genetic_risk:.0f}/100")
st.subheader("🩺 Biological Age Analysis")
# Biological age comparison
ages_df = pd.DataFrame({
'Age Type': ['Chronological', 'Metabolic', 'Cardiac', 'Optimal'],
'Age': [current_age, biomarker_data['metabolic_age'],
biomarker_data['cardiac_age'], current_age - 5],
'Color': ['blue', 'orange', 'red', 'green']
})
fig = px.bar(ages_df, x='Age Type', y='Age', color='Color',
title="Biological Age Comparison")
st.plotly_chart(fig)
st.subheader("🎯 Risk Factor Matrix")
# Create risk matrix
risk_factors = []
# Genetic risks
for gene in genomic_data.get('heart_genes_found', []):
if gene['risk_factor'] > 1.1:
risk_factors.append({
'Factor': f"{gene['gene']} variant",
'Type': 'Genetic',
'Risk Level': 'High' if gene['risk_factor'] > 1.3 else 'Medium',
'Confidence': f"{gene['confidence']:.1%}"
})
# Biomarker risks
if biomarker_data['inflammation_score'] > 50:
risk_factors.append({
'Factor': 'Chronic Inflammation',
'Type': 'Biomarker',
'Risk Level': 'High',
'Confidence': '95%'
})
if biomarker_data['cardiac_age'] > current_age + 5:
risk_factors.append({
'Factor': 'Accelerated Cardiac Aging',
'Type': 'Biomarker',
'Risk Level': 'Medium',
'Confidence': '88%'
})
if risk_factors:
risk_df = pd.DataFrame(risk_factors)
st.dataframe(risk_df, use_container_width=True)
else:
st.success("🎉 No significant risk factors detected!")
st.session_state.analysis_complete = True
st.success("✅ AI analysis complete!")
elif tab == "🫀 Digital Heart Twin":
st.header("🫀 Digital Heart Twin Simulation")
if not st.session_state.get('analysis_complete'):
st.warning("⚠️ Please complete the AI analysis first.")
return
genomic_data = st.session_state.genomic_data
biomarker_data = st.session_state.biomarker_data
current_age = st.session_state.get('current_age', 35)
genetic_risk = st.session_state.get('genetic_risk_score', 50)
# Create digital heart twin
heart_twin = DigitalHeartTwin()
heart_model = heart_twin.create_heart_model(genetic_risk, biomarker_data, current_age)
st.session_state.heart_model = heart_model
# Current heart status
st.subheader("🔍 Current Heart Status")
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Heart Age", f"{heart_model['current_heart_age']:.0f} years",
delta=f"{heart_model['current_heart_age']-current_age:.0f}")
with col2:
current_risk = heart_model['current_trajectory'][0]['risk_level']
st.metric("Current Risk Level", f"{current_risk:.0f}%")
with col3:
potential_gain = heart_model['potential_years_gained']
st.metric("Potential Years Gained", f"{potential_gain:.1f} years", delta="With optimization")
# Heart aging simulation
st.subheader("📈 Heart Aging Simulation")
# Prepare data for plotting
current_ages = [point['age'] for point in heart_model['current_trajectory']]
current_heart_ages = [point['heart_age'] for point in heart_model['current_trajectory']]
optimized_heart_ages = [point['heart_age'] for point in heart_model['optimized_trajectory']]
fig = go.Figure()
# Current trajectory
fig.add_trace(go.Scatter(
x=current_ages, y=current_heart_ages,
mode='lines+markers',
name='Current Trajectory',
line=dict(color='red', width=3)
))
# Optimized trajectory
fig.add_trace(go.Scatter(
x=current_ages, y=optimized_heart_ages,
mode='lines+markers',
name='Optimized Trajectory',
line=dict(color='green', width=3)
))
# Ideal line (heart age = chronological age)
fig.add_trace(go.Scatter(
x=current_ages, y=current_ages,
mode='lines',
name='Ideal (Heart Age = Chronological Age)',
line=dict(color='blue', dash='dash')
))
fig.update_layout(
title='Digital Heart Twin: Aging Projections',
xaxis_title='Chronological Age (years)',
yaxis_title='Heart Age (years)',
hovermode='x unified'
)
st.plotly_chart(fig, use_container_width=True)
# What-if scenarios
st.subheader("🎛️ What-If Scenarios")
scenario = st.selectbox("Select Intervention Scenario", [
"Current Path (No Changes)",
"Mediterranean Diet + Exercise",
"Aggressive Lipid Management",
"Complete Lifestyle Optimization"
])
# Simulate different scenarios
scenario_benefits = {
"Current Path (No Changes)": 0,
"Mediterranean Diet + Exercise": 0.8,
"Aggressive Lipid Management": 0.7,
"Complete Lifestyle Optimization": 0.6
}
improvement_factor = scenario_benefits[scenario]
if improvement_factor > 0:
scenario_heart_ages = [
heart_model['current_heart_age'] + (age - current_age) * (1 + (genetic_risk / 100) * 0.02) * improvement_factor
for age in current_ages
]
fig_scenario = go.Figure()
fig_scenario.add_trace(go.Scatter(
x=current_ages, y=current_heart_ages,
mode='lines', name='Current Path', line=dict(color='red', dash='dash')
))
fig_scenario.add_trace(go.Scatter(
x=current_ages, y=scenario_heart_ages,
mode='lines+markers', name=scenario, line=dict(color='purple', width=3)
))
fig_scenario.update_layout(title=f'Scenario Analysis: {scenario}')
st.plotly_chart(fig_scenario, use_container_width=True)
# Calculate benefits
years_saved = (current_heart_ages[-1] - scenario_heart_ages[-1]) / 1.5
st.success(f"🎯 This scenario could save approximately {years_saved:.1f} biological years!")
elif tab == "💊 Interventions":
st.header("💊 Personalized Intervention Engine")
if not st.session_state.get('analysis_complete'):
st.warning("⚠️ Please complete the analysis first.")
return
genomic_data = st.session_state.genomic_data
biomarker_data = st.session_state.biomarker_data
# Generate interventions
intervention_engine = InterventionEngine()
interventions = intervention_engine.generate_interventions(genomic_data, biomarker_data)
st.session_state.interventions = interventions
# Display intervention categories
tab_nutrition, tab_exercise, tab_supplements, tab_lifestyle, tab_monitoring = st.tabs([
"🥗 Nutrition", "🏃♂️ Exercise", "💊 Supplements", "🧘♀️ Lifestyle", "📊 Monitoring"
])
with tab_nutrition:
st.subheader("🥗 Personalized Nutrition Plan")
if interventions['nutrition']:
for i, recommendation in enumerate(interventions['nutrition'], 1):
st.markdown(f"**{i}.** {recommendation}")
else:
st.info("Current nutrition approach appears optimal based on your genetics.")
# Sample meal plan
st.markdown("### 📋 Sample Daily Meal Plan")
meal_plan = {
'Breakfast': 'Omega-3 rich salmon, avocado toast, berries',
'Lunch': 'Mediterranean quinoa bowl with olive oil',
'Dinner': 'Grilled vegetables, lean protein, nuts',
'Snacks': 'Plant sterols, dark chocolate (85% cacao)'
}
for meal, food in meal_plan.items():
st.markdown(f"**{meal}:** {food}")
with tab_exercise:
st.subheader("🏃♂️ Exercise Prescription")
if interventions['exercise']:
for i, recommendation in enumerate(interventions['exercise'], 1):
st.markdown(f"**{i}.** {recommendation}")
# Exercise plan visualization
st.markdown("### 📅 Weekly Exercise Schedule")
exercise_data = {
'Day': ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
'Activity': ['HIIT', 'Recovery', 'Cardio', 'Strength', 'Cardio', 'HIIT', 'Rest'],
'Duration': [30, 20, 45, 60, 45, 30, 0]
}
fig = px.bar(exercise_data, x='Day', y='Duration', color='Activity',
title='Weekly Exercise Plan')
st.plotly_chart(fig)
with tab_supplements:
st.subheader("💊 Targeted Supplements")
if interventions['supplements']:
supplement_data = []
for supplement in interventions['supplements']:
name = supplement.split(' ')[0]
dosage = supplement.split(' ')[-1] if 'mg' in supplement or 'g' in supplement else 'As directed'
supplement_data.append({'Supplement': name, 'Dosage': dosage, 'Reason': 'Genetic/Biomarker Based'})
df = pd.DataFrame(supplement_data)
st.dataframe(df, use_container_width=True)
else:
st.info("No specific supplements recommended at this time.")
with tab_lifestyle:
st.subheader("🧘♀️ Lifestyle Optimization")
if interventions['lifestyle']:
for i, recommendation in enumerate(interventions['lifestyle'], 1):
st.markdown(f"**{i}.** {recommendation}")
# Lifestyle score visualization
lifestyle_factors = {
'Sleep Quality': 85,
'Stress Management': 70,
'Social Connection': 80,
'Purpose/Meaning': 75,
'Environmental Health': 90
}
fig = go.Figure(data=go.Scatterpolar(
r=list(lifestyle_factors.values()),
theta=list(lifestyle_factors.keys()),
fill='toself',
name='Current Lifestyle Score'
))
fig.update_layout(
polar=dict(radialaxis=dict(visible=True, range=[0, 100])),
title="Lifestyle Optimization Radar"
)
st.plotly_chart(fig)
with tab_monitoring:
st.subheader("📊 Monitoring Protocol")
if interventions['monitoring']:
for i, recommendation in enumerate(interventions['monitoring'], 1):
st.markdown(f"**{i}.** {recommendation}")
# Monitoring schedule
st.markdown("### 📅 Recommended Testing Schedule")
monitoring_schedule = {
'Test': ['Lipid Panel', 'HbA1c', 'CRP', 'Vitamin D', 'Heart Rate Variability'],
'Frequency': ['Every 3 months', 'Every 6 months', 'Every 6 months', 'Annually', 'Daily'],
'Next Due': ['Jan 2026', 'Mar 2026', 'Mar 2026', 'Sep 2026', 'Ongoing']
}
df = pd.DataFrame(monitoring_schedule)
st.dataframe(df, use_container_width=True)
elif tab == "📈 Future Predictions":
st.header("📈 Future Health Predictions")
if not st.session_state.get('analysis_complete'):
st.warning("⚠️ Please complete the analysis first.")
return
current_age = st.session_state.get('current_age', 35)
heart_model = st.session_state.get('heart_model')
if not heart_model:
st.error("Heart model not found. Please complete the Digital Heart Twin analysis.")
return
st.subheader("🔮 Longevity Predictions")
# Calculate life expectancy
base_life_expectancy = 78 # Global average
genetic_risk = st.session_state.get('genetic_risk_score', 50)
biomarker_data = st.session_state.biomarker_data
# Adjust life expectancy based on factors
longevity_adjustment = 0
longevity_adjustment += (50 - genetic_risk) * 0.3 # Genetic factor
longevity_adjustment += biomarker_data['longevity_score'] * 0.2 # Biomarker factor
longevity_adjustment -= max(0, biomarker_data['inflammation_score'] - 20) * 0.1 # Inflammation penalty
predicted_lifespan = base_life_expectancy + longevity_adjustment
optimized_lifespan = predicted_lifespan + heart_model['potential_years_gained']
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Current Path Lifespan", f"{predicted_lifespan:.0f} years")
with col2:
st.metric("Optimized Lifespan", f"{optimized_lifespan:.0f} years",
delta=f"+{optimized_lifespan-predicted_lifespan:.1f}")
with col3:
healthy_years = optimized_lifespan - max(0, heart_model['current_heart_age'] - current_age)
st.metric("Predicted Healthspan", f"{healthy_years:.0f} years")
# Risk timeline
st.subheader("⚠️ Risk Timeline")
risk_events = []
current_risk = heart_model['current_trajectory'][0]['risk_level']
# Simulate risk events
for point in heart_model['current_trajectory']:
if point['risk_level'] > 25 and len(risk_events) == 0:
risk_events.append({
'Age': point['age'],
'Event': 'Elevated cardiovascular risk detected',
'Probability': f"{point['risk_level']:.0f}%"
})
elif point['risk_level'] > 50 and len(risk_events) == 1:
risk_events.append({
'Age': point['age'],
'Event': 'High risk for coronary artery disease',
'Probability': f"{point['risk_level']:.0f}%"
})
elif point['risk_level'] > 75 and len(risk_events) == 2:
risk_events.append({
'Age': point['age'],
'Event': 'Critical intervention recommended',
'Probability': f"{point['risk_level']:.0f}%"
})
if risk_events:
risk_df = pd.DataFrame(risk_events)
st.dataframe(risk_df, use_container_width=True)
else:
st.success("🎉 No significant risk events predicted in the next 30 years!")
# Intervention impact timeline
st.subheader("📊 Intervention Impact Over Time")
years = list(range(current_age, current_age + 31, 5))
# Current path health score
current_health_scores = [max(0, 100 - (year - current_age) * 2 - genetic_risk * 0.5) for year in years]
# Optimized path health score
optimized_health_scores = [min(100, score * 1.3) for score in current_health_scores]
fig = go.Figure()
fig.add_trace(go.Scatter(
x=years, y=current_health_scores,
mode='lines+markers',
name='Current Path',
line=dict(color='red', width=3)
))
fig.add_trace(go.Scatter(
x=years, y=optimized_health_scores,
mode='lines+markers',
name='With Interventions',
line=dict(color='green', width=3)
))
fig.update_layout(
title='Health Score Projection',
xaxis_title='Age (years)',
yaxis_title='Health Score (0-100)',
yaxis=dict(range=[0, 100])
)
st.plotly_chart(fig, use_container_width=True)
# Precision medicine opportunities
st.subheader("🎯 Precision Medicine Opportunities")
opportunities = [
"Gene therapy for LDLR variants (Clinical trials by 2027)",
"Personalized drug dosing based on CYP2D6 genotype",
"Epigenetic reprogramming protocols (Experimental)",
"AI-designed cardioprotective compounds for your genome",
"Precision nutrition based on gut microbiome analysis"
]
for i, opportunity in enumerate(opportunities, 1):
st.markdown(f"**{i}.** {opportunity}")
# Final summary
st.markdown("---")
st.subheader("📋 Executive Summary")
summary = f"""
**Your EternaHeart Analysis Summary:**