Spaces:
Build error
Build error
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196import ioimport zipfilefrom pathlib import Path
import matplotlib.pyplot as pltimport pandas as pdimport streamlit as st
from comparative_core import ( analyze_genomes, read_fasta_file, dataframe_to_csv_bytes, plot_identity_heatmap, conserved_regions_to_dataframe, snp_matrix_to_dataframe,)
st.set_page_config( page_title="Genome Comparative Analysis Tool", page_icon="🧬", layout="wide",)
st.title("🧬 Genome Comparative Analysis Tool")st.markdown( """Upload **2 or more genome FASTA files** to compare them.
### Outputs- **Pairwise % similarity**- **Conserved regions**- **SNP differences**
### Best useThis tool works best for:- viral genomes- plasmids- amplicons- genes- small microbial contigs- closely related genomes
### Notes- The **first uploaded genome** is used as the **reference** for conserved-region and SNP reporting.- Sequences are converted to uppercase and cleaned before analysis.- If genomes differ greatly in size or structure, the comparison may be less informative.""")
with st.sidebar: st.header("Settings") min_conserved_length = st.number_input( "Minimum conserved region length", min_value=5, max_value=10000, value=20, step=1, help="Only conserved regions with at least this number of consecutive identical positions are reported.", ) st.caption("Tip: use 10–30 for short genomes, 50–200 for longer sequences.")
uploaded_files = st.file_uploader( "Upload FASTA files", type=["fa", "fasta", "fna", "fas", "txt"], accept_multiple_files=True,)
run_analysis = st.button("Run Comparative Analysis", type="primary")clear_results = st.button("Clear")
if clear_results: st.rerun()
if run_analysis: if not uploaded_files or len(uploaded_files) < 2: st.error("Please upload at least 2 FASTA files.") st.stop()
genomes = [] errors = []
for uploaded in uploaded_files: try: seq_name, seq = read_fasta_file(uploaded) genomes.append((seq_name, seq)) except Exception as exc: errors.append(f"{uploaded.name}: {exc}")
if errors: st.error("Some files could not be processed:") for e in errors: st.write(f"- {e}") st.stop()
names = [x[0] for x in genomes] sequences = [x[1] for x in genomes]
if len(set(names)) != len(names): st.warning( "Duplicate genome names detected. File names will be used to distinguish results." ) genomes = [(f"{uploaded_files[i].name}", sequences[i]) for i in range(len(sequences))] names = [x[0] for x in genomes]
with st.spinner("Running genome comparison..."): results = analyze_genomes( genomes=genomes, min_conserved_length=min_conserved_length, )
st.success("Analysis completed.")
# Summary st.subheader("Summary") summary_col1, summary_col2, summary_col3 = st.columns(3) with summary_col1: st.metric("Genomes compared", len(genomes)) with summary_col2: st.metric("Reference genome", results["reference_name"]) with summary_col3: st.metric("Reference length", f"{results['reference_length']:,} bp")
# Pairwise identity matrix st.subheader("Pairwise % Similarity") identity_df = results["identity_df"] st.dataframe(identity_df, use_container_width=True)
fig = plot_identity_heatmap(identity_df) st.pyplot(fig, clear_figure=True)
# Conserved regions st.subheader("Conserved Regions") conserved_df = conserved_regions_to_dataframe(results["conserved_regions"]) if conserved_df.empty: st.info("No conserved regions met the selected minimum length.") else: st.dataframe(conserved_df, use_container_width=True)
# SNP summary st.subheader("SNP Differences Relative to Reference") snp_summary_df = results["snp_summary_df"] st.dataframe(snp_summary_df, use_container_width=True)
# Detailed SNP tables st.subheader("Detailed SNP Tables") detailed_snp_tables = results["detailed_snp_tables"] for genome_name, snp_df in detailed_snp_tables.items(): with st.expander(f"SNPs: {genome_name} vs {results['reference_name']}"): if snp_df.empty: st.write("No SNPs detected.") else: st.dataframe(snp_df, use_container_width=True)
# Multi-genome variable sites st.subheader("Variable Sites Across All Genomes") variable_sites_df = snp_matrix_to_dataframe(results["multi_variable_sites"]) if variable_sites_df.empty: st.info("No variable sites found across all aligned genomes.") else: st.dataframe(variable_sites_df, use_container_width=True)
# Downloads st.subheader("Download Results")
zip_buffer = io.BytesIO() with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf: zf.writestr("pairwise_similarity.csv", dataframe_to_csv_bytes(identity_df)) zf.writestr("conserved_regions.csv", dataframe_to_csv_bytes(conserved_df)) zf.writestr("snp_summary.csv", dataframe_to_csv_bytes(snp_summary_df))
for genome_name, snp_df in detailed_snp_tables.items(): safe_name = genome_name.replace(" ", "_").replace("/", "_") zf.writestr( f"snps_{safe_name}.csv", dataframe_to_csv_bytes(snp_df), )
multi_sites_df = snp_matrix_to_dataframe(results["multi_variable_sites"]) zf.writestr("variable_sites_all_genomes.csv", dataframe_to_csv_bytes(multi_sites_df))
# save heatmap heatmap_bytes = io.BytesIO() fig2 = plot_identity_heatmap(identity_df) fig2.savefig(heatmap_bytes, format="png", dpi=300, bbox_inches="tight") plt.close(fig2) heatmap_bytes.seek(0) zf.writestr("pairwise_similarity_heatmap.png", heatmap_bytes.read())
zip_buffer.seek(0)
st.download_button( label="Download all results as ZIP", data=zip_buffer, file_name="genome_comparative_analysis_results.zip", mime="application/zip", )app.pyAdded+196