File size: 38,855 Bytes
846b701
330a9f0
846b701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330a9f0
846b701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
db4aa9d
846b701
 
 
 
 
 
 
 
 
 
 
 
 
 
330a9f0
846b701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330a9f0
846b701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330a9f0
846b701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330a9f0
846b701
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330a9f0
846b701
 
 
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
"""
app.py - Gulumba Genomics Suite v1.0

A single Streamlit application combining, on a shared, tested scientific core
(genomics_core.py), the functionality previously spread across five separate
tools: GenomeScope Pro (composition/codon-bias viewer), the Prokka annotation
workbench, the Pan-Genome analysis app, and the Comparative Genomics app.

Each tool is its own tab with its own "Run" button and its own inputs, exactly
as the separate apps worked before, so nothing about how you use any one tool
changes. What changes underneath:

  - All GC%, codon usage, ENC, CAI, and assembly-statistics calculations are
    computed once, in genomics_core.py, and reused by every tool. The
    original tools each had their own, occasionally disagreeing, copy of
    these formulas (e.g. GC% over unambiguous bases only vs. over full
    length including N). That disagreement is resolved by having one
    implementation.
  - Comparative Genomics gained an alignment-free mode (MinHash/Mash distance
    and ANI, plus a neighbour-joining tree) for genomes too large for the
    original pairwise Needleman-Wunsch approach, which does not scale past a
    few Mb. The original pairwise mode is kept for what it was always good
    at: genes, plasmids, amplicons, and other short, closely related
    sequences.
  - Pan-Genome analysis gained Heaps' law openness estimation and Tettelin-
    style gene-accumulation curves (with permutation resampling), so you can
    report whether the pan-genome is open or closed, not just the core/
    accessory/unique counts.
  - Every figure is publication-styled (600 dpi raster + vector PDF/SVG,
    colour-blind-safe palettes, Type-42 embedded fonts) and every heuristic
    call (origin/terminus prediction, self-derived CAI weights, alignment-
    free ANI) carries an honest confidence/provenance label in the figure or
    table itself, not just in a caption you might not export.

Requirements
    Core (always required): streamlit, pandas, numpy, scipy, matplotlib
    GenBank/EMBL parsing:    biopython
    Annotation workbench:    prokka (external tool on PATH)
    Pan-genome tool:         pyrodigal (pip), cd-hit (external tool on PATH)

Run with:  streamlit run app.py
"""

import io
import os
import shutil
import tempfile
import zipfile
from pathlib import Path
from typing import Dict, List, Optional

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import streamlit as st

import genomics_core as gc
import genomics_figures as gf
import genomics_parsing as gp
import genomics_external as ge

st.set_page_config(page_title="Gulumba Genomics Suite v1.0", page_icon="\U0001F9EC", layout="wide")
gc.set_publication_style()

WORK_ROOT = Path(tempfile.gettempdir()) / "unified_genomics_suite"
WORK_ROOT.mkdir(parents=True, exist_ok=True)


# ============================================================================
# Shared helpers
# ============================================================================

def fig_to_png_bytes(fig, dpi=600) -> bytes:
    buf = io.BytesIO()
    fig.savefig(buf, format="png", dpi=dpi, bbox_inches="tight")
    buf.seek(0)
    return buf.getvalue()


def fig_to_vector_bytes(fig, fmt="pdf") -> bytes:
    buf = io.BytesIO()
    fig.savefig(buf, format=fmt, bbox_inches="tight")
    buf.seek(0)
    return buf.getvalue()


def build_zip(figures: Dict[str, bytes], tables: Dict[str, pd.DataFrame], readme: str = "") -> bytes:
    mem = io.BytesIO()
    with zipfile.ZipFile(mem, "w", compression=zipfile.ZIP_DEFLATED) as zf:
        for name, data in figures.items():
            zf.writestr(f"figures/{name}", data)
        for name, df in tables.items():
            zf.writestr(f"tables/{name}", df.to_csv(index=False))
        if readme:
            zf.writestr("README.txt", readme)
    mem.seek(0)
    return mem.getvalue()


METHODS_NOTE = (
    "Methods note: GC/AT content is reported over unambiguous (A/C/G/T) bases only, "
    "so ambiguity codes and gaps do not bias the percentage. The effective number of "
    "codons follows Wright (1990). RSCU and the codon adaptation index follow Sharp "
    "and Li (1986, 1987). Origin/terminus prediction from cumulative GC skew follows "
    "Lobry (1996) and Grigoriev (1998), and is reported with a signal-to-noise "
    "confidence flag rather than as a certainty - always confirm with dedicated tools "
    "for a final assembly. Alignment-free genome distance uses MinHash/Mash sketching "
    "(Ondov et al. 2016); ANI is estimated from the Mash Jaccard-containment distance, "
    "not from a base-level alignment, and should be read as an estimate at high "
    "similarity (>90% ANI) where the underlying approximation is most accurate."
)


def genetic_code_selector(key_prefix: str) -> gc.CodonContext:
    options = {
        "11 Bacterial, Archaeal and Plant Plastid": 11,
        "1 Standard": 1,
        "2 Vertebrate Mitochondrial": 2,
        "4 Mold, Protozoan and Coelenterate Mitochondrial": 4,
        "5 Invertebrate Mitochondrial": 5,
        "9 Echinoderm and Flatworm Mitochondrial": 9,
    }
    label = st.selectbox("Genetic code table", list(options.keys()), key=f"{key_prefix}_gcode")
    return gc.build_codon_context(options[label])


def theme_selector(key_prefix: str) -> str:
    return st.selectbox("Figure colour theme", ["Ocean", "Ember", "Forest", "Royal"], key=f"{key_prefix}_theme")


def collect_cds_sequences(records: List[gp.GenomeRecord], tables: Dict[str, pd.DataFrame],
                          min_len_bp: int = 90) -> List[str]:
    """Extract CDS sequences from parsed feature tables (any input format)."""
    seqs = []
    for rec in records:
        fdf = tables.get(rec.id)
        if fdf is None or fdf.empty:
            continue
        cds = fdf[fdf["feature_type"].str.lower().isin(["cds"])]
        for _, row in cds.iterrows():
            start, end = int(row["start"]), int(row["end"])
            seq = rec.seq[start:end]
            if int(row.get("strand", 0)) == -1:
                seq = gp.reverse_complement(seq)
            seq = gc.valid_cds(seq)
            if len(seq) >= min_len_bp:
                seqs.append(seq)
    return seqs


# ============================================================================
# Page header
# ============================================================================

st.markdown("## \U0001F9EC Unified Genomics Suite")
st.caption(
    "Gulumba Genome composition and codon usage \u00b7 Prokka annotation workbench \u00b7 "
    "Pan-genome analysis \u00b7 Comparative genomics. One shared, tested scientific "
    "core; publication-ready figures and tables throughout."
)

tab_names = [
    "1. Genome Composition & Codon Usage",
    "2. Annotation Workbench (Prokka)",
    "3. Pan-Genome Analysis",
    "4. Comparative Genomics",
]
tab1, tab2, tab3, tab4 = st.tabs(tab_names)


# ============================================================================
# TOOL 1 - Gulumba Genome composition & codon usage
# (replaces GenomeScope Pro 2.1 + genome_analytics.py)
# ============================================================================

with tab1:
    st.markdown("#### Single-genome structure, GC content, and codon usage bias")
    st.caption(
        "Accepts GenBank, EMBL, FASTA, GFF/GTF+FASTA, BED+FASTA, an annotation "
        "table+FASTA, or a ZIP bundle of any of these."
    )

    c1, c2 = st.columns(2)
    with c1:
        primary_file = st.file_uploader(
            "Genome file (or ZIP bundle)", key="t1_primary",
            type=["gb", "gbk", "genbank", "embl", "fa", "fasta", "fna", "fas",
                  "gff", "gff3", "gtf", "bed", "csv", "tsv", "zip", "gz"],
        )
    with c2:
        secondary_file = st.file_uploader(
            "Matching FASTA (only needed for GFF/BED/table input)", key="t1_secondary",
            type=["fa", "fasta", "fna", "fas", "gz"],
        )

    ctx1 = genetic_code_selector("t1")
    theme1 = theme_selector("t1")
    window_size = st.number_input("Window size for GC/skew (bp)", min_value=100, max_value=200000, value=1000, step=100, key="t1_window")
    min_coding_bp = st.number_input("Minimum CDS length for codon analysis (bp)", min_value=30, max_value=3000, value=90, step=30, key="t1_mincds")

    run1 = st.button("Run genome composition & codon usage analysis", type="primary", key="t1_run")

    if run1:
        if primary_file is None:
            st.error("Please upload a genome file.")
        else:
            try:
                with st.spinner("Parsing input..."):
                    secondary_bytes = secondary_file.getvalue() if secondary_file else None
                    secondary_name = secondary_file.name if secondary_file else None
                    parsed = gp.parse_any(primary_file.name, primary_file.getvalue(), secondary_name, secondary_bytes)

                if not parsed.records:
                    st.error("No sequence records were parsed from the uploaded file.")
                else:
                    main_rec = max(parsed.records, key=lambda r: len(r.seq))
                    feature_df = parsed.tables.get(main_rec.id, gp.empty_feature_table())

                    with st.spinner("Computing composition, skew, and codon metrics..."):
                        window_df = gc.window_table(main_rec.seq, window=int(window_size))
                        ori_ter = gc.predict_ori_ter(window_df)
                        nuc_counts = gc.nucleotide_counts(main_rec.seq)
                        dinuc_df = gc.dinucleotide_oe(main_rec.seq)

                        lengths = [len(r.seq) for r in parsed.records]
                        assembly = gc.assembly_statistics(lengths)

                        cds_seqs = collect_cds_sequences(parsed.records, parsed.tables, int(min_coding_bp))
                        counts = gc.aggregate_codon_counts(cds_seqs, ctx1)
                        stops = gc.stop_codon_counts(cds_seqs, ctx1)
                        weights, weight_source, weight_note = gc.build_cai_weights(ctx1, all_seqs=cds_seqs)
                        usage = gc.codon_usage_table(counts, ctx1, stops)
                        per_gene = gc.per_gene_codon_table(cds_seqs, ctx1, weights, min_codons=int(min_coding_bp) // 3)
                        aa_df = gc.amino_acid_usage(cds_seqs, ctx1)
                        neutrality = (gc.neutrality_regression(per_gene["GC3"].values, per_gene["GC12"].values)
                                     if not per_gene.empty else {})

                    with st.spinner("Rendering figures..."):
                        composition_records = pd.DataFrame([{
                            "record_id": r.id, "length_bp": len(r.seq),
                            "gc_percent": gc.gc_percent(r.seq),
                            "entropy_bits": gc.shannon_entropy(r.seq),
                            **{f"count_{b}": gc.nucleotide_counts(r.seq).get(b, 0) for b in "ATGCN"},
                        } for r in parsed.records])
                        figs = {
                            "01_composition_overview": gf.fig_composition_overview(composition_records, theme1),
                            "02_skew_and_origin": gf.fig_skew_and_ori(window_df, ori_ter, main_rec.id, theme1),
                            "03_dinucleotide_oe": gf.fig_dinucleotide_oe(dinuc_df, theme1),
                            "04_assembly_curve": gf.fig_assembly_curve(lengths, assembly, theme1),
                            "05_rscu_heatmap": gf.fig_rscu_heatmap(usage),
                            "06_codon_bar": gf.fig_codon_bar(usage, theme1),
                            "07_amino_acid_usage": gf.fig_amino_acid_usage(aa_df, theme1),
                            "08_enc_plot": gf.fig_enc_plot(per_gene, theme1),
                            "09_neutrality_plot": gf.fig_neutrality_plot(per_gene, neutrality, theme1),
                            "10_pr2_plot": gf.fig_pr2_plot(per_gene, theme1),
                        }
                        if not feature_df.empty:
                            figs["11_feature_map"] = gf.fig_feature_map(feature_df, len(main_rec.seq), main_rec.id)

                    st.success(f"Analysis complete: {main_rec.id} ({len(main_rec.seq):,} bp, {len(parsed.records)} record(s))")
                    if parsed.notes:
                        st.info(" \u00b7 ".join(parsed.notes))

                    m1, m2, m3, m4 = st.columns(4)
                    m1.metric("GC%", f"{gc.gc_percent(main_rec.seq):.2f}")
                    m2.metric("CDS analysed", f"{len(cds_seqs):,}")
                    m3.metric("ENC (genome)", f"{gc.enc_from_counts(counts, ctx1):.2f}" if counts else "n/a")
                    m4.metric("N50 (bp)", f"{assembly.get('N50_bp', 0):,}")

                    fig_tabs = st.tabs(["Structure", "GC/skew", "Codon usage", "ENC/neutrality/PR2", "Tables"])
                    with fig_tabs[0]:
                        if "11_feature_map" in figs:
                            st.pyplot(figs["11_feature_map"])
                        st.pyplot(figs["04_assembly_curve"])
                    with fig_tabs[1]:
                        st.pyplot(figs["02_skew_and_origin"])
                        st.pyplot(figs["01_composition_overview"])
                        st.pyplot(figs["03_dinucleotide_oe"])
                        st.caption(
                            f"Predicted origin confidence: {ori_ter.get('ori_ter_confidence', 'n/a')} "
                            f"(signal-to-noise {ori_ter.get('ori_ter_signal_to_noise', float('nan')):.2f})"
                        )
                    with fig_tabs[2]:
                        st.pyplot(figs["05_rscu_heatmap"])
                        st.pyplot(figs["06_codon_bar"])
                        st.pyplot(figs["07_amino_acid_usage"])
                        st.caption(f"CAI weight source: {weight_source}. {weight_note}")
                    with fig_tabs[3]:
                        cc1, cc2, cc3 = st.columns(3)
                        cc1.pyplot(figs["08_enc_plot"])
                        cc2.pyplot(figs["09_neutrality_plot"])
                        cc3.pyplot(figs["10_pr2_plot"])
                    with fig_tabs[4]:
                        st.markdown("**Codon usage table**")
                        st.dataframe(usage, use_container_width=True, height=280)
                        st.markdown("**Per-gene codon metrics**")
                        st.dataframe(per_gene, use_container_width=True, height=280)
                        st.markdown("**Feature table**")
                        st.dataframe(feature_df, use_container_width=True, height=200)

                    png_figs = {f"{name}.png": fig_to_png_bytes(fig) for name, fig in figs.items()}
                    pdf_figs = {f"{name}.pdf": fig_to_vector_bytes(fig) for name, fig in figs.items()}
                    all_figs = {**png_figs, **pdf_figs}
                    tables_out = {
                        "codon_usage.csv": usage, "per_gene_metrics.csv": per_gene,
                        "amino_acid_usage.csv": aa_df, "feature_table.csv": feature_df,
                        "window_composition.csv": window_df, "dinucleotide_oe.csv": dinuc_df,
                        "per_record_composition.csv": composition_records,
                    }
                    bundle = build_zip(all_figs, tables_out, METHODS_NOTE)
                    st.download_button("Download complete results bundle (figures + tables + methods note)",
                                       data=bundle, file_name=f"{main_rec.id}_genomics_suite_results.zip",
                                       mime="application/zip", key="t1_download")
                    for fig in figs.values():
                        plt.close(fig)
            except Exception as exc:
                st.error(f"Analysis failed: {exc}")


# ============================================================================
# TOOL 2 - Gulumba Prokka annotation workbench
# (replaces app.py + genome_analysis.py + annotation_core.py)
# ============================================================================

with tab2:
    st.markdown("#### Prokka annotation workbench")
    st.caption(
        "Runs Prokka on an uploaded bacterial genome FASTA, then computes the same "
        "composition and codon-usage metrics as Tool 1 from the Prokka output, so "
        "results are directly comparable across tools."
    )

    if not ge.prokka_available():
        st.warning(
            "Prokka was not found on PATH in this environment. This tab will not run "
            "until Prokka is installed (e.g. `conda install -c bioconda -c conda-forge prokka`). "
            "Every other tool in this suite works without it."
        )

    genome_upload = st.file_uploader("Bacterial genome FASTA", type=["fa", "fasta", "fna", "fas"], key="t2_upload")
    cc1, cc2, cc3, cc4 = st.columns(4)
    with cc1:
        prefix = st.text_input("Sample prefix", value="sample_genome", key="t2_prefix")
    with cc2:
        genus = st.text_input("Genus", value="Escherichia", key="t2_genus")
    with cc3:
        species = st.text_input("Species", value="coli", key="t2_species")
    with cc4:
        cpus = st.number_input("CPUs", min_value=1, max_value=8, value=2, key="t2_cpus")

    ctx2 = genetic_code_selector("t2")
    theme2 = theme_selector("t2")
    run2 = st.button("Run Prokka annotation & analysis", type="primary", key="t2_run")

    if run2:
        if genome_upload is None:
            st.error("Please upload a genome FASTA file.")
        else:
            safe_prefix = "".join(c if c.isalnum() or c in "-_" else "_" for c in prefix).strip("_") or "sample_genome"
            job_dir = WORK_ROOT / f"prokka_{safe_prefix}"
            shutil.rmtree(job_dir, ignore_errors=True)
            job_dir.mkdir(parents=True, exist_ok=True)
            fasta_path = job_dir / f"{safe_prefix}.fasta"
            fasta_path.write_bytes(genome_upload.getvalue())

            with st.spinner("Running Prokka (this can take several minutes)..."):
                result = ge.run_prokka(fasta_path, job_dir / "prokka_out", safe_prefix, genus, species, int(cpus))

            with st.expander("Prokka log"):
                st.text(result["log"])

            if not result["success"]:
                st.error("Prokka did not complete successfully. See the log above for details.")
            else:
                if result["mode"] == "noanno":
                    st.warning(
                        "Full product-search annotation did not complete, so Prokka ran in "
                        "--noanno mode. Gene calls, coordinates, and every metric below are "
                        "still valid; CDS product names are simply unavailable."
                    )
                try:
                    with st.spinner("Loading Prokka output and computing metrics..."):
                        parsed = gp.read_prokka_outputs(result["outdir"], safe_prefix)
                        main_rec = max(parsed.records, key=lambda r: len(r.seq))
                        feature_df = parsed.tables.get(main_rec.id, gp.empty_feature_table())
                        lengths = [len(r.seq) for r in parsed.records]
                        assembly = gc.assembly_statistics(lengths)
                        window_df = gc.window_table(main_rec.seq, window=1000)
                        ori_ter = gc.predict_ori_ter(window_df)
                        cds_seqs = collect_cds_sequences(parsed.records, parsed.tables, 90)
                        counts = gc.aggregate_codon_counts(cds_seqs, ctx2)
                        stops = gc.stop_codon_counts(cds_seqs, ctx2)
                        weights, weight_source, weight_note = gc.build_cai_weights(ctx2, all_seqs=cds_seqs)
                        usage = gc.codon_usage_table(counts, ctx2, stops)
                        per_gene = gc.per_gene_codon_table(cds_seqs, ctx2, weights, min_codons=30)
                        aa_df = gc.amino_acid_usage(cds_seqs, ctx2)

                    st.success(f"Loaded {len(parsed.records)} contig(s), {len(feature_df)} annotated features on the largest contig.")
                    m1, m2, m3, m4 = st.columns(4)
                    m1.metric("Total length (bp)", f"{assembly.get('total_length_bp', 0):,}")
                    m2.metric("GC%", f"{gc.gc_percent(main_rec.seq):.2f}")
                    m3.metric("N50 (bp)", f"{assembly.get('N50_bp', 0):,}")
                    m4.metric("CDS analysed", f"{len(cds_seqs):,}")

                    figs2 = {
                        "01_feature_map": (gf.fig_feature_map(feature_df, len(main_rec.seq), main_rec.id)
                                          if not feature_df.empty else None),
                        "02_assembly_curve": gf.fig_assembly_curve(lengths, assembly, theme2),
                        "03_skew_and_origin": gf.fig_skew_and_ori(window_df, ori_ter, main_rec.id, theme2),
                        "04_rscu_heatmap": gf.fig_rscu_heatmap(usage),
                        "05_amino_acid_usage": gf.fig_amino_acid_usage(aa_df, theme2),
                    }
                    figs2 = {k: v for k, v in figs2.items() if v is not None}
                    for name, fig in figs2.items():
                        st.pyplot(fig)

                    st.markdown("**Feature table**")
                    st.dataframe(feature_df, use_container_width=True, height=240)
                    st.markdown("**Codon usage table**")
                    st.dataframe(usage, use_container_width=True, height=240)

                    png_figs = {f"{n}.png": fig_to_png_bytes(f) for n, f in figs2.items()}
                    bundle2 = build_zip(png_figs, {
                        "feature_table.csv": feature_df, "codon_usage.csv": usage,
                        "per_gene_metrics.csv": per_gene, "amino_acid_usage.csv": aa_df,
                    }, METHODS_NOTE)
                    st.download_button("Download annotation workbench results bundle", data=bundle2,
                                       file_name=f"{safe_prefix}_prokka_workbench_results.zip",
                                       mime="application/zip", key="t2_download")
                    for fig in figs2.values():
                        plt.close(fig)
                except Exception as exc:
                    st.error(f"Post-annotation analysis failed: {exc}")


# ============================================================================
# TOOL 3 - Gulumba Pan-genome analysis
# (replaces pangenome_core.py + the two Pan-Genome Gradio apps)
# ============================================================================

with tab3:
    st.markdown("#### Pan-genome analysis")
    st.caption(
        "Upload two or more genome FASTA files (or a ZIP of them, or one multi-FASTA "
        "file where each record is a separate genome). Genes are called with "
        "pyrodigal and clustered with CD-HIT into core, accessory, and unique sets, "
        "then the pan-genome's openness is estimated with Heaps' law and Tettelin-"
        "style accumulation curves."
    )

    if not ge.cd_hit_available():
        st.warning("cd-hit was not found on PATH. This tab needs CD-HIT installed to run.")

    pg_upload = st.file_uploader(
        "Multi-FASTA, or ZIP of genome FASTA files", type=["fa", "fasta", "fna", "fas", "zip"], key="t3_upload"
    )
    pc1, pc2, pc3 = st.columns(3)
    with pc1:
        identity = st.slider("Clustering identity threshold", 0.70, 1.00, 0.90, 0.01, key="t3_identity")
    with pc2:
        coverage = st.slider("Clustering coverage threshold", 0.50, 1.00, 0.80, 0.01, key="t3_coverage")
    with pc3:
        core_threshold = st.slider("Core gene threshold (fraction of genomes)", 0.80, 1.00, 1.00, 0.01, key="t3_core")

    theme3 = theme_selector("t3")
    accumulation_perms = st.number_input("Permutations for accumulation-curve resampling", min_value=10, max_value=1000, value=100, step=10, key="t3_perms")
    run3 = st.button("Run pan-genome analysis", type="primary", key="t3_run")

    if run3:
        if pg_upload is None:
            st.error("Please upload a multi-FASTA file or a ZIP of genome FASTA files.")
        else:
            job_dir = WORK_ROOT / "pangenome_job"
            shutil.rmtree(job_dir, ignore_errors=True)
            job_dir.mkdir(parents=True, exist_ok=True)
            genome_dir = job_dir / "genomes"
            genome_dir.mkdir(parents=True, exist_ok=True)

            try:
                # Split into one FASTA file per genome, from either a ZIP or a multi-FASTA
                genome_files = []
                if pg_upload.name.lower().endswith(".zip"):
                    with zipfile.ZipFile(io.BytesIO(pg_upload.getvalue())) as zf:
                        for info in zf.infolist():
                            if info.is_dir():
                                continue
                            name = os.path.basename(info.filename)
                            if os.path.splitext(name)[1].lower() not in {".fa", ".fasta", ".fna", ".fas"}:
                                continue
                            out_path = genome_dir / name
                            out_path.write_bytes(zf.read(info.filename))
                            genome_files.append(out_path)
                else:
                    records = gp.parse_fasta(pg_upload.getvalue())
                    for rec in records:
                        safe = "".join(c if c.isalnum() or c in "._-" else "_" for c in rec.id)
                        out_path = genome_dir / f"{safe}.fasta"
                        out_path.write_text(f">{rec.id}\n{rec.seq}\n")
                        genome_files.append(out_path)

                if len(genome_files) < 2:
                    st.error("At least two genomes are required for pan-genome analysis.")
                else:
                    genome_names = [f.stem for f in genome_files]
                    proteins_dir = job_dir / "predicted_proteins"
                    proteins_dir.mkdir(exist_ok=True)

                    with st.spinner(f"Calling genes in {len(genome_files)} genomes with pyrodigal..."):
                        protein_fastas = []
                        for genome_file, gname in zip(genome_files, genome_names):
                            out_faa = proteins_dir / f"{gname}.faa"
                            ge.predict_proteins(str(genome_file), str(out_faa), gname)
                            protein_fastas.append(out_faa)

                    pooled = job_dir / "all_proteins.faa"
                    with open(pooled, "w") as out:
                        for pf in protein_fastas:
                            out.write(pf.read_text())

                    with st.spinner("Clustering proteins with CD-HIT..."):
                        clstr_prefix = job_dir / "clusters"
                        clstr_file = ge.run_cd_hit(pooled, clstr_prefix, identity, coverage)
                        clusters = ge.parse_cd_hit_clusters(clstr_file)

                    presence, cluster_ids = ge.presence_absence_matrix(clusters, genome_names)
                    class_df = ge.classify_clusters(presence, cluster_ids, len(genome_names), core_threshold)
                    counts_cat = class_df["category"].value_counts().to_dict()

                    with st.spinner("Estimating pan-genome openness (Heaps' law + accumulation curves)..."):
                        accumulation = gc.pangenome_accumulation(presence, permutations=int(accumulation_perms))
                        heaps = gc.heaps_law_fit(accumulation)

                    st.success(
                        f"{len(genome_names)} genomes, {len(cluster_ids)} gene clusters: "
                        f"{counts_cat.get('core', 0)} core, {counts_cat.get('accessory', 0)} accessory, "
                        f"{counts_cat.get('unique', 0)} unique."
                    )
                    st.info(f"Pan-genome openness: {heaps.get('interpretation', 'n/a')} (Heaps' gamma = {heaps.get('gamma', float('nan')):.3f})")

                    fig_pie = gf.fig_pangenome_pie(counts_cat, theme3)
                    fig_curves = gf.fig_pangenome_curves(accumulation, heaps, theme3)
                    fig_pa = gf.fig_presence_absence(presence, genome_names)

                    pt1, pt2, pt3 = st.columns(3)
                    pt1.pyplot(fig_pie)
                    pt2.pyplot(fig_curves)
                    st.pyplot(fig_pa)

                    st.markdown("**Cluster classification**")
                    st.dataframe(class_df, use_container_width=True, height=280)

                    presence_df = pd.DataFrame(presence, columns=genome_names)
                    presence_df.insert(0, "cluster_id", cluster_ids)

                    figs3 = {"pangenome_pie.png": fig_to_png_bytes(fig_pie),
                            "pangenome_accumulation_curves.png": fig_to_png_bytes(fig_curves),
                            "presence_absence_matrix.png": fig_to_png_bytes(fig_pa)}
                    tables3 = {"cluster_classification.csv": class_df,
                              "presence_absence_matrix.csv": presence_df,
                              "accumulation_curve.csv": accumulation,
                              "heaps_law_fit.csv": pd.DataFrame([heaps])}
                    bundle3 = build_zip(figs3, tables3, METHODS_NOTE)
                    st.download_button("Download pan-genome results bundle", data=bundle3,
                                       file_name="pangenome_results.zip", mime="application/zip", key="t3_download")
                    for fig in (fig_pie, fig_curves, fig_pa):
                        plt.close(fig)
            except Exception as exc:
                st.error(f"Pan-genome analysis failed: {exc}")


# ============================================================================
# TOOL 4 - Gulumba Comparative genomics
# (replaces comparative_core.py + its Streamlit app; adds an alignment-free
#  mode for anything too large for pairwise Needleman-Wunsch alignment)
# ============================================================================

with tab4:
    st.markdown("#### Comparative genomics")
    st.caption(
        "Two modes. 'Alignment-free' (recommended default) uses MinHash/Mash "
        "sketching and scales to whole bacterial genomes and beyond. 'Detailed "
        "pairwise alignment' reuses the original Needleman-Wunsch approach, which "
        "gives base-level identity and conserved-region detail but only scales to "
        "genes, plasmids, amplicons, and other short sequences (a handful of Mb at "
        "most before memory and runtime become impractical)."
    )

    comp_files = st.file_uploader(
        "Two or more genome FASTA files", type=["fa", "fasta", "fna", "fas"],
        accept_multiple_files=True, key="t4_upload",
    )
    mode = st.radio(
        "Comparison mode",
        ["Alignment-free (Mash distance + ANI + tree)", "Detailed pairwise alignment (small sequences only)"],
        index=0, key="t4_mode",
    )

    if mode.startswith("Alignment-free"):
        k = st.slider("k-mer size", 11, 31, 21, 2, key="t4_k")
        sketch_size = st.slider("Sketch size (larger = more accurate, slower)", 200, 5000, 2000, 100, key="t4_sketch")
    else:
        min_conserved = st.number_input("Minimum conserved region length (bp)", min_value=5, max_value=10000, value=20, key="t4_minconserved")
        st.warning(
            "Pairwise alignment cost grows with the product of every pair of sequence "
            "lengths. Two 5 Mb bacterial chromosomes means roughly 25 x 10^12 alignment "
            "cells, which will exhaust memory. Use this mode for genes, plasmids, "
            "amplicons, or other short sequences; use alignment-free mode for whole "
            "genomes."
        )

    run4 = st.button("Run comparative analysis", type="primary", key="t4_run")

    if run4:
        if not comp_files or len(comp_files) < 2:
            st.error("Please upload at least 2 genome FASTA files.")
        else:
            try:
                genomes = []
                for f in comp_files:
                    recs = gp.parse_fasta(f.getvalue())
                    if not recs:
                        st.warning(f"No sequences found in {f.name}; skipped.")
                        continue
                    combined = "".join(r.seq for r in recs)
                    genomes.append((Path(f.name).stem, combined))

                if len(genomes) < 2:
                    st.error("At least two valid genomes are required.")
                else:
                    if mode.startswith("Alignment-free"):
                        with st.spinner(f"Sketching {len(genomes)} genomes (k={k})..."):
                            sketches = {name: gc.kmer_sketch(seq, k=int(k), sketch_size=int(sketch_size))[0]
                                       for name, seq in genomes}
                        with st.spinner("Computing pairwise Mash distance and ANI..."):
                            dist_df, ani_df = gc.distance_matrix_from_sketches(sketches, k=int(k))
                        with st.spinner("Building neighbour-joining tree..."):
                            newick = gc.neighbor_joining_newick(dist_df)

                        st.success(f"Compared {len(genomes)} genomes using alignment-free Mash sketching.")
                        fig_ani = gf.fig_distance_heatmap(ani_df, "Estimated ANI (%)", "ANI (%)", cmap="viridis")
                        st.pyplot(fig_ani)
                        st.markdown("**Estimated ANI matrix**")
                        st.dataframe(ani_df.round(3), use_container_width=True)
                        st.markdown("**Mash distance matrix**")
                        st.dataframe(dist_df.round(5), use_container_width=True)
                        st.markdown("**Neighbour-joining tree (Newick)**")
                        st.code(newick, language="text")
                        st.caption(
                            "ANI here is estimated from Mash distance (Ondov et al. 2016), not from "
                            "a base-level alignment. Treat values below ~90% ANI as a coarse ranking "
                            "rather than a precise identity - the approximation degrades as sequences "
                            "diverge further."
                        )

                        figs4 = {"ani_heatmap.png": fig_to_png_bytes(fig_ani)}
                        tables4 = {"ani_matrix.csv": ani_df, "mash_distance_matrix.csv": dist_df}
                        readme4 = METHODS_NOTE + f"\n\nNeighbour-joining tree (Newick format):\n{newick}\n"
                        bundle4 = build_zip(figs4, tables4, readme4)
                        st.download_button("Download comparative genomics results bundle", data=bundle4,
                                           file_name="comparative_genomics_alignment_free_results.zip",
                                           mime="application/zip", key="t4_download_af")
                        plt.close(fig_ani)
                    else:
                        # Detailed pairwise mode: only sound for short sequences. Guard against
                        # accidentally running it on whole genomes, which would hang or exhaust
                        # memory rather than failing with a clear message.
                        total_cells = 0
                        n = len(genomes)
                        for i in range(n):
                            for j in range(i + 1, n):
                                total_cells += len(genomes[i][1]) * len(genomes[j][1])
                        if total_cells > 200_000_000:
                            st.error(
                                f"This comparison would require on the order of {total_cells:,} "
                                "alignment cells, which is too large for pairwise alignment in this "
                                "environment. Switch to alignment-free mode for genomes this size."
                            )
                        else:
                            from Bio import pairwise2  # only needed for this specific mode

                            def compute_identity(a, b):
                                comparable = matches = 0
                                for x, y in zip(a, b):
                                    if x == "-" and y == "-":
                                        continue
                                    comparable += 1
                                    if x == y:
                                        matches += 1
                                return round(100.0 * matches / comparable, 2) if comparable else 0.0

                            with st.spinner("Running pairwise alignments..."):
                                names = [g[0] for g in genomes]
                                mat = np.zeros((n, n))
                                for i in range(n):
                                    mat[i, i] = 100.0
                                for i in range(n):
                                    for j in range(i + 1, n):
                                        aln = pairwise2.align.globalms(
                                            genomes[i][1], genomes[j][1], 2, -1, -5, -0.5, one_alignment_only=True
                                        )[0]
                                        ident = compute_identity(aln.seqA, aln.seqB)
                                        mat[i, j] = mat[j, i] = ident
                                identity_df = pd.DataFrame(mat, index=names, columns=names)

                            st.success(f"Pairwise alignment complete for {n} sequences.")
                            fig_id = gf.fig_distance_heatmap(identity_df, "Pairwise % identity", "% identity", cmap="viridis")
                            st.pyplot(fig_id)
                            st.dataframe(identity_df.round(2), use_container_width=True)

                            figs4b = {"pairwise_identity_heatmap.png": fig_to_png_bytes(fig_id)}
                            tables4b = {"pairwise_identity_matrix.csv": identity_df}
                            bundle4b = build_zip(figs4b, tables4b, METHODS_NOTE)
                            st.download_button("Download comparative genomics results bundle", data=bundle4b,
                                               file_name="comparative_genomics_pairwise_results.zip",
                                               mime="application/zip", key="t4_download_pw")
                            plt.close(fig_id)
            except Exception as exc:
                st.error(f"Comparative analysis failed: {exc}")


st.markdown("---")
st.caption(
    "Gulumba Genomics Suite v1.0. All statistics are computed once in genomics_core.py "
    "and shared across every tool above, so a GC% or ENC value means the same thing "
    "everywhere it appears in this app."
)