Upload 2 files
Browse filesFiles changed (2)
- app.py+1012-289
- requirements.txt+5-5
1234567891011121314151617181920212223242526272829303132331 unmodified line35363738394041424344454647484950515253545556575859606162636465666768697071721 unmodified line74757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241 unmodified line1261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143152 unmodified lines318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425import ioimport reimport tempfileimport subprocessimport numpy as npfrom pathlib import Pathimport streamlit as stimport pandas as pdimport matplotlib.pyplot as pltfrom Bio import SeqIO, Phylofrom Bio.Seq import Seqfrom Bio.SeqRecord import SeqRecordAPP_TITLE = "Phylogenetic Tree Builder"APP_SUBTITLE = "Build publication-ready phylogenetic trees from FASTA sequences"ALLOWED_CHARS = set("ACGTURYSWKMBDHVN-")def init_session_state():defaults = {"result_ready": False,"summary_df": None,"tree_png_bytes": None,"tree_newick_text": None,"aligned_fasta_text": None,"error_messages": [],"success_message": "",}for k, v in defaults.items():if k not in st.session_state:1 unmodified linedef clear_results():keys_to_clear = ["result_ready","summary_df","tree_png_bytes","tree_newick_text","aligned_fasta_text","error_messages","success_message",]for k in keys_to_clear:if k in st.session_state:if k == "result_ready":st.session_state[k] = Falseelif k == "error_messages":st.session_state[k] = []elif k == "success_message":st.session_state[k] = ""else:st.session_state[k] = Nonedef clean_header(header: str) -> str:return re.sub(r"\s+", "_", header.strip())def validate_fasta_records(records):errors = []cleaned = []if len(records) < 2:errors.append("At least 2 sequences are required to build a phylogenetic tree.")return cleaned, errorsseen_ids = set()for i, rec in enumerate(records, start=1):1 unmodified lineseq_str = str(rec.seq).upper().replace(" ", "").replace("\n", "")if not seq_str:errors.append(f"Sequence {seq_id} is empty.")continuebad_chars = set(seq_str) - ALLOWED_CHARSif bad_chars:errors.append(f"Sequence {seq_id} contains invalid characters: {', '.join(sorted(bad_chars))}")continueif seq_id in seen_ids:seq_id = f"{seq_id}_{i}"seen_ids.add(seq_id)cleaned.append(SeqRecord(Seq(seq_str), id=seq_id, description=""))if len(cleaned) < 2:errors.append("After validation, fewer than 2 valid sequences remain.")return cleaned, errorsdef parse_fasta_text(text: str):handle = io.StringIO(text)return list(SeqIO.parse(handle, "fasta"))def save_fasta(records, path: Path):with open(path, "w") as handle:SeqIO.write(records, handle, "fasta")def run_command(cmd, cwd=None):result = subprocess.run(cmd,cwd=cwd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)return result.returncode, result.stdout, result.stderrdef run_mafft(input_fasta: Path, output_fasta: Path):cmd = ["mafft", "--auto", str(input_fasta)]code, stdout, stderr = run_command(cmd)if code != 0:raise RuntimeError(f"MAFFT failed:\n{stderr}")1 unmodified linereturn output_fastadef run_fasttree(aligned_fasta: Path, output_tree: Path, nucleotide=True):if nucleotide:cmd = ["FastTree", "-nt", str(aligned_fasta)]else:cmd = ["FastTree", str(aligned_fasta)]code, stdout, stderr = run_command(cmd)if code != 0:raise RuntimeError(f"FastTree failed:\n{stderr}")output_tree.write_text(stdout, encoding="utf-8")return output_treedef dataframe_from_records(records):return pd.DataFrame({"Sequence_ID": [r.id for r in records],"Length": [len(r.seq) for r in records],})def draw_tree_rectangular(tree, image_file: Path, figure_width=12, figure_height=8, dpi=300):fig = plt.figure(figsize=(figure_width, figure_height), dpi=dpi)ax = fig.add_subplot(1, 1, 1)Phylo.draw(tree, axes=ax, do_show=False)plt.tight_layout()fig.savefig(image_file, bbox_inches="tight")plt.close(fig)def _get_terminals_in_order(tree):return tree.get_terminals()def draw_tree_circular(tree, image_file: Path, figure_width=10, figure_height=10, dpi=300):terminals = _get_terminals_in_order(tree)n = len(terminals)if n < 2:raise RuntimeError("Circular tree requires at least 2 terminal sequences.")depths = tree.depths()if not max(depths.values()):depths = tree.depths(unit_branch_lengths=True)term_angle = {term: 2 * plt.pi * i / n for i, term in enumerate(terminals)}def clade_angle(clade):if clade.is_terminal():return term_angle[clade]child_angles = [clade_angle(c) for c in clade.clades]return sum(child_angles) / len(child_angles)fig = plt.figure(figsize=(figure_width, figure_height), dpi=dpi)ax = fig.add_subplot(111, projection="polar")ax.set_theta_direction(-1)ax.set_theta_offset(plt.pi / 2)ax.set_axis_off()def draw_clade(clade, parent_radius=0.0, parent_angle=None):radius = depths.get(clade, 0.0)angle = clade_angle(clade)if parent_angle is not None:ax.plot([parent_angle, parent_angle], [parent_radius, radius], lw=1.2)if len(clade.clades) > 0:child_angles = [clade_angle(c) for c in clade.clades]ax.plot([min(child_angles), max(child_angles)],[radius, radius],lw=1.2)if clade.is_terminal():label = clade.name if clade.name else ""ax.text(angle,radius + max(depths.values()) * 0.05,label,fontsize=8,ha="center",va="center")for child in clade.clades:draw_clade(child, parent_radius=radius, parent_angle=clade_angle(child))root = tree.rootdraw_clade(root, parent_radius=0.0, parent_angle=None)plt.tight_layout()fig.savefig(image_file, bbox_inches="tight")plt.close(fig)def draw_tree_unrooted(tree, image_file: Path, figure_width=10, figure_height=10, dpi=300):fig = plt.figure(figsize=(figure_width, figure_height), dpi=dpi)ax = fig.add_subplot(1, 1, 1)try:Phylo.draw_graphviz(tree, prog="neato", axes=ax, do_show=False)except Exception:# fallback to standard drawing if graphviz-style unrooted rendering is unavailablePhylo.draw(tree, axes=ax, do_show=False)plt.tight_layout()fig.savefig(image_file, bbox_inches="tight")plt.close(fig)def draw_tree_layout(tree_file: Path, image_file: Path, layout: str, figure_width=12, figure_height=8, dpi=300):tree = Phylo.read(str(tree_file), "newick")if layout == "Rectangular":draw_tree_rectangular(tree, image_file, figure_width, figure_height, dpi)elif layout == "Circular":draw_tree_circular(tree, image_file, figure_width, figure_height, dpi)elif layout == "Unrooted":draw_tree_unrooted(tree, image_file, figure_width, figure_height, dpi)else:draw_tree_rectangular(tree, image_file, figure_width, figure_height, dpi)return image_filedef render_persisted_results():if st.session_state.get("error_messages"):for err in st.session_state["error_messages"]:st.error(err)if st.session_state.get("success_message"):st.success(st.session_state["success_message"])if st.session_state.get("summary_df") is not None:st.subheader("Sequence summary")st.dataframe(st.session_state["summary_df"], use_container_width=True)if st.session_state.get("tree_png_bytes") is not None:st.subheader("Tree visualization")st.image(st.session_state["tree_png_bytes"], caption="Phylogenetic tree", use_container_width=True)if (st.session_state.get("tree_newick_text") is not Noneor st.session_state.get("aligned_fasta_text") is not Noneor st.session_state.get("tree_png_bytes") is not None):st.subheader("Download outputs")col1, col2, col3 = st.columns(3)with col1:if st.session_state.get("tree_newick_text") is not None:st.download_button(label="Download Newick tree",data=st.session_state["tree_newick_text"],file_name="tree.nwk",mime="text/plain",key="download_newick")with col2:if st.session_state.get("aligned_fasta_text") is not None:st.download_button(label="Download aligned FASTA",data=st.session_state["aligned_fasta_text"],file_name="aligned.fasta",mime="text/plain",key="download_aligned")with col3:if st.session_state.get("tree_png_bytes") is not None:st.download_button(label="Download tree image (PNG)",data=st.session_state["tree_png_bytes"],file_name="tree.png",mime="image/png",key="download_png")if st.session_state.get("tree_newick_text") is not None:st.subheader("Newick tree")st.code(st.session_state["tree_newick_text"], language="text")def main():st.set_page_config(page_title=APP_TITLE, layout="wide")2 unmodified linesst.title(APP_TITLE)st.caption(APP_SUBTITLE)st.markdown("""This tool:- validates uploaded FASTA sequences- performs multiple sequence alignment with **MAFFT**- builds a phylogenetic tree with **FastTree**- exports **Newick**, aligned FASTA, and a publication-style PNG image- supports **Rectangular**, **Circular**, and **Unrooted** tree layouts""")with st.sidebar:st.header("Settings")seq_type = st.radio("Sequence type", ["Nucleotide", "Protein"], index=0)tree_layout = st.selectbox("Tree layout",["Rectangular", "Circular", "Unrooted"],index=0)figure_width = st.slider("Figure width", 8, 20, 12)figure_height = st.slider("Figure height", 6, 20, 8)dpi = st.selectbox("Image DPI", [150, 300, 600], index=1)st.subheader("Input sequences")uploaded_file = st.file_uploader("Upload FASTA file",type=["fasta", "fa", "fna", "faa", "txt"])fasta_text = st.text_area("Or paste FASTA sequences here", height=220)col_run, col_clear = st.columns([3, 1])with col_run:run_clicked = st.button("Build Phylogenetic Tree", type="primary", use_container_width=True)with col_clear:st.button("Clear", use_container_width=True, on_click=clear_results)if run_clicked:clear_results()try:raw_records = []if uploaded_file is not None:content = uploaded_file.read().decode("utf-8", errors="ignore")raw_records.extend(parse_fasta_text(content))if fasta_text.strip():raw_records.extend(parse_fasta_text(fasta_text))if not raw_records:st.session_state["error_messages"] = ["Please upload or paste FASTA sequences."]render_persisted_results()returnrecords, errors = validate_fasta_records(raw_records)if errors:st.session_state["error_messages"] = errorsrender_persisted_results()returnst.session_state["success_message"] = f"{len(records)} valid sequences detected."st.session_state["summary_df"] = dataframe_from_records(records)with tempfile.TemporaryDirectory() as tmpdir:tmpdir = Path(tmpdir)input_fasta = tmpdir / "input.fasta"aligned_fasta = tmpdir / "aligned.fasta"tree_file = tmpdir / "tree.nwk"image_file = tmpdir / "tree.png"save_fasta(records, input_fasta)with st.spinner("Running multiple sequence alignment with MAFFT..."):run_mafft(input_fasta, aligned_fasta)with st.spinner("Building phylogenetic tree with FastTree..."):run_fasttree(aligned_fasta,tree_file,nucleotide=(seq_type == "Nucleotide"))with st.spinner("Rendering tree image..."):draw_tree_layout(tree_file,image_file,layout=tree_layout,figure_width=figure_width,figure_height=figure_height,dpi=dpi)st.session_state["aligned_fasta_text"] = aligned_fasta.read_text(encoding="utf-8")st.session_state["tree_newick_text"] = tree_file.read_text(encoding="utf-8")st.session_state["tree_png_bytes"] = image_file.read_bytes()st.session_state["result_ready"] = Trueexcept Exception as e:st.session_state["error_messages"] = [f"Pipeline failed: {e}"]render_persisted_results()if __name__ == "__main__":main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021 unmodified line1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491 unmodified line1511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652661 unmodified line2682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210232 unmodified lines102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148"""PhyloForgeA Streamlit application for building publication-quality phylogenetic treesfrom FASTA sequences.Pipeline:1. Parse and validate FASTA input (nucleotide or protein)2. Compute per-sequence statistics3. Multiple sequence alignment (MAFFT, MUSCLE, or Clustal Omega)4. Alignment statistics and conservation profile5. Pairwise distance matrix6. Tree building (FastTree, IQ-TREE, Neighbor-Joining, or UPGMA)7. Optional midpoint rooting8. Tree visualisation (rectangular, circular, radial/unrooted) with colour9. Supporting figures (distance heatmap, composition, conservation)10. Export of trees, alignments, tables, and figures in several formatsExternal aligners and tree builders are called through subprocess. They must beinstalled in the runtime (see packages.txt for HuggingFace Spaces). Neighbor-Joiningand UPGMA run in pure Python through Biopython and need no external tools."""import ioimport reimport mathimport shutilimport tempfileimport subprocessfrom pathlib import Pathfrom collections import Counterimport numpy as npimport pandas as pdimport matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltimport streamlit as stfrom Bio import SeqIO, Phylo, AlignIOfrom Bio.Seq import Seqfrom Bio.SeqRecord import SeqRecordfrom Bio.Align import MultipleSeqAlignmentfrom Bio.Phylo.TreeConstruction import DistanceCalculator, DistanceTreeConstructor# ----------------------------------------------------------------------------# Constants# ----------------------------------------------------------------------------APP_TITLE = "PhyloForge"APP_SUBTITLE = "Publication-quality phylogenetic analysis from FASTA sequences"NUC_CHARS = set("ACGTURYSWKMBDHVN-")PROT_CHARS = set("ACDEFGHIKLMNPQRSTVWYBZXJUO*-")# Named qualitative palettes for tip and clade colouring.QUALITATIVE_PALETTES = {"Vibrant": ["#e6194B", "#3cb44b", "#4363d8", "#f58231", "#911eb4","#42d4f4", "#f032e6", "#bfef45", "#fabed4", "#469990","#dcbeff", "#9A6324", "#800000", "#aaffc3", "#808000"],"Pastel": ["#66c2a5", "#fc8d62", "#8da0cb", "#e78ac3", "#a6d854","#ffd92f", "#e5c494", "#b3b3b3", "#a6cee3", "#fdbf6f"],"Dark": ["#1b9e77", "#d95f02", "#7570b3", "#e7298a", "#66a61e","#e6ab02", "#a6761d", "#666666", "#1f78b4", "#b15928"],"Ocean": ["#003f5c", "#2f4b7c", "#665191", "#a05195", "#d45087","#f95d6a", "#ff7c43", "#ffa600", "#2c7fb8", "#41b6c4"],"Earth": ["#582f0e", "#7f4f24", "#936639", "#a68a64", "#b6ad90","#c2c5aa", "#a4ac86", "#656d4a", "#414833", "#333d29"],}# Continuous colormaps for heatmaps and support-value colouring.CONTINUOUS_MAPS = ["viridis", "plasma", "magma", "cividis", "mako","rocket", "coolwarm", "YlGnBu", "RdYlBu", "Spectral"]# Distance models offered for NJ and UPGMA, by sequence type.NUC_DISTANCE_MODELS = ["identity", "blastn", "trans"]PROT_DISTANCE_MODELS = ["identity", "blosum62", "pam250", "dayhoff","gonnet", "johnson", "jones"]# ----------------------------------------------------------------------------# Session state# ----------------------------------------------------------------------------def init_session_state():defaults = {"result_ready": False,"errors": [],"success": "","warnings": [],"seq_summary_df": None,"composition_df": None,"align_stats_df": None,"distance_df": None,"aligned_fasta_text": None,"newick_text": None,"figures": {}, # name -> {"png": bytes, "svg": str, "pdf": bytes}"method_text": None, # auto-generated methods paragraph}for k, v in defaults.items():if k not in st.session_state:1 unmodified linedef clear_results():st.session_state["result_ready"] = Falsest.session_state["errors"] = []st.session_state["success"] = ""st.session_state["warnings"] = []st.session_state["seq_summary_df"] = Nonest.session_state["composition_df"] = Nonest.session_state["align_stats_df"] = Nonest.session_state["distance_df"] = Nonest.session_state["aligned_fasta_text"] = Nonest.session_state["newick_text"] = Nonest.session_state["figures"] = {}st.session_state["method_text"] = None# ----------------------------------------------------------------------------# FASTA parsing and validation# ----------------------------------------------------------------------------def clean_header(header: str) -> str:h = re.sub(r"\s+", "_", header.strip())h = re.sub(r"[^\w\.\-|]", "_", h)return h or "seq"def parse_fasta_text(text: str):handle = io.StringIO(text)return list(SeqIO.parse(handle, "fasta"))def validate_records(records, seq_type: str):"""Return cleaned records, a list of hard errors, and a list of soft warnings."""errors = []warnings = []cleaned = []allowed = NUC_CHARS if seq_type == "Nucleotide" else PROT_CHARSif len(records) < 3:errors.append("At least 3 sequences are required to build a meaningful tree.")return cleaned, errors, warningsseen_ids = set()for i, rec in enumerate(records, start=1):1 unmodified lineseq_str = str(rec.seq).upper().replace(" ", "").replace("\n", "")if not seq_str:warnings.append(f"Sequence {seq_id} is empty and was skipped.")continuebad_chars = set(seq_str) - allowedif bad_chars:errors.append(f"Sequence {seq_id} contains characters not valid for {seq_type}: "f"{', '.join(sorted(bad_chars))}")continueif seq_id in seen_ids:new_id = f"{seq_id}_{i}"warnings.append(f"Duplicate label {seq_id} renamed to {new_id}.")seq_id = new_idseen_ids.add(seq_id)cleaned.append(SeqRecord(Seq(seq_str), id=seq_id, description=""))if len(cleaned) < 3:errors.append("After validation, fewer than 3 valid sequences remain.")return cleaned, errors, warnings# ----------------------------------------------------------------------------# Sequence statistics# ----------------------------------------------------------------------------def gc_content(seq: str) -> float:s = seq.upper()gc = s.count("G") + s.count("C")valid = sum(s.count(b) for b in "ACGTU")return round(100.0 * gc / valid, 2) if valid else 0.0def ambiguous_count(seq: str, seq_type: str) -> int:s = seq.upper()if seq_type == "Nucleotide":unambig = set("ACGTU-")else:unambig = set("ACDEFGHIKLMNPQRSTVWY-")return sum(1 for c in s if c not in unambig)def sequence_summary(records, seq_type: str) -> pd.DataFrame:rows = []for r in records:s = str(r.seq)row = {"Sequence_ID": r.id,"Length": len(s),"Ambiguous": ambiguous_count(s, seq_type),}if seq_type == "Nucleotide":row["GC_percent"] = gc_content(s)rows.append(row)return pd.DataFrame(rows)def composition_table(records, seq_type: str) -> pd.DataFrame:"""Per-sequence character composition as percentages."""if seq_type == "Nucleotide":cols = list("ACGT")else:cols = list("ACDEFGHIKLMNPQRSTVWY")rows = []for r in records:s = str(r.seq).upper()total = sum(s.count(c) for c in cols)row = {"Sequence_ID": r.id}for c in cols:row[c] = round(100.0 * s.count(c) / total, 2) if total else 0.0rows.append(row)return pd.DataFrame(rows)# ----------------------------------------------------------------------------# Alignment# ----------------------------------------------------------------------------def which_first(names):for n in names:path = shutil.which(n)if path:return pathreturn Nonedef run_command(cmd, cwd=None, stdin_text=None):result = subprocess.run(cmd, cwd=cwd, input=stdin_text,stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,)return result.returncode, result.stdout, result.stderrdef run_mafft(input_fasta: Path, output_fasta: Path, strategy: str):binary = which_first(["mafft"])if not binary:raise RuntimeError("MAFFT is not installed in this runtime.")strategy_flags = {"Auto": ["--auto"],"FFT-NS-2 (fast)": ["--retree", "2"],"L-INS-i (accurate, local)": ["--localpair", "--maxiterate", "1000"],"G-INS-i (accurate, global)": ["--globalpair", "--maxiterate", "1000"],"E-INS-i (multi-domain)": ["--genafpair", "--maxiterate", "1000"],}flags = strategy_flags.get(strategy, ["--auto"])cmd = [binary] + flags + [str(input_fasta)]code, stdout, stderr = run_command(cmd)if code != 0:raise RuntimeError(f"MAFFT failed:\n{stderr}")1 unmodified linereturn output_fastadef run_muscle(input_fasta: Path, output_fasta: Path):binary = which_first(["muscle"])if not binary:raise RuntimeError("MUSCLE is not installed in this runtime.")# Try MUSCLE v5 syntax first, then fall back to v3.cmd_v5 = [binary, "-align", str(input_fasta), "-output", str(output_fasta)]code, stdout, stderr = run_command(cmd_v5)if code == 0 and output_fasta.exists():return output_fastacmd_v3 = [binary, "-in", str(input_fasta), "-out", str(output_fasta)]code, stdout, stderr = run_command(cmd_v3)if code != 0:raise RuntimeError(f"MUSCLE failed:\n{stderr}")return output_fastadef run_clustalo(input_fasta: Path, output_fasta: Path):binary = which_first(["clustalo"])if not binary:raise RuntimeError("Clustal Omega is not installed in this runtime.")cmd = [binary, "-i", str(input_fasta), "-o", str(output_fasta),"--outfmt=fasta", "--force"]code, stdout, stderr = run_command(cmd)if code != 0:raise RuntimeError(f"Clustal Omega failed:\n{stderr}")return output_fastadef run_alignment(aligner: str, strategy: str, input_fasta: Path, output_fasta: Path):if aligner == "MAFFT":return run_mafft(input_fasta, output_fasta, strategy)if aligner == "MUSCLE":return run_muscle(input_fasta, output_fasta)if aligner == "Clustal Omega":return run_clustalo(input_fasta, output_fasta)raise RuntimeError(f"Unknown aligner: {aligner}")# ----------------------------------------------------------------------------# Alignment statistics and conservation# ----------------------------------------------------------------------------def load_alignment(aligned_fasta: Path) -> MultipleSeqAlignment:return AlignIO.read(str(aligned_fasta), "fasta")def column_conservation(alignment) -> np.ndarray:"""Fraction of the most common non-gap residue in each column."""n_cols = alignment.get_alignment_length()n_rows = len(alignment)cons = np.zeros(n_cols)for j in range(n_cols):col = [alignment[i, j].upper() for i in range(n_rows)]col = [c for c in col if c != "-"]if not col:cons[j] = 0.0continuemost = Counter(col).most_common(1)[0][1]cons[j] = most / len(col)return consdef alignment_statistics(alignment, seq_type: str) -> pd.DataFrame:n_rows = len(alignment)n_cols = alignment.get_alignment_length()conserved = 0variable = 0pars_inf = 0gap_cells = 0ambset = set("N-") if seq_type == "Nucleotide" else set("X-")for j in range(n_cols):col = [alignment[i, j].upper() for i in range(n_rows)]gap_cells += sum(1 for c in col if c == "-")real = [c for c in col if c not in ambset]if not real:continuedistinct = set(real)if len(distinct) == 1:conserved += 1else:variable += 1counts = Counter(real)informative = sum(1 for v in counts.values() if v >= 2)if informative >= 2:pars_inf += 1gap_pct = round(100.0 * gap_cells / (n_rows * n_cols), 2) if n_cols else 0.0stats = {"Number of sequences": n_rows,"Alignment length": n_cols,"Conserved sites": conserved,"Variable sites": variable,"Parsimony-informative sites": pars_inf,"Gap percentage": gap_pct,}return pd.DataFrame(list(stats.items()), columns=["Metric", "Value"])# ----------------------------------------------------------------------------# Distance matrix# ----------------------------------------------------------------------------def compute_distance_matrix(alignment, model: str):calculator = DistanceCalculator(model)dm = calculator.get_distance(alignment)return dmdef distance_to_dataframe(dm) -> pd.DataFrame:names = dm.namesn = len(names)mat = np.zeros((n, n))for i in range(n):for j in range(n):mat[i, j] = dm[names[i], names[j]]return pd.DataFrame(mat, index=names, columns=names)# ----------------------------------------------------------------------------# Tree building# ----------------------------------------------------------------------------def run_fasttree(aligned_fasta: Path, output_tree: Path, nucleotide=True):binary = which_first(["FastTree", "fasttree", "FastTreeMP"])if not binary:raise RuntimeError("FastTree is not installed in this runtime.")cmd = [binary, "-nt", str(aligned_fasta)] if nucleotide else [binary, str(aligned_fasta)]code, stdout, stderr = run_command(cmd)if code != 0:raise RuntimeError(f"FastTree failed:\n{stderr}")output_tree.write_text(stdout, encoding="utf-8")return output_treedef run_iqtree(aligned_fasta: Path, output_tree: Path, nucleotide=True,model="MFP", bootstrap=1000, workdir: Path = None):binary = which_first(["iqtree2", "iqtree"])if not binary:raise RuntimeError("IQ-TREE is not installed in this runtime.")prefix = workdir / "iqtree_run"cmd = [binary, "-s", str(aligned_fasta), "-m", model,"-pre", str(prefix), "-nt", "AUTO", "-redo"]if bootstrap and bootstrap >= 1000:cmd += ["-B", str(bootstrap)]code, stdout, stderr = run_command(cmd)treefile = Path(str(prefix) + ".treefile")if code != 0 or not treefile.exists():raise RuntimeError(f"IQ-TREE failed:\n{stderr}\n{stdout}")shutil.copy(treefile, output_tree)return output_treedef run_distance_tree(alignment, output_tree: Path, method: str, model: str):"""Neighbor-Joining or UPGMA via Biopython."""calculator = DistanceCalculator(model)constructor = DistanceTreeConstructor(calculator, "nj" if method == "Neighbor-Joining" else "upgma")tree = constructor.build_tree(alignment)Phylo.write(tree, str(output_tree), "newick")return output_treedef build_tree(method, alignment, aligned_fasta, output_tree, seq_type,distance_model, iqtree_model, bootstrap, workdir):nucleotide = (seq_type == "Nucleotide")if method == "FastTree":return run_fasttree(aligned_fasta, output_tree, nucleotide=nucleotide)if method == "IQ-TREE":return run_iqtree(aligned_fasta, output_tree, nucleotide=nucleotide,model=iqtree_model, bootstrap=bootstrap, workdir=workdir)if method in ("Neighbor-Joining", "UPGMA"):return run_distance_tree(alignment, output_tree, method, distance_model)raise RuntimeError(f"Unknown tree method: {method}")# ----------------------------------------------------------------------------# Tree colour and grouping# ----------------------------------------------------------------------------def assign_groups(labels, mode, delimiter, field_index):"""Return a dict label -> group name."""groups = {}if mode == "None":for lab in labels:groups[lab] = "all"return groupsfor lab in labels:parts = lab.split(delimiter) if delimiter else [lab]idx = field_index if field_index < len(parts) else 0groups[lab] = parts[idx] if parts else labreturn groupsdef palette_for_groups(group_names, palette_name):colours = QUALITATIVE_PALETTES.get(palette_name, QUALITATIVE_PALETTES["Vibrant"])unique = sorted(set(group_names))mapping = {}for i, g in enumerate(unique):mapping[g] = colours[i % len(colours)]return mapping# ----------------------------------------------------------------------------# Tree layout engines# ----------------------------------------------------------------------------def rectangular_layout(tree):terminals = tree.get_terminals()ypos = {}for i, t in enumerate(terminals):ypos[t] = float(i)def set_y(clade):if clade.is_terminal():return ypos[clade]ys = [set_y(c) for c in clade.clades]y = sum(ys) / len(ys)ypos[clade] = yreturn yset_y(tree.root)xpos = {}def set_x(clade, x0):bl = clade.branch_length if clade.branch_length else 0.0x = x0 + blxpos[clade] = xfor c in clade.clades:set_x(c, x)set_x(tree.root, 0.0)return xpos, yposdef unrooted_layout(tree):"""Felsenstein equal-angle layout for radial/unrooted display."""coords = {}def place(clade, x, y, a_start, a_end):coords[clade] = (x, y)if clade.is_terminal():returntotal = clade.count_terminals()a = a_startfor child in clade.clades:leaves = max(child.count_terminals(), 1)wedge = (a_end - a_start) * leaves / totalmid = a + wedge / 2.0bl = child.branch_length if child.branch_length else 0.01cx = x + bl * math.cos(mid)cy = y + bl * math.sin(mid)place(child, cx, cy, a, a + wedge)a += wedgeplace(tree.root, 0.0, 0.0, 0.0, 2 * math.pi)return coords# ----------------------------------------------------------------------------# Tree drawing# ----------------------------------------------------------------------------def support_value(clade):"""Extract a numeric support value from a clade if present."""if clade.confidence is not None:return float(clade.confidence)if clade.name:try:return float(clade.name)except ValueError:return Nonereturn Nonedef draw_rectangular(tree, group_map, colour_map, opts):xpos, ypos = rectangular_layout(tree)fig, ax = plt.subplots(figsize=(opts["w"], opts["h"]), dpi=opts["dpi"])def draw_clade(clade):x = xpos[clade]y = ypos[clade]for child in clade.clades:cx = xpos[child]cy = ypos[child]tip_colour = "#333333"if child.is_terminal():grp = group_map.get(child.name, "all")tip_colour = colour_map.get(grp, "#333333")ax.plot([x, x], [y, cy], color="#555555", lw=opts["lw"])ax.plot([x, cx], [cy, cy], color=tip_colour if child.is_terminal() else "#555555",lw=opts["lw"])draw_clade(child)draw_clade(tree.root)for t in tree.get_terminals():grp = group_map.get(t.name, "all")ax.text(xpos[t] + opts["xpad"], ypos[t], t.name,fontsize=opts["fs"], va="center", ha="left",color=colour_map.get(grp, "#222222"))if opts["show_support"]:for c in tree.get_nonterminals():sv = support_value(c)if sv is not None and sv >= opts["support_thresh"]:ax.text(xpos[c], ypos[c], f"{sv:.0f}" if sv > 1 else f"{sv:.2f}",fontsize=max(opts["fs"] - 2, 5), va="bottom", ha="right",color="#666666")n_term = len(tree.get_terminals())ax.set_ylim(-1, n_term)ax.set_xlim(left=-0.01 * max(xpos.values()))ax.set_xlabel("Branch length", fontsize=opts["fs"])ax.set_yticks([])for spine in ["top", "right", "left"]:ax.spines[spine].set_visible(False)if opts["title"]:ax.set_title(opts["title"], fontsize=opts["fs"] + 3)fig.tight_layout()return figdef draw_circular(tree, group_map, colour_map, opts):terminals = tree.get_terminals()n = len(terminals)xpos, _ = rectangular_layout(tree)max_r = max(xpos.values()) if xpos else 1.0angle = {}span = math.radians(opts.get("arc_span", 350.0))for i, t in enumerate(terminals):angle[t] = span * i / max(n - 1, 1)def set_angle(clade):if clade.is_terminal():return angle[clade]child_angles = [set_angle(c) for c in clade.clades]a = sum(child_angles) / len(child_angles)angle[clade] = areturn aset_angle(tree.root)fig = plt.figure(figsize=(opts["w"], opts["w"]), dpi=opts["dpi"])ax = fig.add_subplot(111, projection="polar")ax.set_theta_direction(-1)ax.set_theta_offset(math.pi / 2)ax.set_axis_off()def draw_clade(clade):r = xpos[clade]a = angle[clade]if clade.clades:child_a = [angle[c] for c in clade.clades]arc = np.linspace(min(child_a), max(child_a), 60)ax.plot(arc, [r] * len(arc), color="#555555", lw=opts["lw"])for child in clade.clades:cr = xpos[child]ca = angle[child]col = "#555555"if child.is_terminal():grp = group_map.get(child.name, "all")col = colour_map.get(grp, "#555555")ax.plot([ca, ca], [r, cr], color=col, lw=opts["lw"])draw_clade(child)draw_clade(tree.root)for t in terminals:grp = group_map.get(t.name, "all")a = angle[t]deg = math.degrees(a)rot = degha = "left"if 90 < (deg % 360) < 270:rot = deg + 180ha = "right"ax.text(a, xpos[t] + max_r * 0.02, t.name,fontsize=opts["fs"], rotation=rot, rotation_mode="anchor",ha=ha, va="center", color=colour_map.get(grp, "#222222"))if opts["title"]:ax.set_title(opts["title"], fontsize=opts["fs"] + 3, pad=20)fig.tight_layout()return figdef draw_unrooted(tree, group_map, colour_map, opts):coords = unrooted_layout(tree)fig, ax = plt.subplots(figsize=(opts["w"], opts["w"]), dpi=opts["dpi"])def draw_clade(clade):x, y = coords[clade]for child in clade.clades:cx, cy = coords[child]col = "#555555"if child.is_terminal():grp = group_map.get(child.name, "all")col = colour_map.get(grp, "#555555")ax.plot([x, cx], [y, cy], color=col, lw=opts["lw"])draw_clade(child)draw_clade(tree.root)for t in tree.get_terminals():x, y = coords[t]grp = group_map.get(t.name, "all")ax.text(x, y, " " + t.name, fontsize=opts["fs"], va="center",ha="left", color=colour_map.get(grp, "#222222"))ax.set_aspect("equal")ax.set_axis_off()if opts["title"]:ax.set_title(opts["title"], fontsize=opts["fs"] + 3)fig.tight_layout()return figdef render_tree_figure(tree, layout, group_map, colour_map, opts):if layout == "Rectangular":return draw_rectangular(tree, group_map, colour_map, opts)if layout == "Circular":return draw_circular(tree, group_map, colour_map, opts)if layout == "Radial (unrooted)":return draw_unrooted(tree, group_map, colour_map, opts)return draw_rectangular(tree, group_map, colour_map, opts)# ----------------------------------------------------------------------------# Supporting figures# ----------------------------------------------------------------------------def figure_distance_heatmap(dist_df, cmap_name, dpi):fig, ax = plt.subplots(figsize=(max(6, 0.5 * len(dist_df)),max(5, 0.5 * len(dist_df))), dpi=dpi)im = ax.imshow(dist_df.values, cmap=cmap_name, aspect="auto")ax.set_xticks(range(len(dist_df.columns)))ax.set_yticks(range(len(dist_df.index)))ax.set_xticklabels(dist_df.columns, rotation=90, fontsize=7)ax.set_yticklabels(dist_df.index, fontsize=7)fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label="Pairwise distance")ax.set_title("Pairwise genetic distance matrix")fig.tight_layout()return figdef figure_conservation(conservation, dpi):fig, ax = plt.subplots(figsize=(12, 3), dpi=dpi)ax.fill_between(range(len(conservation)), conservation, color="#2c7fb8", alpha=0.85)ax.set_xlabel("Alignment column")ax.set_ylabel("Conservation")ax.set_ylim(0, 1.02)ax.set_title("Per-column conservation profile")for spine in ["top", "right"]:ax.spines[spine].set_visible(False)fig.tight_layout()return figdef figure_composition(comp_df, seq_type, palette_name, dpi):value_cols = [c for c in comp_df.columns if c != "Sequence_ID"]colours = QUALITATIVE_PALETTES.get(palette_name, QUALITATIVE_PALETTES["Vibrant"])fig, ax = plt.subplots(figsize=(max(8, 0.6 * len(comp_df)), 5), dpi=dpi)bottom = np.zeros(len(comp_df))x = np.arange(len(comp_df))for i, col in enumerate(value_cols):ax.bar(x, comp_df[col].values, bottom=bottom,color=colours[i % len(colours)], label=col, width=0.8)bottom += comp_df[col].valuesax.set_xticks(x)ax.set_xticklabels(comp_df["Sequence_ID"], rotation=90, fontsize=7)ax.set_ylabel("Composition (%)")title = "Nucleotide composition" if seq_type == "Nucleotide" else "Residue composition"ax.set_title(title)ax.legend(ncol=min(len(value_cols), 10), fontsize=7,loc="upper center", bbox_to_anchor=(0.5, -0.25))for spine in ["top", "right"]:ax.spines[spine].set_visible(False)fig.tight_layout()return figdef figure_gc(summary_df, dpi):if "GC_percent" not in summary_df.columns:return Nonefig, ax = plt.subplots(figsize=(max(8, 0.6 * len(summary_df)), 4), dpi=dpi)x = np.arange(len(summary_df))ax.bar(x, summary_df["GC_percent"].values, color="#41b6c4", width=0.8)ax.axhline(summary_df["GC_percent"].mean(), color="#d95f02",ls="--", lw=1, label="Mean GC")ax.set_xticks(x)ax.set_xticklabels(summary_df["Sequence_ID"], rotation=90, fontsize=7)ax.set_ylabel("GC content (%)")ax.set_title("GC content per sequence")ax.legend(fontsize=8)for spine in ["top", "right"]:ax.spines[spine].set_visible(False)fig.tight_layout()return fig# ----------------------------------------------------------------------------# Figure export# ----------------------------------------------------------------------------def figure_to_formats(fig):out = {}for fmt in ("png", "svg", "pdf"):buf = io.BytesIO()fig.savefig(buf, format=fmt, bbox_inches="tight")out[fmt] = buf.getvalue()plt.close(fig)return out# ----------------------------------------------------------------------------# Methods paragraph# ----------------------------------------------------------------------------def build_methods_text(aligner, strategy, method, seq_type, distance_model,iqtree_model, bootstrap, n_seq, align_len):parts = []parts.append(f"A total of {n_seq} {seq_type.lower()} sequences were analysed.")if aligner == "MAFFT":parts.append(f"Multiple sequence alignment was performed with MAFFT using the {strategy} strategy.")else:parts.append(f"Multiple sequence alignment was performed with {aligner}.")parts.append(f"The resulting alignment was {align_len} columns long.")if method == "FastTree":engine = "an approximate maximum-likelihood tree was inferred with FastTree."parts.append(f"From this alignment, {engine}")elif method == "IQ-TREE":model_text = "automatic model selection (ModelFinder)" if iqtree_model == "MFP" else f"the {iqtree_model} model"parts.append(f"A maximum-likelihood tree was inferred with IQ-TREE under {model_text}, "f"with branch support from {bootstrap} ultrafast bootstrap replicates.")elif method in ("Neighbor-Joining", "UPGMA"):parts.append(f"A {method} tree was constructed from a {distance_model} distance matrix, "f"as implemented in Biopython.")parts.append("Trees and supporting figures were produced within the PhyloForge application.")return " ".join(parts)# ----------------------------------------------------------------------------# Rendering persisted results# ----------------------------------------------------------------------------def render_results():for w in st.session_state.get("warnings", []):st.warning(w)for e in st.session_state.get("errors", []):st.error(e)if st.session_state.get("success"):st.success(st.session_state["success"])if not st.session_state.get("result_ready"):returntabs = st.tabs(["Trees", "Sequence tables", "Alignment", "Distance matrix","Figures", "Downloads", "Methods"])figures = st.session_state.get("figures", {})with tabs[0]:for name in ["tree_main"]:if name in figures:st.image(figures[name]["png"], use_container_width=True)if st.session_state.get("newick_text"):st.subheader("Newick string")st.code(st.session_state["newick_text"], language="text")with tabs[1]:if st.session_state.get("seq_summary_df") is not None:st.subheader("Sequence summary")st.dataframe(st.session_state["seq_summary_df"], use_container_width=True)if st.session_state.get("composition_df") is not None:st.subheader("Composition (%)")st.dataframe(st.session_state["composition_df"], use_container_width=True)with tabs[2]:if st.session_state.get("align_stats_df") is not None:st.subheader("Alignment statistics")st.dataframe(st.session_state["align_stats_df"], use_container_width=True)if "conservation" in figures:st.image(figures["conservation"]["png"], use_container_width=True)with tabs[3]:if st.session_state.get("distance_df") is not None:st.subheader("Pairwise distance matrix")st.dataframe(st.session_state["distance_df"].round(4), use_container_width=True)if "distance_heatmap" in figures:st.image(figures["distance_heatmap"]["png"], use_container_width=True)with tabs[4]:for key, label in [("composition", "Composition"),("gc", "GC content")]:if key in figures:st.subheader(label)st.image(figures[key]["png"], use_container_width=True)with tabs[5]:render_downloads(figures)with tabs[6]:if st.session_state.get("method_text"):st.write(st.session_state["method_text"])st.caption("Draft text for a methods section. Check tool versions and citations before use.")def render_downloads(figures):st.subheader("Data files")c1, c2, c3 = st.columns(3)with c1:if st.session_state.get("newick_text"):st.download_button("Newick tree", st.session_state["newick_text"],"tree.nwk", "text/plain", key="dl_nwk")with c2:if st.session_state.get("aligned_fasta_text"):st.download_button("Aligned FASTA", st.session_state["aligned_fasta_text"],"aligned.fasta", "text/plain", key="dl_aln")with c3:if st.session_state.get("distance_df") is not None:st.download_button("Distance matrix (CSV)",st.session_state["distance_df"].to_csv(),"distances.csv", "text/csv", key="dl_dist")c4, c5 = st.columns(2)with c4:if st.session_state.get("seq_summary_df") is not None:st.download_button("Sequence summary (CSV)",st.session_state["seq_summary_df"].to_csv(index=False),"summary.csv", "text/csv", key="dl_sum")with c5:if st.session_state.get("composition_df") is not None:st.download_button("Composition (CSV)",st.session_state["composition_df"].to_csv(index=False),"composition.csv", "text/csv", key="dl_comp")st.subheader("Figures")for name, data in figures.items():st.markdown(f"**{name}**")f1, f2, f3 = st.columns(3)with f1:st.download_button(f"{name} PNG", data["png"], f"{name}.png","image/png", key=f"dl_{name}_png")with f2:st.download_button(f"{name} SVG", data["svg"], f"{name}.svg","image/svg+xml", key=f"dl_{name}_svg")with f3:st.download_button(f"{name} PDF", data["pdf"], f"{name}.pdf","application/pdf", key=f"dl_{name}_pdf")# ----------------------------------------------------------------------------# Main pipeline# ----------------------------------------------------------------------------def run_pipeline(records, seq_type, aligner, strategy, tree_method,distance_model, iqtree_model, bootstrap, root_midpoint,tree_layout, palette_name, group_mode, delimiter, field_index,cmap_name, tree_opts):figures = {}# Sequence tablessummary_df = sequence_summary(records, seq_type)comp_df = composition_table(records, seq_type)st.session_state["seq_summary_df"] = summary_dfst.session_state["composition_df"] = comp_dfwith tempfile.TemporaryDirectory() as tmp:tmp = Path(tmp)input_fasta = tmp / "input.fasta"aligned_fasta = tmp / "aligned.fasta"tree_file = tmp / "tree.nwk"with open(input_fasta, "w") as h:SeqIO.write(records, h, "fasta")with st.spinner(f"Aligning with {aligner}..."):run_alignment(aligner, strategy, input_fasta, aligned_fasta)alignment = load_alignment(aligned_fasta)st.session_state["aligned_fasta_text"] = aligned_fasta.read_text(encoding="utf-8")align_stats = alignment_statistics(alignment, seq_type)st.session_state["align_stats_df"] = align_statsalign_len = alignment.get_alignment_length()# Distance matrix (for the heatmap and, when relevant, for the tree)dm = compute_distance_matrix(alignment, distance_model)dist_df = distance_to_dataframe(dm)st.session_state["distance_df"] = dist_dfwith st.spinner(f"Building tree with {tree_method}..."):build_tree(tree_method, alignment, aligned_fasta, tree_file, seq_type,distance_model, iqtree_model, bootstrap, tmp)tree = Phylo.read(str(tree_file), "newick")if root_midpoint:try:tree.root_at_midpoint()except Exception:passst.session_state["newick_text"] = tree_file.read_text(encoding="utf-8")# Grouping and colourlabels = [t.name for t in tree.get_terminals()]group_map = assign_groups(labels, group_mode, delimiter, field_index)colour_map = palette_for_groups(list(group_map.values()), palette_name)# Main tree figurewith st.spinner("Rendering tree figure..."):fig = render_tree_figure(tree, tree_layout, group_map, colour_map, tree_opts)figures["tree_main"] = figure_to_formats(fig)# Supporting figurescons = column_conservation(alignment)figures["conservation"] = figure_to_formats(figure_conservation(cons, tree_opts["dpi"]))figures["distance_heatmap"] = figure_to_formats(figure_distance_heatmap(dist_df, cmap_name, tree_opts["dpi"]))figures["composition"] = figure_to_formats(figure_composition(comp_df, seq_type, palette_name, tree_opts["dpi"]))gc_fig = figure_gc(summary_df, tree_opts["dpi"])if gc_fig is not None:figures["gc"] = figure_to_formats(gc_fig)st.session_state["figures"] = figuresst.session_state["method_text"] = build_methods_text(aligner, strategy, tree_method, seq_type, distance_model,iqtree_model, bootstrap, len(records), align_len)st.session_state["success"] = f"Analysis complete. {len(records)} sequences processed."st.session_state["result_ready"] = True# ----------------------------------------------------------------------------# Streamlit UI# ----------------------------------------------------------------------------def main():st.set_page_config(page_title=APP_TITLE, layout="wide")2 unmodified linesst.title(APP_TITLE)st.caption(APP_SUBTITLE)with st.sidebar:st.header("Sequence")seq_type = st.radio("Sequence type", ["Nucleotide", "Protein"], index=0)st.header("Alignment")aligner = st.selectbox("Aligner", ["MAFFT", "MUSCLE", "Clustal Omega"], index=0)strategy = "Auto"if aligner == "MAFFT":strategy = st.selectbox("MAFFT strategy",["Auto", "FFT-NS-2 (fast)", "L-INS-i (accurate, local)","G-INS-i (accurate, global)", "E-INS-i (multi-domain)"],index=0,)st.header("Tree method")tree_method = st.selectbox("Method",["FastTree", "IQ-TREE", "Neighbor-Joining", "UPGMA"],index=0,)distance_models = NUC_DISTANCE_MODELS if seq_type == "Nucleotide" else PROT_DISTANCE_MODELSdistance_model = st.selectbox("Distance model (NJ, UPGMA, heatmap)",distance_models, index=0)iqtree_model = "MFP"bootstrap = 1000if tree_method == "IQ-TREE":iqtree_model = st.text_input("IQ-TREE model (MFP for ModelFinder)", value="MFP")bootstrap = st.slider("Ultrafast bootstrap replicates", 1000, 5000, 1000, step=1000)root_midpoint = st.checkbox("Midpoint rooting", value=True)st.header("Tree display")tree_layout = st.selectbox("Layout",["Rectangular", "Circular", "Radial (unrooted)"], index=0)palette_name = st.selectbox("Colour palette", list(QUALITATIVE_PALETTES.keys()), index=0)cmap_name = st.selectbox("Heatmap colormap", CONTINUOUS_MAPS, index=0)group_mode = st.selectbox("Colour tips by", ["None", "Label field"], index=0)delimiter = "_"field_index = 0if group_mode == "Label field":delimiter = st.text_input("Field delimiter", value="_")field_index = st.number_input("Field index (0 = first)", min_value=0, value=0, step=1)st.header("Figure options")fig_w = st.slider("Figure width", 6, 24, 12)fig_h = st.slider("Figure height", 4, 24, 8)dpi = st.selectbox("DPI", [150, 300, 600], index=1)font_size = st.slider("Label font size", 5, 16, 9)line_width = st.slider("Branch line width", 0.5, 4.0, 1.4, step=0.1)show_support = st.checkbox("Show support values", value=True)support_thresh = st.slider("Support display threshold", 0.0, 100.0, 0.0)arc_span = st.slider("Circular arc span (degrees)", 180, 360, 350)tree_title = st.text_input("Figure title", value="")st.markdown("Upload or paste FASTA sequences, choose your settings in the sidebar, ""then build the tree. The tool runs alignment, distance estimation, tree ""inference, and figure generation, then returns trees, tables, and figures ""in PNG, SVG, and PDF.")uploaded = st.file_uploader("Upload FASTA file",type=["fasta", "fa", "fna", "faa", "txt"])fasta_text = st.text_area("Or paste FASTA sequences", height=200)c_run, c_clear = st.columns([3, 1])with c_run:run_clicked = st.button("Build phylogenetic tree", type="primary",use_container_width=True)with c_clear:st.button("Clear", use_container_width=True, on_click=clear_results)if run_clicked:clear_results()try:raw = []if uploaded is not None:content = uploaded.read().decode("utf-8", errors="ignore")raw.extend(parse_fasta_text(content))if fasta_text.strip():raw.extend(parse_fasta_text(fasta_text))if not raw:st.session_state["errors"] = ["Please upload or paste FASTA sequences."]render_results()returnrecords, errors, warnings = validate_records(raw, seq_type)st.session_state["warnings"] = warningsif errors:st.session_state["errors"] = errorsrender_results()returntree_opts = {"w": fig_w, "h": fig_h, "dpi": dpi, "fs": font_size,"lw": line_width, "show_support": show_support,"support_thresh": support_thresh, "title": tree_title,"xpad": 0.002, "arc_span": arc_span,}run_pipeline(records, seq_type, aligner, strategy, tree_method,distance_model, iqtree_model, bootstrap, root_midpoint,tree_layout, palette_name, group_mode, delimiter, field_index,cmap_name, tree_opts,)except Exception as e:st.session_state["errors"] = [f"Pipeline failed: {e}"]render_results()if __name__ == "__main__":main()
12345streamlit==1.44.1biopython==1.85pandas==2.2.3matplotlib==3.10.1numpy==1.26.412345streamlit>=1.33biopython>=1.83pandas>=2.0numpy>=1.24matplotlib>=3.7
app.py+1012-289
requirements.txt+5-5