PGx Analyzer Team commited on
Commit
b513d61
·
1 Parent(s): 7c802d4

Add Plotly bar charts, donut charts, and visual graphs across all 9 analysis tabs

Browse files
Files changed (1) hide show
  1. app.py +189 -19
app.py CHANGED
@@ -423,15 +423,36 @@ def render_unified_results(full_results: dict, qc_report: dict):
423
  with c_ov1:
424
  st.markdown("### 🏆 CYP2C19 Phenotype Summary")
425
  pgx = ov.get('cyp2c19_summary', {})
426
- phe_df = pd.DataFrame([{'Phenotype Category': k, 'Count': v['count'], 'Percentage': f"{v['percentage']:.1f}%"} for k, v in pgx.get('phenotypes', {}).items() if v['count'] > 0])
 
427
  st.table(phe_df)
428
 
 
 
 
 
 
 
 
 
 
 
429
  with c_ov2:
430
  st.markdown("### 🌐 Regional Sample Distribution")
431
  reg = full_results.get('regional', {})
432
  reg_df = pd.DataFrame([{'Region': r, 'Sample Count (N)': r_data.get('sample_count', 0), '% of Cohort': f"{(r_data.get('sample_count', 0)/tot_samples*100):.1f}%" if tot_samples>0 else "0%"} for r, r_data in reg.items()])
433
  st.table(reg_df)
434
 
 
 
 
 
 
 
 
 
 
 
435
  # -------------------------------------------------------------------------
436
  # TAB 2: GENOTYPE & ALLELE
437
  # -------------------------------------------------------------------------
@@ -510,9 +531,19 @@ def render_unified_results(full_results: dict, qc_report: dict):
510
  color='Genotype',
511
  color_discrete_sequence=['#15803D', '#1D4ED8', '#B91C1C']
512
  )
513
- fig_bar.update_layout(height=260, margin=dict(l=20, r=20, t=35, b=20))
514
  st.plotly_chart(fig_bar, use_container_width=True)
515
 
 
 
 
 
 
 
 
 
 
 
516
  # -------------------------------------------------------------------------
517
  # TAB 3: HARDY-WEINBERG
518
  # -------------------------------------------------------------------------
@@ -537,7 +568,25 @@ def render_unified_results(full_results: dict, qc_report: dict):
537
  'Exact Test P-Value': hw.get('exact_p_value', 1.0),
538
  'Interpretation': hw.get('interpretation', 'In HWE')
539
  })
540
- st.table(pd.DataFrame(hwe_table_rows))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
541
 
542
  st.markdown("##### Table 3. Chi-Square Distribution Reference Table (df = 1, α = 0.05, Critical = 3.841)")
543
  chi2_ref_df = pd.DataFrame([{
@@ -570,7 +619,24 @@ def render_unified_results(full_results: dict, qc_report: dict):
570
  {'GROUP': 'Gender — Female', 'N': gen_dict.get('Female', {}).get('sample_count', 0), '% OF TOTAL': f"{(gen_dict.get('Female', {}).get('sample_count', 0)/tot_n*100):.1f}%" if tot_n>0 else "0%"},
571
  {'GROUP': 'Gender — Male', 'N': gen_dict.get('Male', {}).get('sample_count', 0), '% OF TOTAL': f"{(gen_dict.get('Male', {}).get('sample_count', 0)/tot_n*100):.1f}%" if tot_n>0 else "0%"},
572
  ]
573
- st.table(pd.DataFrame(group_rows))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
 
575
  # -------------------------------------------------------------------------
576
  # TAB 5: CYP2C19 CALLING
@@ -633,18 +699,34 @@ def render_unified_results(full_results: dict, qc_report: dict):
633
  inv_log_rows.append({'SNP Variant': snp, 'Sample ID': item['sample_id'], 'Raw Invalid Genotype Value': item['raw_value'], 'Audit Action': 'Quarantined & Excluded'})
634
  st.table(pd.DataFrame(inv_log_rows))
635
 
636
- st.markdown("#### Per-SNP Quality Control & Missing Values Table")
637
- qc_rows = []
638
- for snp, sdata in qc_report['snp_qc_stats'].items():
639
- qc_rows.append({
640
- 'SNP Variant': snp,
641
- 'Valid Samples': sdata['valid_samples'],
642
- 'Missing Genotypes Count': sdata['missing_samples'],
643
- 'Invalid Genotypes Count': sdata.get('invalid_samples', 0),
644
- 'Missing Data Rate (%)': f"{sdata['missing_pct']:.1f}%",
645
- 'Quality Audit Status': 'PASS' if sdata.get('invalid_samples', 0) == 0 else 'WARNING'
646
- })
647
- st.table(pd.DataFrame(qc_rows))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
648
 
649
  # -------------------------------------------------------------------------
650
  # TAB 7: GEOGRAPHIC POPULATION GROUPS
@@ -670,6 +752,39 @@ def render_unified_results(full_results: dict, qc_report: dict):
670
  """, unsafe_allow_html=True)
671
 
672
  st.markdown("<br>", unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673
  st.markdown("#### Comprehensive Regional Statistical Summary Table")
674
 
675
  cyp2_rows = [
@@ -724,9 +839,37 @@ def render_unified_results(full_results: dict, qc_report: dict):
724
  if p_name in f_phenos:
725
  pheno_chart_df.append({'Gender': 'Female', 'Phenotype': p_name.split(' (')[0], 'Count': f_phenos[p_name]['count']})
726
 
727
- if pheno_chart_df:
728
- fig_g2 = px.bar(pd.DataFrame(pheno_chart_df), x='Phenotype', y='Count', color='Gender', barmode='group', title="Metabolizer Phenotypes Comparison (Male vs Female)")
729
- st.plotly_chart(fig_g2, use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
730
 
731
  # -------------------------------------------------------------------------
732
  # TAB 9: DEDICATED STATE-WISE PAGES
@@ -748,6 +891,33 @@ def render_unified_results(full_results: dict, qc_report: dict):
748
  pm_pct = st_data.get('cyp2c19_summary', {}).get('phenotypes', {}).get('Poor Metabolizer', st_data.get('cyp2c19_summary', {}).get('phenotypes', {}).get('Poor Metabolizer (PM)', {})).get('percentage', 0)
749
  sk4.metric("Poor Metabolizers %", f"{pm_pct:.1f}%")
750
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
751
  # -----------------------------------------------------------------------------
752
  # 3-STEP WORKFLOW PIPELINE RENDERER (EXACT MATCH FOR USER SCREENSHOTS 1, 2, 3, 4, 5)
753
  # -----------------------------------------------------------------------------
 
423
  with c_ov1:
424
  st.markdown("### 🏆 CYP2C19 Phenotype Summary")
425
  pgx = ov.get('cyp2c19_summary', {})
426
+ phe_dict = pgx.get('phenotypes', {})
427
+ phe_df = pd.DataFrame([{'Phenotype Category': k, 'Count': v['count'], 'Percentage': f"{v['percentage']:.1f}%"} for k, v in phe_dict.items() if v['count'] > 0])
428
  st.table(phe_df)
429
 
430
+ fig_ov_phe = px.pie(
431
+ names=[k for k, v in phe_dict.items() if v['count'] > 0],
432
+ values=[v['count'] for k, v in phe_dict.items() if v['count'] > 0],
433
+ hole=0.45,
434
+ title="Overall Phenotype Distribution",
435
+ color_discrete_sequence=['#166534', '#1E40AF', '#4B5563', '#991B1B', '#D97706', '#0D9488']
436
+ )
437
+ fig_ov_phe.update_layout(height=260, margin=dict(l=20, r=20, t=35, b=20))
438
+ st.plotly_chart(fig_ov_phe, use_container_width=True)
439
+
440
  with c_ov2:
441
  st.markdown("### 🌐 Regional Sample Distribution")
442
  reg = full_results.get('regional', {})
443
  reg_df = pd.DataFrame([{'Region': r, 'Sample Count (N)': r_data.get('sample_count', 0), '% of Cohort': f"{(r_data.get('sample_count', 0)/tot_samples*100):.1f}%" if tot_samples>0 else "0%"} for r, r_data in reg.items()])
444
  st.table(reg_df)
445
 
446
+ reg_chart_df = pd.DataFrame([{'Region': r, 'Samples (N)': r_data.get('sample_count', 0)} for r, r_data in reg.items()])
447
+ fig_ov_reg = px.bar(
448
+ reg_chart_df, x='Region', y='Samples (N)',
449
+ title="Regional Population Group Sizes",
450
+ color='Region',
451
+ color_discrete_sequence=px.colors.qualitative.Set2
452
+ )
453
+ fig_ov_reg.update_layout(height=260, margin=dict(l=20, r=20, t=35, b=20))
454
+ st.plotly_chart(fig_ov_reg, use_container_width=True)
455
+
456
  # -------------------------------------------------------------------------
457
  # TAB 2: GENOTYPE & ALLELE
458
  # -------------------------------------------------------------------------
 
531
  color='Genotype',
532
  color_discrete_sequence=['#15803D', '#1D4ED8', '#B91C1C']
533
  )
534
+ fig_bar.update_layout(height=220, margin=dict(l=20, r=20, t=35, b=20))
535
  st.plotly_chart(fig_bar, use_container_width=True)
536
 
537
+ al_df = pd.DataFrame([{'Allele': k, 'Frequency (%)': a_p.get(k, 0)} for k in a_c.keys()])
538
+ fig_al = px.bar(
539
+ al_df, x='Allele', y='Frequency (%)',
540
+ title=f"{snp_code} Allele Frequencies ({sel_key})",
541
+ color='Allele',
542
+ color_discrete_sequence=['#0D9488', '#D97706']
543
+ )
544
+ fig_al.update_layout(height=200, margin=dict(l=20, r=20, t=35, b=20))
545
+ st.plotly_chart(fig_al, use_container_width=True)
546
+
547
  # -------------------------------------------------------------------------
548
  # TAB 3: HARDY-WEINBERG
549
  # -------------------------------------------------------------------------
 
568
  'Exact Test P-Value': hw.get('exact_p_value', 1.0),
569
  'Interpretation': hw.get('interpretation', 'In HWE')
570
  })
571
+
572
+ c_hwe_tbl, c_hwe_fig = st.columns([1.2, 0.8])
573
+ with c_hwe_tbl:
574
+ st.table(pd.DataFrame(hwe_table_rows))
575
+
576
+ with c_hwe_fig:
577
+ chi2_chart_df = pd.DataFrame([
578
+ {'SNP': snp_name, 'Chi2 Stat': s_res.get('hwe', {}).get('chi2_stat', 0)}
579
+ for snp_name, s_res in snps_data.items()
580
+ ])
581
+ fig_hwe = px.bar(
582
+ chi2_chart_df, x='SNP', y='Chi2 Stat',
583
+ title=f"HWE Chi-Square (χ²) Stats vs Threshold 3.841 ({sel_key})",
584
+ color='SNP',
585
+ color_discrete_sequence=['#2563EB', '#7C3AED', '#DB2777']
586
+ )
587
+ fig_hwe.add_hline(y=3.841, line_dash="dash", line_color="red", annotation_text="Critical Threshold (3.841)")
588
+ fig_hwe.update_layout(height=260, margin=dict(l=20, r=20, t=35, b=20))
589
+ st.plotly_chart(fig_hwe, use_container_width=True)
590
 
591
  st.markdown("##### Table 3. Chi-Square Distribution Reference Table (df = 1, α = 0.05, Critical = 3.841)")
592
  chi2_ref_df = pd.DataFrame([{
 
619
  {'GROUP': 'Gender — Female', 'N': gen_dict.get('Female', {}).get('sample_count', 0), '% OF TOTAL': f"{(gen_dict.get('Female', {}).get('sample_count', 0)/tot_n*100):.1f}%" if tot_n>0 else "0%"},
620
  {'GROUP': 'Gender — Male', 'N': gen_dict.get('Male', {}).get('sample_count', 0), '% OF TOTAL': f"{(gen_dict.get('Male', {}).get('sample_count', 0)/tot_n*100):.1f}%" if tot_n>0 else "0%"},
621
  ]
622
+
623
+ c_pop1, c_pop2 = st.columns([1.0, 1.0])
624
+ with c_pop1:
625
+ st.table(pd.DataFrame(group_rows))
626
+
627
+ with c_pop2:
628
+ pop_chart_df = pd.DataFrame([
629
+ {'Group': r['GROUP'], 'N': r['N']}
630
+ for r in group_rows if r['GROUP'] != 'Overall'
631
+ ])
632
+ fig_pop = px.bar(
633
+ pop_chart_df, x='N', y='Group', orientation='h',
634
+ title="Population Subgroup Sizes (N)",
635
+ color='Group',
636
+ color_discrete_sequence=px.colors.qualitative.Bold
637
+ )
638
+ fig_pop.update_layout(height=320, margin=dict(l=20, r=20, t=35, b=20), yaxis=dict(autorange="reversed"))
639
+ st.plotly_chart(fig_pop, use_container_width=True)
640
 
641
  # -------------------------------------------------------------------------
642
  # TAB 5: CYP2C19 CALLING
 
699
  inv_log_rows.append({'SNP Variant': snp, 'Sample ID': item['sample_id'], 'Raw Invalid Genotype Value': item['raw_value'], 'Audit Action': 'Quarantined & Excluded'})
700
  st.table(pd.DataFrame(inv_log_rows))
701
 
702
+ c_qc_tbl, c_qc_fig = st.columns([1.1, 0.9])
703
+ with c_qc_tbl:
704
+ st.markdown("#### Per-SNP Quality Control & Missing Values Table")
705
+ qc_rows = []
706
+ for snp, sdata in qc_report['snp_qc_stats'].items():
707
+ qc_rows.append({
708
+ 'SNP Variant': snp,
709
+ 'Valid Samples': sdata['valid_samples'],
710
+ 'Missing Genotypes Count': sdata['missing_samples'],
711
+ 'Invalid Genotypes Count': sdata.get('invalid_samples', 0),
712
+ 'Missing Data Rate (%)': f"{sdata['missing_pct']:.1f}%",
713
+ 'Quality Audit Status': 'PASS' if sdata.get('invalid_samples', 0) == 0 else 'WARNING'
714
+ })
715
+ st.table(pd.DataFrame(qc_rows))
716
+
717
+ with c_qc_fig:
718
+ qc_fig_df = pd.DataFrame([
719
+ {'SNP': snp, 'Valid': sdata['valid_samples'], 'Missing': sdata['missing_samples'], 'Invalid': sdata.get('invalid_samples', 0)}
720
+ for snp, sdata in qc_report['snp_qc_stats'].items()
721
+ ])
722
+ fig_qc = px.bar(
723
+ qc_fig_df, x='SNP', y=['Valid', 'Missing', 'Invalid'],
724
+ title="Sample Quality Audit Breakdown per SNP",
725
+ barmode='stack',
726
+ color_discrete_sequence=['#16A34A', '#EAB308', '#DC2626']
727
+ )
728
+ fig_qc.update_layout(height=260, margin=dict(l=20, r=20, t=35, b=20))
729
+ st.plotly_chart(fig_qc, use_container_width=True)
730
 
731
  # -------------------------------------------------------------------------
732
  # TAB 7: GEOGRAPHIC POPULATION GROUPS
 
752
  """, unsafe_allow_html=True)
753
 
754
  st.markdown("<br>", unsafe_allow_html=True)
755
+
756
+ c_geo1, c_geo2 = st.columns(2)
757
+ with c_geo1:
758
+ geo_var_df = pd.DataFrame([
759
+ {'Region': r, 'CYP2C19*2 Variant Freq f(A)': reg.get(r, {}).get('snps', {}).get('CYP2C19*2', {}).get('allele_freqs', {}).get('A', 0)}
760
+ for r in regions
761
+ ])
762
+ fig_geo_var = px.bar(
763
+ geo_var_df, x='Region', y='CYP2C19*2 Variant Freq f(A)',
764
+ title="CYP2C19*2 Variant Frequency f(A) by Region",
765
+ color='Region',
766
+ color_discrete_sequence=px.colors.qualitative.Dark24
767
+ )
768
+ fig_geo_var.update_layout(height=260, margin=dict(l=20, r=20, t=35, b=20))
769
+ st.plotly_chart(fig_geo_var, use_container_width=True)
770
+
771
+ with c_geo2:
772
+ geo_pm_df = pd.DataFrame([
773
+ {
774
+ 'Region': r,
775
+ 'Poor Metabolizer %': reg.get(r, {}).get('cyp2c19_summary', {}).get('phenotypes', {}).get('Poor Metabolizer', reg.get(r, {}).get('cyp2c19_summary', {}).get('phenotypes', {}).get('Poor Metabolizer (PM)', {})).get('percentage', 0)
776
+ }
777
+ for r in regions
778
+ ])
779
+ fig_geo_pm = px.bar(
780
+ geo_pm_df, x='Region', y='Poor Metabolizer %',
781
+ title="Poor Metabolizers (PM %) by Region",
782
+ color='Region',
783
+ color_discrete_sequence=px.colors.qualitative.Vivid
784
+ )
785
+ fig_geo_pm.update_layout(height=260, margin=dict(l=20, r=20, t=35, b=20))
786
+ st.plotly_chart(fig_geo_pm, use_container_width=True)
787
+
788
  st.markdown("#### Comprehensive Regional Statistical Summary Table")
789
 
790
  cyp2_rows = [
 
839
  if p_name in f_phenos:
840
  pheno_chart_df.append({'Gender': 'Female', 'Phenotype': p_name.split(' (')[0], 'Count': f_phenos[p_name]['count']})
841
 
842
+ st.markdown("<br>", unsafe_allow_html=True)
843
+ cg1, cg2 = st.columns(2)
844
+ with cg1:
845
+ if pheno_chart_df:
846
+ fig_g2 = px.bar(
847
+ pd.DataFrame(pheno_chart_df),
848
+ x='Phenotype', y='Count',
849
+ color='Gender', barmode='group',
850
+ title="Metabolizer Phenotypes Comparison (Male vs Female)",
851
+ color_discrete_sequence=['#2563EB', '#EC4899']
852
+ )
853
+ fig_g2.update_layout(height=280, margin=dict(l=20, r=20, t=35, b=20))
854
+ st.plotly_chart(fig_g2, use_container_width=True)
855
+
856
+ with cg2:
857
+ m_snps = male.get('snps', {}).get('CYP2C19*2', {}).get('genotype_counts', {})
858
+ f_snps = female.get('snps', {}).get('CYP2C19*2', {}).get('genotype_counts', {})
859
+ gen_gt_df = []
860
+ for gt in ['GG', 'GA', 'AA']:
861
+ if gt in m_snps:
862
+ gen_gt_df.append({'Gender': 'Male', 'Genotype': gt, 'Count': m_snps[gt]})
863
+ if gt in f_snps:
864
+ gen_gt_df.append({'Gender': 'Female', 'Genotype': gt, 'Count': f_snps[gt]})
865
+ if gen_gt_df:
866
+ fig_gen_gt = px.bar(
867
+ pd.DataFrame(gen_gt_df), x='Genotype', y='Count', color='Gender', barmode='group',
868
+ title="CYP2C19*2 Genotypes Comparison (Male vs Female)",
869
+ color_discrete_sequence=['#2563EB', '#EC4899']
870
+ )
871
+ fig_gen_gt.update_layout(height=280, margin=dict(l=20, r=20, t=35, b=20))
872
+ st.plotly_chart(fig_gen_gt, use_container_width=True)
873
 
874
  # -------------------------------------------------------------------------
875
  # TAB 9: DEDICATED STATE-WISE PAGES
 
891
  pm_pct = st_data.get('cyp2c19_summary', {}).get('phenotypes', {}).get('Poor Metabolizer', st_data.get('cyp2c19_summary', {}).get('phenotypes', {}).get('Poor Metabolizer (PM)', {})).get('percentage', 0)
892
  sk4.metric("Poor Metabolizers %", f"{pm_pct:.1f}%")
893
 
894
+ st_phenos = st_data.get('cyp2c19_summary', {}).get('phenotypes', {})
895
+ st_snps = st_data.get('snps', {}).get('CYP2C19*2', {}).get('genotype_counts', {})
896
+
897
+ cs1, cs2 = st.columns(2)
898
+ with cs1:
899
+ st_gt_df = pd.DataFrame([{'Genotype': k, 'Count': v} for k, v in st_snps.items()])
900
+ if not st_gt_df.empty:
901
+ fig_st_gt = px.bar(
902
+ st_gt_df, x='Genotype', y='Count',
903
+ title=f"{selected_st} — CYP2C19*2 Genotypes",
904
+ color='Genotype',
905
+ color_discrete_sequence=['#16A34A', '#2563EB', '#DC2626']
906
+ )
907
+ fig_st_gt.update_layout(height=260, margin=dict(l=20, r=20, t=35, b=20))
908
+ st.plotly_chart(fig_st_gt, use_container_width=True)
909
+
910
+ with cs2:
911
+ st_phe_df = pd.DataFrame([{'Phenotype': k.split(' (')[0], 'Count': v['count']} for k, v in st_phenos.items() if v['count'] > 0])
912
+ if not st_phe_df.empty:
913
+ fig_st_phe = px.pie(
914
+ st_phe_df, names='Phenotype', values='Count', hole=0.45,
915
+ title=f"{selected_st} — Metabolizer Phenotypes",
916
+ color_discrete_sequence=['#166534', '#1E40AF', '#4B5563', '#991B1B', '#D97706', '#0D9488']
917
+ )
918
+ fig_st_phe.update_layout(height=260, margin=dict(l=20, r=20, t=35, b=20))
919
+ st.plotly_chart(fig_st_phe, use_container_width=True)
920
+
921
  # -----------------------------------------------------------------------------
922
  # 3-STEP WORKFLOW PIPELINE RENDERER (EXACT MATCH FOR USER SCREENSHOTS 1, 2, 3, 4, 5)
923
  # -----------------------------------------------------------------------------