File size: 42,390 Bytes
e1253eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
"""

TopoGrammar - Grammar-Aware 3D Genome Engine Demo

==================================================



Hugging Face Spaces Demo for TopoGrammar v2.1.0

The Industry's First Grammar-Aware Engine for Balanced Structural Variants



Copyright (c) 2026 Bryan Daugherty, Gregory Ward & Shawn Ryan. All Rights Reserved.



This demo showcases TopoGrammar's capabilities without exposing proprietary algorithms.

All results are pre-computed demonstrations for educational purposes.

"""

import gradio as gr
import hashlib
import random
import time
import httpx
import json
import os
from datetime import datetime
from typing import Optional, Dict, List, Tuple

# =============================================================================
# BSV Blockchain Configuration
# =============================================================================

BSV_API_URL = "https://simplebsv.codenlighten.org"
BSV_API_KEY = os.getenv("BSV_API_KEY")  # Set via HF Secrets


def publish_to_bsv(data: Dict) -> Optional[str]:
    """

    Publish attestation data to BSV blockchain via SimpleBSV API.



    Args:

        data: Dictionary containing attestation data (no trade secrets)



    Returns:

        Transaction ID if successful, None otherwise

    """
    # Guard clause: fail gracefully if no key configured
    if not BSV_API_KEY:
        print("BSV_API_KEY not configured - running in offline mode")
        return None
    
    try:
        headers = {
            "Content-Type": "application/json",
            "x-api-key": BSV_API_KEY
        }

        # Use ?wait=true for synchronous response with txid
        response = httpx.post(
            f"{BSV_API_URL}/publish/json?wait=true",
            headers=headers,
            json={"json": data},
            timeout=30.0
        )

        if response.status_code == 200:
            result = response.json()
            return result.get("txid")
        else:
            print(f"BSV API error: {response.status_code} - {response.text}")
            return None

    except Exception as e:
        print(f"BSV publish error: {e}")
        return None

# =============================================================================
# Demo Configuration - Pre-computed results (no trade secrets exposed)
# =============================================================================

# Demo VUS Examples with pre-computed classifications
VUS_EXAMPLES = {
    "brca1_boundary": {
        "name": "BRCA1 TAD Boundary Disruption",
        "variant_id": "chr17:43,044,295 G>A",
        "gene": "BRCA1",
        "initial_class": "VUS",
        "final_class": "Pathogenic",
        "confidence": 0.93,
        "mechanism": "TAD Boundary Disruption",
        "evidence_codes": ["PS3_insulation", "PM1_boundary", "PS3_ctcf"],
        "insulation_change": -0.52,
        "description": "This intronic variant disrupts a CTCF binding site at a critical TAD boundary, causing enhancer-promoter miscommunication affecting BRCA1 expression.",
    },
    "myc_enhancer_hijack": {
        "name": "MYC Enhancer Hijacking",
        "variant_id": "chr8:128,750,000 inv(500kb)",
        "gene": "MYC",
        "initial_class": "VUS",
        "final_class": "Pathogenic",
        "confidence": 0.89,
        "mechanism": "Enhancer Hijacking",
        "evidence_codes": ["PS3_neoloop", "PS2_oncogene", "PM1_boundary"],
        "insulation_change": -0.68,
        "description": "Balanced inversion creates a neo-loop connecting MYC to a hijacked super-enhancer, causing oncogene activation without copy number change.",
    },
    "sonic_hedgehog": {
        "name": "SHH Limb Enhancer",
        "variant_id": "chr7:156,584,000 del(50kb)",
        "gene": "SHH",
        "initial_class": "VUS",
        "final_class": "Likely Pathogenic",
        "confidence": 0.85,
        "mechanism": "Enhancer Deletion",
        "evidence_codes": ["PM1_regulatory", "PP3_conservation", "PS3_insulation"],
        "insulation_change": -0.41,
        "description": "Deletion removes the ZRS limb enhancer from SHH regulatory domain, disrupting developmental gene expression.",
    },
    "benign_intronic": {
        "name": "Benign Intronic SNP",
        "variant_id": "chr12:25,398,284 C>T",
        "gene": "KRAS",
        "initial_class": "VUS",
        "final_class": "Benign",
        "confidence": 0.91,
        "mechanism": "No 3D Impact",
        "evidence_codes": ["BS1_frequency", "BP4_no_disruption"],
        "insulation_change": 0.02,
        "description": "Deep intronic variant with no effect on TAD structure, CTCF binding, or regulatory grammar. Common in population databases.",
    },
    "tp53_scramble": {
        "name": "TP53 Grammar Scrambling",
        "variant_id": "chr17:7,670,000 inv(120kb)",
        "gene": "TP53",
        "initial_class": "VUS",
        "final_class": "Pathogenic",
        "confidence": 0.96,
        "mechanism": "Regulatory Grammar Scrambling",
        "evidence_codes": ["PS3_semantic", "PS3_insulation", "PM1_boundary", "PP3_conservation"],
        "insulation_change": -0.71,
        "description": "Balanced inversion scrambles the regulatory grammar of TP53, inverting enhancer-promoter orientation and disrupting tumor suppressor expression.",
    },
}

# Demo TAD examples
TAD_EXAMPLES = {
    "chr21_dscr": {
        "name": "Chromosome 21 - Down Syndrome Critical Region",
        "region": "chr21:35,000,000-40,000,000",
        "n_tads": 4,
        "n_boundaries": 5,
        "ctcf_sites": 12,
        "genes": ["DSCR1", "DSCR3", "DSCR4", "RUNX1"],
        "boundary_strength": [0.85, 0.92, 0.78, 0.88, 0.81],
    },
    "chr7_egfr": {
        "name": "Chromosome 7 - EGFR Locus",
        "region": "chr7:55,000,000-56,500,000",
        "n_tads": 3,
        "n_boundaries": 4,
        "ctcf_sites": 8,
        "genes": ["EGFR", "LANCL2", "VOPP1"],
        "boundary_strength": [0.91, 0.87, 0.94, 0.82],
    },
    "chr8_myc": {
        "name": "Chromosome 8 - MYC Oncogene",
        "region": "chr8:127,500,000-129,500,000",
        "n_tads": 2,
        "n_boundaries": 3,
        "ctcf_sites": 6,
        "genes": ["MYC", "PVT1"],
        "boundary_strength": [0.96, 0.89, 0.93],
    },
}

# Demo Neo-Loop examples
NEOLOOP_EXAMPLES = {
    "burkitt_myc": {
        "name": "Burkitt Lymphoma - MYC Translocation",
        "sv_type": "Translocation t(8;14)",
        "oncogene": "MYC",
        "hijacked_enhancer": "IGH Super-Enhancer",
        "loop_strength": 0.92,
        "clinical_priority": "Critical",
        "cancer_type": "Burkitt Lymphoma",
        "description": "Classic t(8;14) translocation juxtaposes MYC with immunoglobulin heavy chain enhancers, creating pathogenic neo-loop.",
    },
    "ewing_ewsr1": {
        "name": "Ewing Sarcoma - EWSR1-FLI1",
        "sv_type": "Translocation t(11;22)",
        "oncogene": "EWSR1-FLI1 fusion",
        "hijacked_enhancer": "GGAA microsatellite enhancers",
        "loop_strength": 0.88,
        "clinical_priority": "Critical",
        "cancer_type": "Ewing Sarcoma",
        "description": "Fusion protein creates neo-loops at GGAA microsatellites, aberrantly activating developmental genes.",
    },
    "aml_runx1": {
        "name": "AML - RUNX1 Disruption",
        "sv_type": "Inversion inv(16)",
        "oncogene": "CBFB-MYH11 fusion",
        "hijacked_enhancer": "Myeloid enhancer cluster",
        "loop_strength": 0.85,
        "clinical_priority": "High",
        "cancer_type": "Acute Myeloid Leukemia",
        "description": "Pericentric inversion disrupts normal RUNX1 regulation, creating aberrant chromatin loops.",
    },
}

# Benchmark comparisons
BENCHMARK_DATA = {
    "tad_detection": {
        "TopoGrammar (CTCF-gated)": {"accuracy": 91, "f1": 0.91, "subtad": True},
        "HiCCUPS": {"accuracy": 80, "f1": 0.76, "subtad": False},
        "Arrowhead": {"accuracy": 78, "f1": 0.74, "subtad": False},
        "TopDom": {"accuracy": 75, "f1": 0.71, "subtad": False},
    },
    "vus_resolution": {
        "reclassification_rate": 68,
        "pathogenic_accuracy": 93,
        "mean_confidence": 87,
    },
    "insulation_density": {
        "major_tads": 9.11,
        "all_boundaries": 15.57,
        "improvement": 70.9,
    },
}


# =============================================================================
# Visualization Functions
# =============================================================================

def create_contact_map_ascii(region: str, n_tads: int) -> str:
    """Create ASCII representation of a Hi-C contact map with TADs."""
    size = 40
    map_lines = []

    # Create diagonal pattern with TAD blocks
    tad_size = size // n_tads

    for i in range(size):
        row = ""
        for j in range(size):
            if abs(i - j) <= 2:
                row += "β–ˆβ–ˆ"  # Diagonal
            elif (i // tad_size) == (j // tad_size):
                # Within same TAD
                distance = abs(i - j)
                if distance < tad_size // 2:
                    row += "β–“β–“"
                elif distance < tad_size:
                    row += "β–‘β–‘"
                else:
                    row += "  "
            else:
                row += "  "
        map_lines.append(row)

    return "\n".join(map_lines)


def create_insulation_profile(boundary_strengths: List[float]) -> str:
    """Create ASCII insulation score profile."""
    lines = []
    lines.append("Insulation Score Profile:")
    lines.append("=" * 60)

    for i, strength in enumerate(boundary_strengths):
        bar_len = int(strength * 40)
        bar = "β–ˆ" * bar_len + "β–‘" * (40 - bar_len)
        lines.append(f"Boundary {i+1}: [{bar}] {strength:.2f}")

    lines.append("=" * 60)
    return "\n".join(lines)


def create_grammar_diagram(mechanism: str) -> str:
    """Create regulatory grammar visualization."""
    if mechanism == "Regulatory Grammar Scrambling":
        return """

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”

β”‚                  REGULATORY GRAMMAR ANALYSIS                 β”‚

β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€

β”‚                                                             β”‚

β”‚  REFERENCE GRAMMAR:                                         β”‚

β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”        β”‚

β”‚  β”‚CTCF+ β”‚ β†’ β”‚ ENHANCER β”‚ β†’ β”‚ PROMOTER β”‚ β†’ β”‚ GENE β”‚        β”‚

β”‚  β””β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”˜        β”‚

β”‚  "The enhancer activates the gene"                         β”‚

β”‚                                                             β”‚

β”‚  VARIANT GRAMMAR (SCRAMBLED):                               β”‚

β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”        β”‚

β”‚  β”‚ GENE β”‚ ← β”‚ PROMOTER β”‚ ← β”‚ ENHANCER β”‚ ← β”‚CTCF- β”‚        β”‚

β”‚  β””β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”€β”˜        β”‚

β”‚  "Gene the activates enhancer the" ⚠ SCRAMBLED            β”‚

β”‚                                                             β”‚

β”‚  SEMANTIC BREAK SCORE: 0.85 (CRITICAL)                     β”‚

β”‚  β€’ Token Disruption: 30% weight                            β”‚

β”‚  β€’ Order Inversion: 40% weight                             β”‚

β”‚  β€’ Orientation Flip: 30% weight                            β”‚

β”‚                                                             β”‚

β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

"""
    elif mechanism == "Enhancer Hijacking":
        return """

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”

β”‚                   ENHANCER HIJACKING ANALYSIS                β”‚

β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€

β”‚                                                             β”‚

β”‚  NORMAL TOPOLOGY:                                           β”‚

β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”               β”‚

β”‚  β”‚   TAD A         β”‚     β”‚   TAD B         β”‚               β”‚

β”‚  β”‚ [Enhancer]──────│─X───│──────[Oncogene] β”‚               β”‚

β”‚  β”‚      ↓          β”‚     β”‚                 β”‚               β”‚

β”‚  β”‚  [Target Gene]  β”‚     β”‚                 β”‚               β”‚

β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜               β”‚

β”‚         BOUNDARY BLOCKS CONTACT                             β”‚

β”‚                                                             β”‚

β”‚  AFTER STRUCTURAL VARIANT:                                  β”‚

β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”              β”‚

β”‚  β”‚              FUSED TAD                    β”‚              β”‚

β”‚  β”‚ [Enhancer]═══════════════════[Oncogene]  β”‚              β”‚

β”‚  β”‚      ↓ NEO-LOOP FORMED ↓                 β”‚              β”‚

β”‚  β”‚  [Target Gene]  ⚠ ONCOGENE ACTIVATED ⚠   β”‚              β”‚

β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜              β”‚

β”‚                                                             β”‚

β”‚  LOOP STRENGTH: 0.89 | PRIORITY: CRITICAL                  β”‚

β”‚                                                             β”‚

β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

"""
    elif mechanism == "TAD Boundary Disruption":
        return """

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”

β”‚                TAD BOUNDARY DISRUPTION ANALYSIS              β”‚

β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€

β”‚                                                             β”‚

β”‚  NORMAL INSULATION:                                         β”‚

β”‚  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ β”‚ β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ                       β”‚

β”‚      TAD A        β”‚      TAD B                              β”‚

β”‚                CTCFβ”‚CTCF                                    β”‚

β”‚               β–²β–²β–²β–²β–²β”‚β–²β–²β–²β–²β–²                                   β”‚

β”‚            Strong Boundary                                  β”‚

β”‚                                                             β”‚

β”‚  AFTER VARIANT (CTCF SITE DISRUPTED):                       β”‚

β”‚  β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ   β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ                       β”‚

β”‚      TAD A    β–‘β–‘β–‘β–‘β–‘β–‘β–‘   TAD B                              β”‚

β”‚                 ↓↓↓↓↓                                       β”‚

β”‚           Insulation Leak                                   β”‚

β”‚                                                             β”‚

β”‚  INSULATION CHANGE: -52%                                    β”‚

β”‚  BOUNDARY LOSS: MAJOR                                       β”‚

β”‚                                                             β”‚

β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

"""
    else:
        return """

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”

β”‚                    3D GENOME ANALYSIS                        β”‚

β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€

β”‚                                                             β”‚

β”‚  No significant 3D structural impact detected.              β”‚

β”‚                                                             β”‚

β”‚  β€’ TAD boundaries: INTACT                                   β”‚

β”‚  β€’ Insulation scores: NORMAL                                β”‚

β”‚  β€’ Regulatory grammar: PRESERVED                            β”‚

β”‚  β€’ CTCF binding: UNAFFECTED                                 β”‚

β”‚                                                             β”‚

β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

"""


def create_confidence_bars(evidence_codes: List[str], confidence: float) -> str:
    """Create evidence code visualization."""
    lines = []
    lines.append("\n### Evidence Summary\n")

    for code in evidence_codes:
        # Determine strength from code prefix
        if code.startswith("PS"):
            strength = "Strong"
            bar = "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"
            color = "🟒"
        elif code.startswith("PM"):
            strength = "Moderate"
            bar = "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘"
            color = "🟑"
        elif code.startswith("PP"):
            strength = "Supporting"
            bar = "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘"
            color = "🟠"
        elif code.startswith("BS") or code.startswith("BP"):
            strength = "Benign"
            bar = "β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ"
            color = "πŸ”΅"
        else:
            strength = "Unknown"
            bar = "β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘"
            color = "βšͺ"

        lines.append(f"{color} **{code}** ({strength}): `{bar}`")

    lines.append(f"\n**Overall Confidence**: {confidence:.0%}")

    return "\n".join(lines)


def generate_bsv_attestation(variant_id: str, classification: str, confidence: float) -> str:
    """Generate and publish BSV blockchain attestation."""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S UTC")

    # Create attestation data (no trade secrets - only results summary)
    attestation_data = {
        "platform": "TopoGrammar",
        "version": "v2.1.0",
        "timestamp": timestamp,
        "analysis_type": "VUS_Resolution",
        "variant_id": variant_id,
        "classification": classification,
        "confidence": round(confidence, 2),
        "attestation_type": "demo"
    }

    # Create hash of the attestation data
    data_str = json.dumps(attestation_data, sort_keys=True)
    query_hash = hashlib.sha256(data_str.encode()).hexdigest()[:16]
    full_hash = hashlib.sha256(data_str.encode()).hexdigest()

    # Publish to BSV blockchain
    txid = publish_to_bsv(attestation_data)

    if txid:
        # Real blockchain attestation
        whatsonchain_url = f"https://whatsonchain.com/tx/{txid}"
        status_line = f"Status: βœ“ RECORDED ON BSV MAINNET"
        txid_display = txid[:20] + "..." if len(txid) > 20 else txid
        verify_section = f"""β•‘  Transaction ID: {txid_display}

β•‘                                                              β•‘

β•‘  πŸ”— Verify on WhatsOnChain:                                  β•‘

β•‘  {whatsonchain_url[:54]}"""
    else:
        # Fallback if API fails
        status_line = "Status: ⚠ OFFLINE MODE (BSV API unavailable)"
        verify_section = f"""β•‘  Data Hash:      {full_hash[:32]}...

β•‘                                                              β•‘

β•‘  β„Ή Blockchain recording temporarily unavailable.             β•‘

β•‘  Result hash preserved for later attestation."""

    return f"""

```

╔══════════════════════════════════════════════════════════════╗

β•‘           TOPOGRAMMAR BSV ATTESTATION CERTIFICATE            β•‘

╠══════════════════════════════════════════════════════════════╣

β•‘                                                              β•‘

β•‘  Query Hash:     {query_hash}                    β•‘

β•‘  Timestamp:      {timestamp}                     β•‘

β•‘  Model Version:  TopoGrammar v2.1.0                         β•‘

β•‘                                                              β•‘

β•‘  ─────────────────────────────────────────────────────────  β•‘

β•‘                                                              β•‘

β•‘  Variant:        {variant_id}

β•‘  Classification: {classification}

β•‘  Confidence:     {confidence:.1%}

β•‘                                                              β•‘

β•‘  ─────────────────────────────────────────────────────────  β•‘

β•‘                                                              β•‘

β•‘  {status_line}

β•‘  Network: BSV Mainnet                                        β•‘

β•‘                                                              β•‘

{verify_section}

β•‘                                                              β•‘

β•‘  This attestation is immutably recorded on BSV blockchain.  β•‘

β•‘  No proprietary algorithms or trade secrets are published.  β•‘

β•‘                                                              β•‘

β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

```

"""


def create_share_links(variant_id: str, classification: str) -> str:
    """Create social sharing buttons."""
    import urllib.parse

    text = f"🧬 TopoGrammar reclassified {variant_id} as {classification}! Grammar-aware 3D genome analysis for precision medicine. #Genomics #AI #PrecisionMedicine"

    twitter_url = f"https://twitter.com/intent/tweet?text={urllib.parse.quote(text)}&url=https://huggingface.co/spaces/GotThatData/TopoGrammar"
    linkedin_url = f"https://www.linkedin.com/sharing/share-offsite/?url=https://huggingface.co/spaces/GotThatData/TopoGrammar"

    return f"""

<div style="display: flex; gap: 10px; margin-top: 20px;">

    <a href="{twitter_url}" target="_blank" style="background: #1DA1F2; color: white; padding: 10px 20px; border-radius: 5px; text-decoration: none;">

        🐦 Share on X

    </a>

    <a href="{linkedin_url}" target="_blank" style="background: #0077B5; color: white; padding: 10px 20px; border-radius: 5px; text-decoration: none;">

        πŸ’Ό Share on LinkedIn

    </a>

</div>

"""


# =============================================================================
# Main Demo Functions
# =============================================================================

def run_vus_analysis(example_key: str) -> str:
    """Run VUS resolution demo."""
    if example_key not in VUS_EXAMPLES:
        return "❌ Example not found. Please select a valid example."

    # Simulate processing delay
    time.sleep(1.5)

    example = VUS_EXAMPLES[example_key]

    # Build result markdown
    result = f"""

# 🧬 VUS Resolution Analysis



## Variant Information

| Field | Value |

|-------|-------|

| **Variant ID** | `{example['variant_id']}` |

| **Gene** | {example['gene']} |

| **Initial Classification** | {example['initial_class']} |



---



## TopoGrammar Analysis Result



### Classification Update

| Before | β†’ | After |

|--------|---|-------|

| **{example['initial_class']}** | πŸ”„ | **{example['final_class']}** |



### Confidence Score

{"β–ˆ" * int(example['confidence'] * 20)}{"β–‘" * (20 - int(example['confidence'] * 20))} **{example['confidence']:.0%}**



### Primary Mechanism

**{example['mechanism']}**



### 3D Structural Impact

- **Insulation Change**: {example['insulation_change']:+.0%}



---



## Mechanism Visualization



{create_grammar_diagram(example['mechanism'])}



---



{create_confidence_bars(example['evidence_codes'], example['confidence'])}



---



## Clinical Interpretation



{example['description']}



---



## BSV Verification



{generate_bsv_attestation(example['variant_id'], example['final_class'], example['confidence'])}



---



{create_share_links(example['variant_id'], example['final_class'])}

"""

    return result


def run_tad_analysis(example_key: str) -> str:
    """Run TAD detection demo."""
    if example_key not in TAD_EXAMPLES:
        return "❌ Example not found. Please select a valid example."

    time.sleep(1.0)

    example = TAD_EXAMPLES[example_key]

    result = f"""

# πŸ”¬ TAD Detection Analysis



## Region Information

| Field | Value |

|-------|-------|

| **Region** | `{example['region']}` |

| **TADs Detected** | {example['n_tads']} |

| **Boundaries** | {example['n_boundaries']} |

| **CTCF Sites** | {example['ctcf_sites']} |



---



## Genes in Region

{', '.join([f"**{g}**" for g in example['genes']])}



---



## Contact Map Visualization



```

{create_contact_map_ascii(example['region'], example['n_tads'])}

```



---



## Boundary Strength Profile



```

{create_insulation_profile(example['boundary_strength'])}

```



---



## Detection Method



TopoGrammar uses **CTCF-gated boundary detection** which achieves:

- **91% TAD accuracy** (vs 80% for HiCCUPS)

- **0.91 F1 score** for boundary detection

- **Sub-TAD detection** capability



The CTCF-gating mechanism ensures boundaries are only called where:

1. Insulation score shows local minimum

2. CTCF binding evidence is present

3. Gradient analysis confirms boundary



---



## Benchmark Comparison



| Method | TAD Accuracy | Boundary F1 | Sub-TAD |

|--------|-------------|-------------|---------|

| **TopoGrammar** | **91%** | **0.91** | βœ“ |

| HiCCUPS | 80% | 0.76 | βœ— |

| Arrowhead | 78% | 0.74 | βœ— |

| TopDom | 75% | 0.71 | βœ— |

"""

    return result


def run_neoloop_analysis(example_key: str) -> str:
    """Run neo-loop detection demo."""
    if example_key not in NEOLOOP_EXAMPLES:
        return "❌ Example not found. Please select a valid example."

    time.sleep(1.2)

    example = NEOLOOP_EXAMPLES[example_key]

    # Priority styling
    if example['clinical_priority'] == "Critical":
        priority_emoji = "πŸ”΄"
        priority_style = "color: red; font-weight: bold;"
    else:
        priority_emoji = "🟑"
        priority_style = "color: orange; font-weight: bold;"

    result = f"""

# πŸ§ͺ Neo-Loop Detection Analysis



## Structural Variant

| Field | Value |

|-------|-------|

| **SV Type** | `{example['sv_type']}` |

| **Cancer Type** | {example['cancer_type']} |

| **Clinical Priority** | {priority_emoji} **{example['clinical_priority']}** |



---



## Oncogene Activation



### Activated Oncogene

**{example['oncogene']}**



### Hijacked Enhancer

**{example['hijacked_enhancer']}**



### Neo-Loop Strength

{"β–ˆ" * int(example['loop_strength'] * 20)}{"β–‘" * (20 - int(example['loop_strength'] * 20))} **{example['loop_strength']:.0%}**



---



## Mechanism Visualization



```

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”

β”‚                    NEO-LOOP FORMATION                        β”‚

β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€

β”‚                                                             β”‚

β”‚  BEFORE: {example['sv_type']}

β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                     β”‚

β”‚  β”‚  Enhancer  │─ ─ X ─ ─│  Oncogene  β”‚                     β”‚

β”‚  β”‚  Domain A  β”‚         β”‚  Domain B  β”‚                     β”‚

β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                     β”‚

β”‚       ↓                                                     β”‚

β”‚   Normal Target                                             β”‚

β”‚                                                             β”‚

β”‚  AFTER: {example['sv_type']}

β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                  β”‚

β”‚  β”‚     Enhancer ══════════ Oncogene     β”‚                  β”‚

β”‚  β”‚         ↓   NEO-LOOP   ↓             β”‚                  β”‚

β”‚  β”‚      ABERRANT ACTIVATION             β”‚                  β”‚

β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                  β”‚

β”‚                                                             β”‚

β”‚  Loop Strength: {example['loop_strength']:.2f}

β”‚  Priority: {example['clinical_priority']}

β”‚                                                             β”‚

β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

```



---



## Clinical Interpretation



{example['description']}



---



## Actionable Insights



Based on this neo-loop detection:



1. **Molecular Testing**: Confirm {example['sv_type']} by FISH or karyotyping

2. **Targeted Therapy**: Consider therapies targeting {example['oncogene']} pathway

3. **Clinical Trial**: Patient may be eligible for trials targeting this mechanism

4. **Monitoring**: Track {example['oncogene']} expression as biomarker



---



## BSV Verification



{generate_bsv_attestation(example['sv_type'], f"Neo-loop: {example['oncogene']}", example['loop_strength'])}

"""

    return result


def show_benchmarks() -> str:
    """Show benchmark results."""
    return f"""

# πŸ“Š TopoGrammar Benchmarks



## TAD Detection Performance



| Method | TAD Accuracy | Boundary F1 | Sub-TAD Detection |

|--------|-------------|-------------|-------------------|

| **TopoGrammar (CTCF-gated)** | **91%** | **0.91** | βœ“ Yes |

| HiCCUPS | 80% | 0.76 | βœ— No |

| Arrowhead | 78% | 0.74 | βœ— No |

| TopDom | 75% | 0.71 | βœ— No |



---



## VUS Resolution Performance



| Metric | Value |

|--------|-------|

| **Reclassification Rate** | 68% of VUS variants |

| **Pathogenic Accuracy** | 93% |

| **Mean Confidence Score** | 87% |



---



## Insulation Density Improvement



| Boundary Set | Insulation Ratio | P-value |

|--------------|------------------|---------|

| Major TADs only | 9.11x | <0.0001 |

| **All Boundaries** | **15.57x** | **<0.0001** |

| **Improvement** | **+70.9%** | β€” |



---



## What Makes TopoGrammar Different



### 1. Grammar-Aware Architecture



Traditional tools see DNA as a string of letters. TopoGrammar sees it as **sentences with grammar**:



```

Reference:  [CTCF+] [Enhancer] [Promoter] [Gene]

            "The enhancer activates the gene"



Inversion:  [Gene] [Promoter] [Enhancer] [CTCF-]

            "Gene the activates enhancer the"  ← SCRAMBLED

```



### 2. Physics + Semantics Concordance



When both physics (insulation collapse) AND semantics (grammar scramble) agree:



| Evidence Type | Alone | Concordant |

|--------------|-------|------------|

| Physics | PM1 (Moderate) | β€” |

| Semantics | PM1 (Moderate) | β€” |

| **Both** | β€” | **PS3 (Strong)** ← UPGRADE |



### 3. CTCF-Gated Detection



Unlike other tools, TopoGrammar only calls boundaries where:

- βœ“ Insulation score shows local minimum

- βœ“ CTCF binding evidence is present

- βœ“ Gradient analysis confirms boundary



This reduces false positives by **40%** compared to insulation-only methods.



---



## Clinical Value Pillars



| Pillar | Clinical Value | Technical Foundation |

|--------|---------------|---------------------|

| **Architectural Fidelity** | Eliminates VUS by proving physical boundary collapse | PINN Physics (15.57x insulation) |

| **Semantic Intelligence** | Detects "scrambled" instructions in balanced inversions | Regulatory Grammar Encoder |

| **Privacy-First Growth** | Global model evolution without data leakage | Async Federated Learning |

| **Clinician Clarity** | High-level medical prose instead of raw math | LLM Interpretation Layer |

"""


# =============================================================================
# Gradio Interface
# =============================================================================

HEADER_MD = """

# 🧬 TopoGrammar



## The Industry's First Grammar-Aware 3D Genome Engine



**Balanced Structural Variants (BSVs)** - inversions, translocations, complex rearrangements - appear "silent" to standard sequencers because they don't change gene dosage. But they **scramble the regulatory grammar** that controls gene expression.



**TopoGrammar solves this.** It's the first engine that understands chromatin as a *language* with grammar rules that can be broken.



---



| Capability | Performance |

|------------|-------------|

| 🎯 VUS Reclassification | 68% of variants |

| πŸ“Š Pathogenic Accuracy | 93% confidence |

| πŸ”¬ TAD Detection F1 | 0.91 (vs 0.76 HiCCUPS) |

| ⚑ Sub-TAD Detection | Yes (unique capability) |



---

"""

ABOUT_MD = """

# ℹ️ About TopoGrammar



## Overview



TopoGrammar is part of the **OmniPrime Enterprise Platform**, integrating:

- **TopoGrammar v2.1.0** - Grammar-Aware 3D Genome Engine

- **BioPrime v4.0 "Golden"** - Physics-First Molecular Docking



Together, they enable a seamless **Patient Genome β†’ Drug Candidate** workflow.



---



## Core Innovation



### Regulatory Grammar Analysis



TopoGrammar treats regulatory elements as a **language**:



```

CTCF β†’ Enhancer β†’ Promoter β†’ Gene

   "The enhancer activates the gene"

```



When structural variants **scramble** this grammar, TopoGrammar detects it:



```

Gene ← Promoter ← Enhancer ← CTCF

   "Gene the activates enhancer the"  ⚠ PATHOGENIC

```



### Semantic Break Score



Quantifies regulatory disruption:

- **Token Disruption (30%)**: Elements removed or duplicated

- **Order Inversion (40%)**: Sequence rearranged

- **Orientation Flip (30%)**: Strand direction reversed



---



## Technology Stack



- **Physics-Informed Neural Networks (PINNs)** for 3D reconstruction

- **CTCF-Gated Boundary Detection** for precise TAD calling

- **Federated Learning** for privacy-preserving multi-site training

- **LLM Interpretation** for clinical reporting

- **BSV Blockchain** for result attestation



---



## Creators



- **Bryan Daugherty**

- **Gregory Ward**

- **Shawn Ryan**



---



## Learn More



🌐 [bioprime.one](https://bioprime.one) | 🧬 [OmniPrime Platform](https://github.com/Saifullah62/OmniPrime_v1.0)



---



**Copyright (c) 2026 Bryan Daugherty, Gregory Ward & Shawn Ryan. All Rights Reserved.**



*This demo showcases TopoGrammar capabilities. Actual clinical use requires the full OmniPrime Enterprise Platform.*

"""

# Custom CSS
CUSTOM_CSS = """

.gradio-container {

    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);

}

.gr-button-primary {

    background: linear-gradient(90deg, #00d4ff, #00ff88) !important;

    border: none !important;

}

.gr-button-secondary {

    background: linear-gradient(90deg, #667eea, #764ba2) !important;

    border: none !important;

    color: white !important;

}

"""

# Build the interface
with gr.Blocks(
    title="TopoGrammar - Grammar-Aware 3D Genome Engine",
    theme=gr.themes.Base(
        primary_hue="cyan",
        secondary_hue="purple",
        neutral_hue="slate",
    ),
    css=CUSTOM_CSS,
) as demo:

    gr.Markdown(HEADER_MD)

    with gr.Tabs():
        # Tab 1: VUS Resolution
        with gr.TabItem("🧬 VUS Resolution"):
            gr.Markdown("""

            ## Variant of Uncertain Significance β†’ Clinical Classification



            Select a demo variant to see how TopoGrammar reclassifies VUS using 3D genome analysis.

            """)

            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("### Select Example")
                    vus_brca1 = gr.Button("πŸ”΄ BRCA1 Boundary Disruption", variant="secondary")
                    vus_myc = gr.Button("πŸ”΄ MYC Enhancer Hijacking", variant="secondary")
                    vus_shh = gr.Button("🟑 SHH Limb Enhancer", variant="secondary")
                    vus_tp53 = gr.Button("πŸ”΄ TP53 Grammar Scrambling", variant="secondary")
                    vus_benign = gr.Button("🟒 Benign Intronic SNP", variant="secondary")

                with gr.Column(scale=3):
                    vus_output = gr.Markdown("*Select an example to run VUS analysis*")

            vus_brca1.click(fn=lambda: run_vus_analysis("brca1_boundary"), outputs=vus_output)
            vus_myc.click(fn=lambda: run_vus_analysis("myc_enhancer_hijack"), outputs=vus_output)
            vus_shh.click(fn=lambda: run_vus_analysis("sonic_hedgehog"), outputs=vus_output)
            vus_tp53.click(fn=lambda: run_vus_analysis("tp53_scramble"), outputs=vus_output)
            vus_benign.click(fn=lambda: run_vus_analysis("benign_intronic"), outputs=vus_output)

        # Tab 2: TAD Detection
        with gr.TabItem("πŸ”¬ TAD Detection"):
            gr.Markdown("""

            ## Topologically Associating Domain Detection



            See how TopoGrammar detects TAD boundaries with CTCF-gating for 91% accuracy.

            """)

            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("### Select Region")
                    tad_dscr = gr.Button("Chr21 - Down Syndrome Region", variant="secondary")
                    tad_egfr = gr.Button("Chr7 - EGFR Locus", variant="secondary")
                    tad_myc = gr.Button("Chr8 - MYC Oncogene", variant="secondary")

                with gr.Column(scale=3):
                    tad_output = gr.Markdown("*Select a region to analyze TAD structure*")

            tad_dscr.click(fn=lambda: run_tad_analysis("chr21_dscr"), outputs=tad_output)
            tad_egfr.click(fn=lambda: run_tad_analysis("chr7_egfr"), outputs=tad_output)
            tad_myc.click(fn=lambda: run_tad_analysis("chr8_myc"), outputs=tad_output)

        # Tab 3: Neo-Loop Detection
        with gr.TabItem("πŸ§ͺ Neo-Loop Detection"):
            gr.Markdown("""

            ## Cancer Neo-Loop & Enhancer Hijacking Detection



            Identify oncogene activation through structural variant-induced neo-loops.

            """)

            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("### Select Cancer Example")
                    neo_burkitt = gr.Button("πŸ”΄ Burkitt Lymphoma (MYC)", variant="secondary")
                    neo_ewing = gr.Button("πŸ”΄ Ewing Sarcoma (EWSR1)", variant="secondary")
                    neo_aml = gr.Button("🟑 AML (RUNX1)", variant="secondary")

                with gr.Column(scale=3):
                    neo_output = gr.Markdown("*Select a cancer example to detect neo-loops*")

            neo_burkitt.click(fn=lambda: run_neoloop_analysis("burkitt_myc"), outputs=neo_output)
            neo_ewing.click(fn=lambda: run_neoloop_analysis("ewing_ewsr1"), outputs=neo_output)
            neo_aml.click(fn=lambda: run_neoloop_analysis("aml_runx1"), outputs=neo_output)

        # Tab 4: Benchmarks
        with gr.TabItem("πŸ“Š Benchmarks"):
            gr.Markdown(show_benchmarks())

        # Tab 5: About
        with gr.TabItem("ℹ️ About"):
            gr.Markdown(ABOUT_MD)

    gr.Markdown("---")
    gr.Markdown("""

    <center>



    **TopoGrammar v2.1.0** | Part of **OmniPrime Enterprise Platform**



    [🌐 bioprime.one](https://bioprime.one) | [🧬 GitHub](https://github.com/Saifullah62/OmniPrime_v1.0) | [πŸ“§ Contact](mailto:info@bioprime.one)



    *This is a demonstration. Clinical use requires the full OmniPrime Enterprise Platform.*



    </center>

    """)


if __name__ == "__main__":
    demo.launch()