Spaces:
Build error
Build error
Update app.py
Browse files858 unmodified lines859860861862863864865866867868869870871872873874875876192 unmodified lines10691070107110721073107410751076107710781079740 unmodified lines18201821182218231824182547 unmodified lines1873187418751876187718781879188018817 unmodified lines18891890189118921893189418951 unmodified line189718981899190019011902858 unmodified linesreturn seq[:usable]def collect_cds_sequences(record, feature_df: pd.DataFrame) -> List[str]:if feature_df.empty:return []cds = feature_df[feature_df["feature_type"].str.lower().eq("cds")].copy()seqs = []for _, row in cds.iterrows():seq = valid_cds_sequence(extract_feature_sequence(record, row))if len(seq) >= 90:seqs.append(seq)return seqsdef iterate_codons(seq: str):for i in range(0, len(seq) - 2, 3):yield seq[i:i + 3]192 unmodified linesreturn round(gravy, 4), round(aromaticity, 4)def per_cds_metrics(cds_sequences: List[str], ctx: CodonContext, weights: Optional[Dict[str, float]]) -> pd.DataFrame:rows = []for idx, seq in enumerate(cds_sequences, 1):seq = valid_cds_sequence(seq)if len(seq) < 90:continuecounts = codon_counts_single(seq, ctx)enc = enc_from_counts(counts, ctx)740 unmodified linestheme_name = st.selectbox("Figure colour theme", list(LINE_THEMES.keys()), index=0)run_mode = st.radio("Output mode", ["Fast preview", "Publication quality"], index=1)max_detailed_records = st.number_input("Replicons to render in detail (largest first)", min_value=1, max_value=20, value=4, step=1)derive_weights = st.checkbox("Derive codon weights from this genome when no reference is given", value=True)infer_orfs = st.checkbox("Predict ORFs for FASTA only input", value=False)min_orf_aa = st.slider("Minimum ORF length, amino acids", 30, 500, 90, 10)47 unmodified linesdinuc_df = dinucleotide_relative_abundance(str(main_record.seq))tetra_df = tetranucleotide_frequency(str(main_record.seq))all_cds = []for r in records:all_cds.extend(collect_cds_sequences(r, tables.get(r.id, pd.DataFrame())))codon_counts = aggregate_codon_counts(all_cds, ctx)stop_counts = {c: 0 for c in ctx.stop_codons}7 unmodified linesweights = ref_weights if ref_weights else (derive_weights_from_counts(codon_counts, ctx) if derive_weights else None)codon_df = codon_usage_table(codon_counts, ctx, stop_counts, ref_weights)optimal_df = optimal_codon_table(codon_df)per_cds_df = per_cds_metrics(all_cds, ctx, weights)aa_df = amino_acid_usage(all_cds, ctx)cai_mean = round(float(per_cds_df["CAI"].dropna().mean()), 4) if not per_cds_df.empty and per_cds_df["CAI"].notna().any() else float("nan")neutrality = neutrality_regression(per_cds_df)1 unmodified linestats = build_summary_statistics(records, main_record, composition, assembly, origin_terminus,feature_df, filtered_df, all_cds, codon_df, codon_counts,ctx, cai_mean, per_cds_df, neutrality)stats_df = pd.DataFrame([stats]).T.reset_index()stats_df.columns = ["parameter", "value"]858 unmodified lines859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914192 unmodified lines11071108110911101111111211131114111511161117740 unmodified lines1858185918601861186218631864186547 unmodified lines19131914191519161917191819191920192119221923192419257 unmodified lines19331934193519361937193819391 unmodified line1941194219431944194519461947858 unmodified linesreturn seq[:usable]CODING_TYPE_PRIORITY = ["cds", "orf", "gene", "mrna"]def collect_coding_sequences(record, feature_df: pd.DataFrame, coding_types: List[str], min_len_bp: int = 90) -> List[str]:"""Collect coding nucleotide sequences for codon analysis.For GenBank and EMBL records the original feature objects are used throughfeature.extract, which joins exons and applies the strand correctly. For FASTA basedinputs (ORF prediction, GFF, BED, annotation table) the coordinate table is used."""types_lower = {t.lower() for t in coding_types}seqs: List[str] = []used_record_features = Falsefor feat in getattr(record, "features", []):if str(getattr(feat, "type", "")).lower() in types_lower:try:s = valid_cds_sequence(str(feat.extract(record.seq)))except Exception:continueif len(s) >= min_len_bp:seqs.append(s)used_record_features = Trueif used_record_features:return seqsif feature_df is not None and not feature_df.empty:sub = feature_df[feature_df["feature_type"].str.lower().isin(types_lower)]for _, row in sub.iterrows():s = valid_cds_sequence(extract_feature_sequence(record, row))if len(s) >= min_len_bp:seqs.append(s)return seqsdef collect_all_coding(records, tables, coding_choice: str, min_len_bp: int = 90) -> Tuple[List[str], str]:"""Return all coding sequences and the feature type that produced them.With auto detect the function tries CDS, then ORF, then gene, then mRNA, and stops atthe first type that yields sequences. This avoids an empty codon table when the filelabels coding features as ORF or gene rather than CDS."""candidates = CODING_TYPE_PRIORITY if coding_choice == "Auto detect" else [coding_choice.lower()]for cand in candidates:seqs: List[str] = []for r in records:seqs.extend(collect_coding_sequences(r, tables.get(r.id, pd.DataFrame()), [cand], min_len_bp))if seqs:return seqs, cand.upper()return [], (candidates[0].upper() if candidates else "CDS")def iterate_codons(seq: str):for i in range(0, len(seq) - 2, 3):yield seq[i:i + 3]192 unmodified linesreturn round(gravy, 4), round(aromaticity, 4)def per_cds_metrics(cds_sequences: List[str], ctx: CodonContext, weights: Optional[Dict[str, float]], min_len_bp: int = 90) -> pd.DataFrame:rows = []for idx, seq in enumerate(cds_sequences, 1):seq = valid_cds_sequence(seq)if len(seq) < min_len_bp:continuecounts = codon_counts_single(seq, ctx)enc = enc_from_counts(counts, ctx)740 unmodified linestheme_name = st.selectbox("Figure colour theme", list(LINE_THEMES.keys()), index=0)run_mode = st.radio("Output mode", ["Fast preview", "Publication quality"], index=1)max_detailed_records = st.number_input("Replicons to render in detail (largest first)", min_value=1, max_value=20, value=4, step=1)coding_choice = st.selectbox("Coding feature for codon analysis", ["Auto detect", "CDS", "ORF", "gene", "mRNA"], index=0)min_coding_bp = st.number_input("Minimum coding length for codon analysis, bp", min_value=30, max_value=3000, value=90, step=30)derive_weights = st.checkbox("Derive codon weights from this genome when no reference is given", value=True)infer_orfs = st.checkbox("Predict ORFs for FASTA only input", value=False)min_orf_aa = st.slider("Minimum ORF length, amino acids", 30, 500, 90, 10)47 unmodified linesdinuc_df = dinucleotide_relative_abundance(str(main_record.seq))tetra_df = tetranucleotide_frequency(str(main_record.seq))all_cds, coding_type_used = collect_all_coding(records, tables, coding_choice, int(min_coding_bp))if all_cds:parsed.notes.append(f"Codon analysis used {len(all_cds):,} coding sequences taken from feature type {coding_type_used}.")else:parsed.notes.append("No coding sequences were collected, so codon usage is zero. Check that the file ""contains CDS, ORF or gene features, or enable ORF prediction for FASTA only input, ""or set the coding feature manually in the sidebar.")codon_counts = aggregate_codon_counts(all_cds, ctx)stop_counts = {c: 0 for c in ctx.stop_codons}7 unmodified linesweights = ref_weights if ref_weights else (derive_weights_from_counts(codon_counts, ctx) if derive_weights else None)codon_df = codon_usage_table(codon_counts, ctx, stop_counts, ref_weights)optimal_df = optimal_codon_table(codon_df)per_cds_df = per_cds_metrics(all_cds, ctx, weights, int(min_coding_bp))aa_df = amino_acid_usage(all_cds, ctx)cai_mean = round(float(per_cds_df["CAI"].dropna().mean()), 4) if not per_cds_df.empty and per_cds_df["CAI"].notna().any() else float("nan")neutrality = neutrality_regression(per_cds_df)1 unmodified linestats = build_summary_statistics(records, main_record, composition, assembly, origin_terminus,feature_df, filtered_df, all_cds, codon_df, codon_counts,ctx, cai_mean, per_cds_df, neutrality)stats["coding_feature_type_used"] = coding_type_used if all_cds else "none"stats_df = pd.DataFrame([stats]).T.reset_index()stats_df.columns = ["parameter", "value"]
app.py+60-15