Phylogenetic_Tree_Builder / crispr_utils.py
GENOMICS-CDDBRG's picture
Update crispr_utils.py
1addb1a verified
Raw History Blame Contribute Delete
28.8 kB
import io
import zipfile
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Iterable, List, Optional, Sequence, Tuple
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyrodigal
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from common import safe_filename, run_command
@dataclass
class AnalysisConfig:
min_repeat_len: int = 23
max_repeat_len: int = 47
min_spacer_len: int = 18
max_spacer_len: int = 78
min_repeats: int = 3
neighborhood_bp: int = 15000
min_orf_aa: int = 60
min_cas_identity: float = 35.0
min_cas_coverage: float = 50.0
def ensure_directories(paths: Iterable[Path]) -> None:
for path in paths:
path.mkdir(parents=True, exist_ok=True)
def sanitize_filename_stem(filename: str) -> str:
return safe_filename(filename)
def parse_fasta_text(fasta_text: str) -> List[SeqRecord]:
return list(SeqIO.parse(io.StringIO(fasta_text), "fasta"))
def read_fasta(path: Path) -> List[SeqRecord]:
records = list(SeqIO.parse(str(path), "fasta"))
if not records:
raise ValueError("No FASTA records were found in the uploaded file.")
return records
def write_fasta(records: Sequence[SeqRecord], path: Path) -> None:
SeqIO.write(records, str(path), "fasta")
def reverse_complement(seq: str) -> str:
return str(Seq(seq).reverse_complement())
def hamming_distance(a: str, b: str) -> int:
if len(a) != len(b):
raise ValueError("Sequences must have equal length for Hamming distance.")
return sum(1 for x, y in zip(a, b) if x != y)
def normalized_identity(a: str, b: str) -> float:
if not a or not b or len(a) != len(b):
return 0.0
return 100.0 * (1.0 - (hamming_distance(a, b) / len(a)))
def _build_kmer_index(seq: str, k: int, min_repeats: int) -> Dict[str, List[int]]:
"""
Vectorized replacement for a per-position Python loop.
Groups every position in seq that starts an identical k-mer, skipping
any k-mer that contains an ambiguous base ('N'). The grouping itself is
done with numpy sort and compare operations, which run in compiled code,
instead of slicing and hashing a Python string at every position. This
is the step that made the original scan slow on multi-megabase genomes,
since it repeated the position-by-position loop once for every repeat
length in the configured range.
Output is equivalent to the original dict built by manual iteration:
only motifs with at least min_repeats occurrences are kept.
"""
n = len(seq)
if n < k:
return {}
arr = np.frombuffer(seq.encode("ascii"), dtype=np.uint8)
windows = np.lib.stride_tricks.sliding_window_view(arr, k)
valid = ~np.any(windows == ord("N"), axis=1)
valid_idx = np.nonzero(valid)[0]
if valid_idx.size == 0:
return {}
valid_windows = np.ascontiguousarray(windows[valid_idx])
# Pack each k-byte row into one fixed-width record so numpy can sort
# and group whole rows at once, rather than us hashing strings in Python.
packed = valid_windows.view(np.dtype((np.void, k))).ravel()
order = np.argsort(packed, kind="stable")
packed_sorted = packed[order]
pos_sorted = valid_idx[order]
boundaries = np.nonzero(
np.concatenate(([True], packed_sorted[1:] != packed_sorted[:-1]))
)[0]
boundaries = np.append(boundaries, packed_sorted.size)
index: Dict[str, List[int]] = {}
for start, end in zip(boundaries[:-1], boundaries[1:]):
if end - start < min_repeats:
continue
pos0 = int(pos_sorted[start])
motif = seq[pos0 : pos0 + k]
index[motif] = sorted(int(p) for p in pos_sorted[start:end])
return index
def find_candidate_arrays_on_strand(
seq: str,
contig_id: str,
strand: str,
config: AnalysisConfig,
) -> List[dict]:
"""
Heuristic CRISPR array detector:
- searches repeated units of length k
- requires >= min_repeats
- enforces spacer length range
- allows modest repeat divergence
Note: repeat grouping is currently exact match only. Two repeat units
that differ by even one base will not be grouped together, so the
identity check in build_array_record will always evaluate to 100%.
On real genomes, where repeat units often carry one or two base
differences, this can under detect or miss arrays entirely. Flagging
this separately, since fixing it changes detection behavior and needs
your input before I touch it.
"""
arrays = []
for repeat_len in range(config.min_repeat_len, config.max_repeat_len + 1):
index = _build_kmer_index(seq, repeat_len, config.min_repeats)
for motif, starts in index.items():
chain = [starts[0]]
for s in starts[1:]:
prev = chain[-1]
spacer_len = s - prev - repeat_len
if config.min_spacer_len <= spacer_len <= config.max_spacer_len:
chain.append(s)
else:
if len(chain) >= config.min_repeats:
arr = build_array_record(seq, contig_id, strand, motif, chain, repeat_len)
if arr is not None:
arrays.append(arr)
chain = [s]
if len(chain) >= config.min_repeats:
arr = build_array_record(seq, contig_id, strand, motif, chain, repeat_len)
if arr is not None:
arrays.append(arr)
deduped = deduplicate_arrays(arrays)
return deduped
def build_array_record(
seq: str,
contig_id: str,
strand: str,
motif: str,
starts: List[int],
repeat_len: int,
) -> Optional[dict]:
repeats = []
spacers = []
for idx, s in enumerate(starts):
repeat_seq = seq[s : s + repeat_len]
repeats.append(repeat_seq)
if idx < len(starts) - 1:
next_s = starts[idx + 1]
spacer_seq = seq[s + repeat_len : next_s]
spacers.append(spacer_seq)
if len(repeats) < 3:
return None
identity_values = [normalized_identity(motif, r) for r in repeats]
avg_identity = sum(identity_values) / len(identity_values)
if avg_identity < 85:
return None
array_start = starts[0] + 1
array_end = starts[-1] + repeat_len
spacer_lengths = [len(s) for s in spacers]
return {
"contig": contig_id,
"strand": strand,
"start": array_start,
"end": array_end,
"repeat_count": len(repeats),
"spacer_count": len(spacers),
"repeat_length": repeat_len,
"mean_spacer_length": round(sum(spacer_lengths) / len(spacer_lengths), 2) if spacer_lengths else 0.0,
"consensus_repeat": motif,
"repeat_identity_mean": round(avg_identity, 2),
"spacer_sequences": "|".join(spacers),
}
def deduplicate_arrays(arrays: List[dict]) -> List[dict]:
if not arrays:
return []
arrays = sorted(
arrays,
key=lambda x: (
x["contig"],
x["start"],
-(x["repeat_count"]),
-(x["repeat_length"]),
),
)
filtered = []
for arr in arrays:
keep = True
for existing in filtered:
if (
arr["contig"] == existing["contig"]
and abs(arr["start"] - existing["start"]) <= 5
and abs(arr["end"] - existing["end"]) <= 5
):
score_a = arr["repeat_count"] * arr["repeat_length"]
score_b = existing["repeat_count"] * existing["repeat_length"]
if score_a <= score_b:
keep = False
break
if keep:
filtered.append(arr)
for i, arr in enumerate(filtered, start=1):
arr["array_id"] = f"CRISPR_{i}"
return filtered
def detect_crispr_arrays(records: List[SeqRecord], config: AnalysisConfig) -> pd.DataFrame:
all_arrays = []
for record in records:
seq = str(record.seq).upper()
plus_arrays = find_candidate_arrays_on_strand(
seq=seq,
contig_id=record.id,
strand="+",
config=config,
)
rc_seq = reverse_complement(seq)
minus_arrays_rc = find_candidate_arrays_on_strand(
seq=rc_seq,
contig_id=record.id,
strand="-",
config=config,
)
adjusted_minus = []
seq_len = len(seq)
for arr in minus_arrays_rc:
orig_start = seq_len - arr["end"] + 1
orig_end = seq_len - arr["start"] + 1
arr["start"] = orig_start
arr["end"] = orig_end
adjusted_minus.append(arr)
all_arrays.extend(plus_arrays)
all_arrays.extend(adjusted_minus)
df = pd.DataFrame(all_arrays)
if df.empty:
return pd.DataFrame(
columns=[
"array_id", "contig", "strand", "start", "end", "repeat_count",
"spacer_count", "repeat_length", "mean_spacer_length",
"consensus_repeat", "repeat_identity_mean", "spacer_sequences"
]
)
df = df.sort_values(["contig", "start", "end"]).reset_index(drop=True)
return df
def predict_genes(records: List[SeqRecord], config: AnalysisConfig) -> pd.DataFrame:
# meta=True runs Pyrodigal in metagenomic mode, which uses a set of
# precomputed models and does not require an explicit train() call.
# The previous meta=False setting needs training on a representative
# sequence before find_genes() will produce results, which was missing
# here and is a likely reason gene, Cas, and locus tables came back
# empty even when CRISPR arrays were detected.
gene_finder = pyrodigal.GeneFinder(meta=True)
rows = []
gene_counter = 1
for record in records:
seq_bytes = bytes(str(record.seq).upper(), "ascii")
genes = gene_finder.find_genes(seq_bytes)
for gene in genes:
protein = gene.translate()
if len(protein) < config.min_orf_aa:
continue
# Pyrodigal versions differ on whether gene.sequence() returns
# str or bytes, so both are handled here instead of assuming one.
nucleotide_sequence = gene.sequence()
if isinstance(nucleotide_sequence, bytes):
nucleotide_sequence = nucleotide_sequence.decode("ascii")
rows.append(
{
"gene_id": f"ORF_{gene_counter}",
"contig": record.id,
"start": int(gene.begin),
"end": int(gene.end),
"strand": "+" if gene.strand == 1 else "-",
"partial_begin": bool(gene.partial_begin),
"partial_end": bool(gene.partial_end),
"protein_length_aa": len(protein),
"protein_sequence": protein,
"nucleotide_sequence": nucleotide_sequence,
}
)
gene_counter += 1
df = pd.DataFrame(rows)
if df.empty:
return pd.DataFrame(
columns=[
"gene_id", "contig", "start", "end", "strand", "partial_begin",
"partial_end", "protein_length_aa", "protein_sequence", "nucleotide_sequence"
]
)
return df.sort_values(["contig", "start", "end"]).reset_index(drop=True)
def write_gene_fastas(genes_df: pd.DataFrame, protein_fasta_path: Path, nucleotide_fasta_path: Path) -> None:
protein_records = []
nucleotide_records = []
for _, row in genes_df.iterrows():
desc = f"{row['contig']}:{row['start']}-{row['end']}({row['strand']})"
protein_records.append(
SeqRecord(
Seq(row["protein_sequence"]),
id=row["gene_id"],
description=desc,
)
)
nucleotide_records.append(
SeqRecord(
Seq(row["nucleotide_sequence"]),
id=row["gene_id"],
description=desc,
)
)
write_fasta(protein_records, protein_fasta_path)
write_fasta(nucleotide_records, nucleotide_fasta_path)
def build_blast_db_if_needed(reference_fasta: Path) -> None:
pin = reference_fasta.with_suffix(reference_fasta.suffix + ".pin")
psq = reference_fasta.with_suffix(reference_fasta.suffix + ".psq")
phr = reference_fasta.with_suffix(reference_fasta.suffix + ".phr")
if pin.exists() and psq.exists() and phr.exists():
return
cmd = ["makeblastdb", "-in", str(reference_fasta), "-dbtype", "prot"]
result = run_command(cmd)
if result["returncode"] != 0:
raise RuntimeError(f"makeblastdb failed:\n{result['stderr']}")
def parse_subject_name(subject_id: str, subject_description: str) -> Tuple[str, str]:
text = f"{subject_id} {subject_description}".strip().lower()
cas_family = "Cas-like"
subtype = "Unclassified"
patterns = [
("cas1", "Adaptation"),
("cas2", "Adaptation"),
("cas3", "Type I"),
("cas4", "Adaptation"),
("cas5", "Type I"),
("cas6", "Type I/III"),
("cas7", "Type I/III"),
("cas8", "Type I"),
("cas9", "Type II"),
("cas10", "Type III"),
("cas12", "Type V"),
("cpf1", "Type V"),
("cas13", "Type VI"),
("csn2", "Type II"),
("csm", "Type III"),
("cmr", "Type III"),
("csa", "Type I"),
("cse", "Type I"),
("csy", "Type I-F"),
]
for family, cls in patterns:
if family in text:
cas_family = family.upper()
subtype = cls
break
return cas_family, subtype
def search_cas_proteins(
genes_df: pd.DataFrame,
cas_reference_path: Optional[Path],
output_dir: Path,
config: AnalysisConfig,
) -> pd.DataFrame:
empty_cols = [
"gene_id", "contig", "start", "end", "strand", "protein_length_aa",
"subject_id", "subject_description", "cas_family", "cas_class",
"percent_identity", "alignment_length", "evalue", "bitscore",
"query_coverage_pct", "subject_coverage_pct"
]
if genes_df.empty or cas_reference_path is None or not cas_reference_path.exists():
return pd.DataFrame(columns=empty_cols)
query_faa = output_dir / "predicted_proteins.faa"
query_fna = output_dir / "predicted_genes.fna"
write_gene_fastas(genes_df, query_faa, query_fna)
build_blast_db_if_needed(cas_reference_path)
out_file = output_dir / "cas_blast.tsv"
# Biopython removed its command line wrapper classes (Bio.Blast.Applications),
# so blastp is called directly as a subprocess, the same way the other tools
# in this app call external programs.
outfmt = "6 qseqid sseqid pident length mismatch gapopen qstart qend sstart send evalue bitscore qlen slen stitle"
cmd = [
"blastp",
"-query", str(query_faa),
"-db", str(cas_reference_path),
"-evalue", "1e-5",
"-outfmt", outfmt,
"-max_target_seqs", "5",
"-out", str(out_file),
]
result = run_command(cmd)
if result["returncode"] != 0:
raise RuntimeError(f"blastp failed:\n{result['stderr']}")
if not out_file.exists() or out_file.stat().st_size == 0:
return pd.DataFrame(columns=empty_cols)
cols = [
"qseqid", "sseqid", "pident", "length", "mismatch", "gapopen",
"qstart", "qend", "sstart", "send", "evalue", "bitscore", "qlen", "slen", "stitle"
]
blast_df = pd.read_csv(out_file, sep="\t", names=cols)
if blast_df.empty:
return pd.DataFrame()
blast_df["query_coverage_pct"] = 100.0 * blast_df["length"] / blast_df["qlen"]
blast_df["subject_coverage_pct"] = 100.0 * blast_df["length"] / blast_df["slen"]
blast_df = blast_df[
(blast_df["pident"] >= config.min_cas_identity) &
(blast_df["subject_coverage_pct"] >= config.min_cas_coverage)
].copy()
if blast_df.empty:
return pd.DataFrame(columns=empty_cols)
blast_df = blast_df.sort_values(
by=["qseqid", "bitscore", "pident", "subject_coverage_pct"],
ascending=[True, False, False, False],
).drop_duplicates(subset=["qseqid"], keep="first")
merged = blast_df.merge(
genes_df[
["gene_id", "contig", "start", "end", "strand", "protein_length_aa"]
],
left_on="qseqid",
right_on="gene_id",
how="left",
)
family_info = merged.apply(
lambda r: parse_subject_name(r["sseqid"], str(r["stitle"])),
axis=1,
result_type="expand",
)
family_info.columns = ["cas_family", "cas_class"]
merged = pd.concat([merged, family_info], axis=1)
final_df = merged.rename(
columns={
"sseqid": "subject_id",
"stitle": "subject_description",
"pident": "percent_identity",
"length": "alignment_length",
}
)[empty_cols].sort_values(["contig", "start", "end"]).reset_index(drop=True)
return final_df
def link_crispr_and_cas(
arrays_df: pd.DataFrame,
cas_df: pd.DataFrame,
config: AnalysisConfig,
) -> pd.DataFrame:
empty_cols = [
"locus_id", "array_id", "contig", "array_start", "array_end",
"array_repeat_count", "array_spacer_count", "n_cas_genes",
"cas_gene_ids", "cas_families", "predicted_system_class",
"distance_to_nearest_cas_bp"
]
if arrays_df.empty:
return pd.DataFrame(columns=empty_cols)
loci = []
for idx, arr in arrays_df.iterrows():
contig_hits = cas_df[cas_df["contig"] == arr["contig"]].copy() if not cas_df.empty else pd.DataFrame()
if contig_hits.empty:
loci.append(
{
"locus_id": f"LOCUS_{idx + 1}",
"array_id": arr["array_id"],
"contig": arr["contig"],
"array_start": arr["start"],
"array_end": arr["end"],
"array_repeat_count": arr["repeat_count"],
"array_spacer_count": arr["spacer_count"],
"n_cas_genes": 0,
"cas_gene_ids": "",
"cas_families": "",
"predicted_system_class": "Orphan CRISPR array",
"distance_to_nearest_cas_bp": None,
}
)
continue
within = contig_hits[
(
(contig_hits["start"] >= arr["start"] - config.neighborhood_bp) &
(contig_hits["start"] <= arr["end"] + config.neighborhood_bp)
) |
(
(contig_hits["end"] >= arr["start"] - config.neighborhood_bp) &
(contig_hits["end"] <= arr["end"] + config.neighborhood_bp)
)
].copy()
if within.empty:
loci.append(
{
"locus_id": f"LOCUS_{idx + 1}",
"array_id": arr["array_id"],
"contig": arr["contig"],
"array_start": arr["start"],
"array_end": arr["end"],
"array_repeat_count": arr["repeat_count"],
"array_spacer_count": arr["spacer_count"],
"n_cas_genes": 0,
"cas_gene_ids": "",
"cas_families": "",
"predicted_system_class": "Orphan CRISPR array",
"distance_to_nearest_cas_bp": nearest_cas_distance(arr, contig_hits),
}
)
continue
families = within["cas_family"].fillna("").astype(str).tolist()
predicted_class = infer_system_class(families)
loci.append(
{
"locus_id": f"LOCUS_{idx + 1}",
"array_id": arr["array_id"],
"contig": arr["contig"],
"array_start": arr["start"],
"array_end": arr["end"],
"array_repeat_count": arr["repeat_count"],
"array_spacer_count": arr["spacer_count"],
"n_cas_genes": int(len(within)),
"cas_gene_ids": ";".join(within["gene_id"].astype(str).tolist()),
"cas_families": ";".join(within["cas_family"].astype(str).tolist()),
"predicted_system_class": predicted_class,
"distance_to_nearest_cas_bp": nearest_cas_distance(arr, within),
}
)
return pd.DataFrame(loci)
def nearest_cas_distance(arr_row: pd.Series, cas_df: pd.DataFrame) -> Optional[int]:
if cas_df.empty:
return None
distances = []
arr_start, arr_end = int(arr_row["start"]), int(arr_row["end"])
for _, row in cas_df.iterrows():
gstart, gend = int(row["start"]), int(row["end"])
if gend < arr_start:
distances.append(arr_start - gend)
elif gstart > arr_end:
distances.append(gstart - arr_end)
else:
distances.append(0)
return int(min(distances)) if distances else None
def infer_system_class(families: List[str]) -> str:
fams = set(f.upper() for f in families if isinstance(f, str) and f)
if "CAS9" in fams or "CSN2" in fams:
return "Type II-like"
if "CAS12" in fams or "CPF1" in fams:
return "Type V-like"
if "CAS13" in fams:
return "Type VI-like"
if "CAS10" in fams or any(x.startswith("CSM") or x.startswith("CMR") for x in fams):
return "Type III-like"
if "CAS3" in fams or "CAS5" in fams or "CAS8" in fams:
return "Type I-like"
if "CAS1" in fams and "CAS2" in fams:
return "Adaptation module with nearby array"
return "CRISPR-Cas candidate locus"
def summary_dict(records: List[SeqRecord], arrays_df: pd.DataFrame, genes_df: pd.DataFrame, cas_df: pd.DataFrame, loci_df: pd.DataFrame) -> dict:
genome_bp = sum(len(r.seq) for r in records)
total_spacers = int(arrays_df["spacer_count"].sum()) if not arrays_df.empty else 0
linked_loci = 0
if not loci_df.empty:
linked_loci = int((loci_df["n_cas_genes"] > 0).sum())
return {
"n_contigs": len(records),
"genome_bp": int(genome_bp),
"n_crispr_arrays": int(len(arrays_df)),
"n_genes": int(len(genes_df)),
"n_cas_hits": int(len(cas_df)),
"n_linked_loci": linked_loci,
"total_spacers": total_spacers,
}
def run_full_analysis(
genome_fasta_path: Path,
cas_reference_path: Optional[Path],
output_dir: Path,
config: AnalysisConfig,
) -> Dict[str, pd.DataFrame]:
records = read_fasta(genome_fasta_path)
arrays_df = detect_crispr_arrays(records, config)
genes_df = predict_genes(records, config)
cas_df = search_cas_proteins(genes_df, cas_reference_path, output_dir, config)
loci_df = link_crispr_and_cas(arrays_df, cas_df, config)
summary = summary_dict(records, arrays_df, genes_df, cas_df, loci_df)
return {
"summary": summary,
"crispr_arrays": arrays_df,
"genes": genes_df,
"cas_hits": cas_df,
"loci": loci_df,
}
def save_gff(arrays_df: pd.DataFrame, cas_df: pd.DataFrame, out_path: Path) -> None:
lines = ["##gff-version 3"]
for _, row in arrays_df.iterrows():
attrs = (
f"ID={row['array_id']};"
f"RepeatCount={row['repeat_count']};"
f"SpacerCount={row['spacer_count']};"
f"ConsensusRepeat={row['consensus_repeat']}"
)
lines.append(
"\t".join(
[
str(row["contig"]),
"CRISPRCasTool",
"CRISPR_array",
str(int(row["start"])),
str(int(row["end"])),
".",
str(row["strand"]),
".",
attrs,
]
)
)
for _, row in cas_df.iterrows():
attrs = (
f"ID={row['gene_id']};"
f"Name={row['cas_family']};"
f"Class={row['cas_class']};"
f"Bitscore={row['bitscore']};"
f"Evalue={row['evalue']}"
)
lines.append(
"\t".join(
[
str(row["contig"]),
"CRISPRCasTool",
"Cas_gene",
str(int(row["start"])),
str(int(row["end"])),
".",
str(row["strand"]),
".",
attrs,
]
)
)
out_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def save_results_bundle(results: Dict[str, pd.DataFrame], output_dir: Path, sample_name: str) -> Path:
arrays_df = results["crispr_arrays"]
genes_df = results["genes"]
cas_df = results["cas_hits"]
loci_df = results["loci"]
summary = results["summary"]
arrays_csv = output_dir / f"{sample_name}_crispr_arrays.csv"
genes_csv = output_dir / f"{sample_name}_predicted_genes.csv"
cas_csv = output_dir / f"{sample_name}_cas_hits.csv"
loci_csv = output_dir / f"{sample_name}_crispr_cas_loci.csv"
summary_json = output_dir / f"{sample_name}_summary.json"
gff_path = output_dir / f"{sample_name}_features.gff3"
arrays_df.to_csv(arrays_csv, index=False)
genes_df.to_csv(genes_csv, index=False)
cas_df.to_csv(cas_csv, index=False)
loci_df.to_csv(loci_csv, index=False)
summary_json.write_text(pd.Series(summary).to_json(indent=2), encoding="utf-8")
save_gff(arrays_df, cas_df, gff_path)
bundle_path = output_dir / f"{sample_name}_crispr_cas_results.zip"
with zipfile.ZipFile(bundle_path, "w", zipfile.ZIP_DEFLATED) as zf:
for file_path in [arrays_csv, genes_csv, cas_csv, loci_csv, summary_json, gff_path]:
if file_path.exists():
zf.write(file_path, arcname=file_path.name)
return bundle_path
def render_overview_plot(arrays_df: pd.DataFrame, cas_df: pd.DataFrame):
fig, ax = plt.subplots(figsize=(10, 4))
n_arrays = len(arrays_df)
n_cas = len(cas_df)
labels = ["CRISPR arrays", "Cas hits"]
values = [n_arrays, n_cas]
ax.bar(labels, values)
ax.set_ylabel("Count")
ax.set_title("Overview of detected CRISPR arrays and Cas-associated genes")
for i, v in enumerate(values):
ax.text(i, v + max(values + [1]) * 0.03, str(v), ha="center")
fig.tight_layout()
return fig
def render_locus_plot(locus_row: pd.Series, arrays_df: pd.DataFrame, cas_df: pd.DataFrame, neighborhood_bp: int):
contig = locus_row["contig"]
arr_start = int(locus_row["array_start"])
arr_end = int(locus_row["array_end"])
window_start = max(1, arr_start - neighborhood_bp)
window_end = arr_end + neighborhood_bp
fig, ax = plt.subplots(figsize=(12, 2.8))
ax.set_title(f"{locus_row['locus_id']} | {contig}")
ax.set_xlim(window_start, window_end)
ax.set_ylim(0, 10)
ax.hlines(5, window_start, window_end, linewidth=2)
arrs = arrays_df[
(arrays_df["contig"] == contig) &
(arrays_df["end"] >= window_start) &
(arrays_df["start"] <= window_end)
]
hits = cas_df[
(cas_df["contig"] == contig) &
(cas_df["end"] >= window_start) &
(cas_df["start"] <= window_end)
]
for _, row in arrs.iterrows():
ax.add_patch(
plt.Rectangle(
(int(row["start"]), 4.2),
int(row["end"]) - int(row["start"]),
1.6,
fill=True,
alpha=0.7,
)
)
ax.text(
(int(row["start"]) + int(row["end"])) / 2,
6.2,
row["array_id"],
ha="center",
va="bottom",
fontsize=8,
)
for _, row in hits.iterrows():
y = 2.2 if row["strand"] == "+" else 7.0
ax.add_patch(
plt.Rectangle(
(int(row["start"]), y),
int(row["end"]) - int(row["start"]),
0.9,
fill=True,
alpha=0.85,
)
)
ax.text(
(int(row["start"]) + int(row["end"])) / 2,
y + 1.0,
str(row["cas_family"]),
ha="center",
va="bottom",
fontsize=7,
rotation=0,
)
ax.set_xlabel("Genomic position (bp)")
ax.set_yticks([])
fig.tight_layout()
return fig