Commit a0e434f5 by Vinh-Son PHO

first commit

parents
The following persons contributed to the actual implementation of the software:
- Vinh-Son PHO
The following persons contributed to the article's work:
- Alessandro Natale BIANCHI
- Chris Bowler
- Alessandra CARBONE
This diff is collapsed. Click to expand it.
# PLMView
## Introduction
PLMView is a software that uses Protein Language Models (PLMs) to cluster functionally similar amino acid sequences. It takes fasta files as input and outputs:
1. A projection of the input sequences in a numerical space.
2. A Newick tree (.nhx) that contains the functional clusters.
This Newick tree can be easily displayed using iTOL (or other tree visualisation tools) and manipulated using ete3.
## Requirements
Make sure that you have downloaded our conservation predictor, it should be in "PLMView/src/cons_models/Mulan/MODEL_NAME.pt".
Python libraries : NumPy, Cython, SciPy, PyTorch, Transformers, ete3.
To be able to use CUDA acceleration (for both `PLMV_embed` and `PLMV_compare_cuda`), make sure that PyTorch is installed correctly with CUDA and that you use the python interpreter assiociated with that pytorch installation.
To test wether CUDA can be used for parallelized alignment, try importing ``` alignment_cuda``` in python.
## Installation
To install, go to the `src` directory and run :
```console
python setup.py build_ext --inplace
```
This step is necessary to compile some Cython, C++ and CUDA files. The CUDA files are compiled and usable only if PyTorch and CUDA are correctly installed.
Furthermore, you can add :
```
export PATH=$PATH:/path/to/PLMView/scripts
```
to your .bashrc file to call the following scripts globally.
## Simplified pipeline
Bash script to run PLMView to build the functional tree starting from sequences and to compute explanations are provided in `scripts`. Feel free to change the different constants in those scripts.
We highly recommend, running `PLMV_run.sh` with carefully selected `min_seq_id` and `coverage`, used for automatic anchor selection using `mmseqs easy-cluster`, based on your dataset. Optimal values may depends on factors such as variability withing sequence, multi or single domain dataset, etc...
We also recommend, using no more than a few thousand anchors, for computational effectiveness.
## Detailed pipeline
If you want more control over the different hyperparameters/aligment tools, you can run the PLMView pipeline "manually" :
1. Select your input sequences.
2. Select the anchor sequences. They can be a subset of the input sequences or a domain associated with the input sequences eg. PF00001 for opsins. Be careful, while naming anchors and sequences. Any duplicate name will be copied from anchors to sequence (to reduce computational cost).
3. Embed your input and anchor sequences using :
```console
python PLMView/src/PLMV_embed.py --anchors anchors.fasta --sequences input.fasta --anchors-dir anchors --sequences-dir sequences
```
Note that on its first execution, step 3. will download the chosen Protein Language Machine and cache it, this can take several minutes.
4. Compare the input sequences to the anchors to create the representation space using:
```console
python PLMView/src/PLMV_compare.py --anchors-dir anchors --sequences-dir sequences --out-dir out_comp
```
5. Cluster the sequences in the representation space using:
```console
python PLMView/src/PLMV_tree_SCUT.py --repr-space out_comp --out-dir out_tree --prefix cluster_tree
```
or
```console
python PLMView/src/PLMV_tree_ward.py --repr-space out_comp --out-dir out_tree --prefix cluster_tree
```
6. Given a tree built using PLMV_tree_SCUT and the anchors used to build it, one can infer the position of a new sequence in the tree using:
```console
python PLMView/src/PLMV_embed.py --sequences new_input.fasta --sequences-dir new_sequences
python PLMView/src/PLMV_compare.py --anchors-dir anchors --sequences-dir new_sequences --out-dir new_out_comp
python PLMView/src/PLMV_infer.py --repr-space new_out_comp --tree-path out_tree/cluster_tree.pkl --out-dir out --prefix inferred_leaves
```
7. Given a Fasta alignment, you can generate scores "explaining" the importance of each position in the overall classification of the sequences contained in said alignment. Generating scores for the left and right branches in a tree can be really helpful when looking at which positions are important for the split.
```console
python PLMView/src/PLMV_explain.py --anchors-dir anchors --sequences-dir sequences --repr-space out_comp --out-dir out_explain --prefix scores --alignment-file alignment.fasta --tree out_tree/tree.pkl --node ROOT
```
## Remarks
To use `PLMV_explain.py` and `PLMV_infer.py`, if your tree is too large try setting `sys.setrecursionlimit()` to 10000.
`PLMV_embed.py --compile True` requires torch > 2.0, and is probably best used for very large datasets (>20k), for smaller ones, the compiling overhead outweights the speedup, VRAM usage is also hard to track so chose `--max-batch-size mbs --vram-threshold th` wisely.
Support for mixed precision for embed has been added, however actual VRAM usage is poorly tracked so chose `--max-batch-size mbs --vram-threshold th` wisely when using bf16 or fp16.
Support for FlashAttention depends on the PLM being used. Ankh does not support it at the time of writing (Check HuggingFace's T5EncoderModel).
fp16 mixed precision during `PLMV_embed.py` is quite unstable, bf16/fp32 are to be preferred. This doesn't seem to affect `PLMV_compare.py`. So for example, feel free to embed using fp32 and compare using fp16.
## Citing PLMView
If you use PLMView in your research, please cite the corresponding paper.
## License
PLMView is distributed under the terms of the CC BY-SA 4.0 License.
\ No newline at end of file
#!/usr/bin/env bash
set -euo pipefail
# -------------------------
# Script + project root
# -------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$SCRIPT_DIR/.."
SRC_DIR="$PROJECT_ROOT/src"
# -------------------------
# Usage
# -------------------------
BASE_NAME="${1:-}"
SEQ_INT="${2:-}"
WORKDIR="${3:-}"
# Optional 4th argument
NODES="${4:-}"
if [[ -z "$BASE_NAME" || -z "$SEQ_INT" || -z "$WORKDIR" ]]; then
echo "Error: 3 or 4 arguments required"
echo "Usage: $0 <basename> <seq-of-interest> <work-dir> [nodes]"
exit 1
fi
OUT_DIR="$WORKDIR/out"
# -------------------------
# Python scripts (FIXED)
# -------------------------
SCRIPT_SAMPLE="$SRC_DIR/PLMV_sample_explain.py"
SCRIPT_SCORE="$SRC_DIR/PLMV_explain.py"
SCRIPT_PLOT="$SRC_DIR/PLMV_viz_explain.py"
SCRIPT_LOGO="$SRC_DIR/PLMV_Logo_scaled.py"
# -------------------------
# Paths
# -------------------------
OUT_SAMPLE="$OUT_DIR/out_sample_${BASE_NAME}"
OUT_SCORE="$OUT_DIR/out_score_${BASE_NAME}"
OUT_LOGO="$OUT_DIR/out_logo_${BASE_NAME}"
OUTPUT_DIR="$OUT_DIR/out_explain_viz_${BASE_NAME}"
K=0
N_SAMPLE=64
SEED="42"
ANCHOR_DIR="$WORKDIR/anchors/anchors_${BASE_NAME}"
SEQUENCE_DIR="$WORKDIR/sequences/sequences_${BASE_NAME}"
REPR_SPACE="$OUT_DIR/out_comp_${BASE_NAME}"
TREE="$OUT_DIR/out_tree_${BASE_NAME}/${BASE_NAME}"
ANNOT=""
# -------------------------
# Input FASTA detection
# -------------------------
IN_FASTA="$WORKDIR/input/${BASE_NAME}.fasta"
IN_FA="$WORKDIR/input/${BASE_NAME}.fa"
IN_FAA="$WORKDIR/input/${BASE_NAME}.faa"
if [[ -f "$IN_FASTA" ]]; then
SEQUENCE_FN="$IN_FASTA"
elif [[ -f "$IN_FA" ]]; then
SEQUENCE_FN="$IN_FA"
elif [[ -f "$IN_FAA" ]]; then
SEQUENCE_FN="$IN_FAA"
else
echo "Error: no input fasta found for base: $BASE_NAME"
exit 1
fi
# -------------------------
# Debug
# -------------------------
echo "Starting pipeline:"
echo "TREE=$TREE"
echo "SEQ_INT=$SEQ_INT"
echo "SEQUENCE_FN=$SEQUENCE_FN"
echo "NODES=$NODES"
# -------------------------
# Create output dirs
# -------------------------
mkdir -p "$OUT_SAMPLE" "$OUT_SCORE" "$OUTPUT_DIR" "$OUT_LOGO"
# -------------------------
# Step 1: sample explain
# -------------------------
echo "PLMV_sample_explain.py..."
python "$SCRIPT_SAMPLE" \
--tree "${TREE}.nhx" \
--sequences "$SEQUENCE_FN" \
--seq-of-interest "$SEQ_INT" \
--out-dir "$OUT_SAMPLE" \
--prefix "$BASE_NAME" \
--k "$K" \
--n-sample "$N_SAMPLE" \
--seed "$SEED" \
--nodes "$NODES"
# -------------------------
# Step 2: MAFFT alignment
# -------------------------
echo "Running MAFFT alignment..."
mafft --genafpair --maxiterate 1000 \
"${OUT_SAMPLE}/${BASE_NAME}.fasta" \
> "${OUT_SAMPLE}/${BASE_NAME}_ali.fasta"
RECOMPUTED_NODES="$(cat "${OUT_SAMPLE}/${BASE_NAME}_nodes.txt")"
# -------------------------
# Step 3: scoring
# -------------------------
echo "PLMV_explain.py..."
python "$SCRIPT_SCORE" \
--anchors-dir "$ANCHOR_DIR" \
--sequences-dir "$SEQUENCE_DIR" \
--repr-space "$REPR_SPACE" \
--out-dir "$OUT_SCORE" \
--prefix "$BASE_NAME" \
--alignment-file "${OUT_SAMPLE}/${BASE_NAME}_ali.fasta" \
--tree "${TREE}.pkl" \
--nodes "$RECOMPUTED_NODES" \
--h5 "" \
--explained-variance "1" \
--th "0" \
--th-seq "0" \
--force "false" \
--sys-setrecursionlimit "" \
--use-cuda "True" \
--preload-device "cpu" \
--PLM "ElnaggarLab/ankh-large" \
--verbose "True"
# -------------------------
# Step 4: visualization
# -------------------------
echo "PLMV_viz_explain.py..."
python "$SCRIPT_PLOT" \
--explain-dir "$OUT_SCORE" \
--out-dir "$OUTPUT_DIR" \
--sampled-MSA "${OUT_SAMPLE}/${BASE_NAME}_ali.fasta" \
--tree "${TREE}.nhx" \
--annot-cols "$ANNOT"
# -------------------------
# Step 5: logos
# -------------------------
echo "PLMV_Logo.py..."
python "$SCRIPT_LOGO" \
--viz-dir "$OUTPUT_DIR" \
--sampled-MSA "${OUT_SAMPLE}/${BASE_NAME}_ali.fasta" \
--tree "${TREE}.nhx" \
--out-dir "$OUT_LOGO"
echo "Pipeline completed successfully. Outputs in $OUTPUT_DIR."
#!/usr/bin/env bash
set -euo pipefail
# -------------------------
# Root resolution
# -------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$SCRIPT_DIR/.."
SRC_DIR="$PROJECT_ROOT/src"
# -------------------------
# Usage
# -------------------------
BASE_NAME="${1:-}"
SEQ_INT="${2:-}"
WORKDIR="${3:-}"
REFNODE="${4:-}"
NODES="${5:-}"
if [[ $# -lt 4 || $# -gt 5 ]]; then
echo "Error: 4 or 5 arguments required: basename seq-of-interest work-dir refnode [nodes]"
echo "Usage: $0 <basename> <seq-of-interest> <work-dir> <refnode> [nodes]"
exit 1
fi
OUT_DIR="$WORKDIR/out"
# -------------------------
# Python scripts (FIXED)
# -------------------------
SCRIPT_SAMPLE="$SRC_DIR/PLMV_sample_explain_1vsall.py"
SCRIPT_SCORE="$SRC_DIR/PLMV_explain.py"
SCRIPT_PLOT="$SRC_DIR/PLMV_viz_explain_1vsall.py"
SCRIPT_LOGO="$SRC_DIR/PLMV_Logo_scaled_1vsall.py"
# -------------------------
# Output structure
# -------------------------
RUN_DIR="$OUT_DIR/out_1vsall_${REFNODE}_${NODES}"
OUT_SAMPLE="$RUN_DIR/out_sample_${BASE_NAME}"
OUT_SCORE="$RUN_DIR/out_score_${BASE_NAME}"
OUT_LOGO="$RUN_DIR/out_logo_${BASE_NAME}"
OUTPUT_DIR="$RUN_DIR/out_explain_viz_${BASE_NAME}"
# -------------------------
# Parameters
# -------------------------
K=0
N_SAMPLE=64
SEED="42"
ANCHOR_DIR="$WORKDIR/anchors/anchors_${BASE_NAME}"
SEQUENCE_DIR="$WORKDIR/sequences/sequences_${BASE_NAME}"
REPR_SPACE="$OUT_DIR/out_comp_${BASE_NAME}"
TREE="$OUT_DIR/out_tree_${BASE_NAME}/${BASE_NAME}"
ANNOT=""
# -------------------------
# Input FASTA detection
# -------------------------
IN_FASTA="$WORKDIR/input/${BASE_NAME}.fasta"
IN_FA="$WORKDIR/input/${BASE_NAME}.fa"
IN_FAA="$WORKDIR/input/${BASE_NAME}.faa"
if [[ -f "$IN_FASTA" ]]; then
SEQUENCE_FN="$IN_FASTA"
elif [[ -f "$IN_FA" ]]; then
SEQUENCE_FN="$IN_FA"
elif [[ -f "$IN_FAA" ]]; then
SEQUENCE_FN="$IN_FAA"
else
echo "Error: no input fasta found for $BASE_NAME"
exit 1
fi
# -------------------------
# Debug
# -------------------------
echo "Starting pipeline:"
echo "TREE=$TREE"
echo "SEQ_INT=$SEQ_INT"
echo "REFNODE=$REFNODE"
echo "NODES=$NODES"
echo "SEQUENCE_FN=$SEQUENCE_FN"
# -------------------------
# Create dirs
# -------------------------
mkdir -p "$OUT_SAMPLE" "$OUT_SCORE" "$OUTPUT_DIR" "$OUT_LOGO"
# -------------------------
# Step 1
# -------------------------
echo "PLMV_sample_explain.py..."
python "$SCRIPT_SAMPLE" \
--tree "${TREE}.nhx" \
--sequences "$SEQUENCE_FN" \
--seq-of-interest "$SEQ_INT" \
--out-dir "$OUT_SAMPLE" \
--prefix "$BASE_NAME" \
--k "$K" \
--n-sample "$N_SAMPLE" \
--seed "$SEED" \
--nodes "$NODES" \
--refnode "$REFNODE"
# -------------------------
# Step 2
# -------------------------
echo "Running MAFFT alignment..."
mafft --genafpair --maxiterate 1000 \
"${OUT_SAMPLE}/${BASE_NAME}.fasta" \
> "${OUT_SAMPLE}/${BASE_NAME}_ali.fasta"
RECOMPUTED_NODES="$(cat "${OUT_SAMPLE}/${BASE_NAME}_nodes.txt")"
# -------------------------
# Step 3
# -------------------------
echo "PLMV_explain.py..."
python "$SCRIPT_SCORE" \
--anchors-dir "$ANCHOR_DIR" \
--sequences-dir "$SEQUENCE_DIR" \
--repr-space "$REPR_SPACE" \
--out-dir "$OUT_SCORE" \
--prefix "$BASE_NAME" \
--alignment-file "${OUT_SAMPLE}/${BASE_NAME}_ali.fasta" \
--tree "${TREE}.pkl" \
--nodes "$RECOMPUTED_NODES" \
--h5 "" \
--explained-variance "1" \
--th "0" \
--th-seq "0" \
--force "false" \
--sys-setrecursionlimit "" \
--use-cuda "True" \
--preload-device "cpu" \
--PLM "ElnaggarLab/ankh-large" \
--verbose "True"
# -------------------------
# Step 4
# -------------------------
echo "PLMV_viz_explain.py..."
python "$SCRIPT_PLOT" \
--explain-dir "$OUT_SCORE" \
--out-dir "$OUTPUT_DIR" \
--sampled-MSA "${OUT_SAMPLE}/${BASE_NAME}_ali.fasta" \
--tree "${TREE}.nhx" \
--annot-cols "$ANNOT" \
--refnode "$REFNODE"
# -------------------------
# Step 5
# -------------------------
echo "PLMV_Logo_scaled_1vsall.py..."
python "$SCRIPT_LOGO" \
--viz-dir "$OUTPUT_DIR" \
--sampled-MSA "${OUT_SAMPLE}/${BASE_NAME}_ali.fasta" \
--tree "${TREE}.nhx" \
--out-dir "$OUT_LOGO" \
--refnode "$REFNODE"
echo "Pipeline completed successfully. Outputs in $OUTPUT_DIR."
#!/usr/bin/env bash
set -euo pipefail
# -------------------------
# Inputs
# -------------------------
FASTA_FILE="${1:-}"
WORKDIR="${2:-}"
# Optional args (3rd and 4th positional)
MIN_SEQ_ID="${3:-0.6}"
COVERAGE="${4:-0.5}"
if [[ -z "$FASTA_FILE" || -z "$WORKDIR" ]]; then
echo "Usage: $0 <input_fasta> <working_dir> [min_seq_id=0.6] [coverage=0.5]"
exit 1
fi
if [[ ! -f "$FASTA_FILE" ]]; then
echo "Error: fasta file not found: $FASTA_FILE"
exit 1
fi
# -------------------------
# Setup working directory
# -------------------------
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$SCRIPT_DIR/.."
INPUT_DIR="$WORKDIR/input"
CLUST_DIR="$WORKDIR/clust"
ANCHORS_DIR="$WORKDIR/anchors"
SEQUENCES_DIR="$WORKDIR/sequences"
OUT_DIR="$WORKDIR/out"
LOG_DIR="$WORKDIR/log"
TMP_DIR="$WORKDIR/tmp"
mkdir -p \
"$INPUT_DIR" \
"$CLUST_DIR" \
"$ANCHORS_DIR" \
"$SEQUENCES_DIR" \
"$OUT_DIR" \
"$LOG_DIR" \
"$TMP_DIR"
# -------------------------
# Copy input fasta
# -------------------------
fname=$(basename "$FASTA_FILE")
base="${fname%.*}"
cp "$FASTA_FILE" "$INPUT_DIR/$fname"
f="$INPUT_DIR/$fname"
logfile="$LOG_DIR/${base}.log"
echo "Processing single file: $f"
echo "Working directory: $WORKDIR"
echo "Logging to: $logfile"
# -------------------------
# Pipeline
# -------------------------
{
echo -e "===== Start\t\t$base: $(date) ====="
# 1. mmseqs clustering
mmseqs easy-cluster \
"$INPUT_DIR/${base}."* \
"$CLUST_DIR/${base}" \
"$TMP_DIR" \
--min-seq-id "$MIN_SEQ_ID" \
-c "$COVERAGE" \
>"$LOG_DIR/mmseqs_${base}.log" 2>&1
input_nseq=$(grep -c "^>" "$f")
repr_file="$CLUST_DIR/${base}_rep_seq.fasta"
repr_nseq=$(grep -c "^>" "$repr_file")
echo "Summary: input=${input_nseq}, representatives=${repr_nseq}"
echo -e "===== Embed\t\t$base: $(date) ====="
# 2. Embed
python -u "$PROJECT_ROOT/src/PLMV_embed.py" \
--anchors "$repr_file" \
--sequences "$f" \
--anchors-dir "$ANCHORS_DIR/anchors_${base}" \
--sequences-dir "$SEQUENCES_DIR/sequences_${base}" \
--vram-threshold 0.8 \
--dtype fp32 \
--log "$LOG_DIR"
echo -e "===== Compare\t$base: $(date) ====="
# 3. Compare
python -u "$PROJECT_ROOT/src/PLMV_compare.py" \
--anchors-dir "$ANCHORS_DIR/anchors_${base}" \
--sequences-dir "$SEQUENCES_DIR/sequences_${base}" \
--out-dir "$OUT_DIR/out_comp_${base}" \
--use-cuda True \
--dtype fp16 \
--batch-size 32 \
--preload-device cpu
echo -e "===== SCUT\t\t$base: $(date) ====="
# 4. Tree
python -u "$PROJECT_ROOT/src/PLMV_tree_SCUT.py" \
--repr-space "$OUT_DIR/out_comp_${base}" \
--out-dir "$OUT_DIR/out_tree_${base}" \
--prefix "${base}" \
--seed 42 \
--n-min 1
echo -e "===== End\t\t$base: $(date) ====="
} >"$logfile" 2>&1
echo "Done: $base"
echo "Results in: $WORKDIR"
from setuptools import setup, Extension, find_packages
from Cython.Build import cythonize
from torch.utils.cpp_extension import BuildExtension, CUDAExtension, CUDA_HOME
import numpy
extensions = cythonize([
Extension(
name="aligner.alignment_cython",
sources=["src/aligner/alignment_cython.pyx"],
include_dirs=[numpy.get_include()],
)
])
# Add CUDA extension only if CUDA is available
if CUDA_HOME is not None:
extensions.append(
CUDAExtension(
name="aligner.alignment_cuda",
sources=[
"src/aligner/bindings.cpp",
"src/aligner/alignment_kernel.cu",
],
#extra_link_args=[
# "-Wl,-rpath,$ORIGIN/../../../torch/lib"
#],
)
)
else:
print("CUDA not found. Skipping build of 'alignment_cuda' extension.")
setup(
name="plmview",
version='0.1.0',
description="PLMView",
license="CC BY-NC-SA 4.0",
ext_modules=extensions,
packages=find_packages(where="src"),
package_dir={"": "src"},
cmdclass={"build_ext": BuildExtension},
)
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
import torch
import sys
TTY = None # will be initialized on first use
def _get_tty():
global TTY
if TTY is None:
try:
TTY = open("/dev/tty", "w")
except OSError:
TTY = sys.stdout
return TTY
def dim_reduc(mat,k=None,explained_var=0.999):
"""
compute svd, on the centered matrix (not standardardized)
"""
X_mean = mat.mean(dim=0)
X = mat - X_mean
_, S, Vh = torch.linalg.svd(X)
S = S**2
S = S/S.sum()
if k is None:
k = torch.where((S.cumsum(0) >= explained_var))[0][0].item()
lin_proj = Vh[:,:k]
return X_mean, lin_proj
def project(mat,m,w):
return ((mat - m) @ w)
def printProgressBar(
iteration,
total,
prefix='',
suffix='',
decimals=1,
length=50,
fill='█',
printEnd="\r",
):
"""
Call in a loop to create terminal progress bar
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
tty = _get_tty()
print(f'\r{prefix} |{bar}| {percent}% {suffix}', end=printEnd, file=tty, flush=True)
if iteration == total:
print(file=tty, flush=True)
def parse_fasta(fasta_file):
"""Parse a fasta file and return a dictionary."""
with open(fasta_file) as f:
lines = f.readlines()
fasta_dict = {}
for line in lines:
if line.startswith(">"):
key = line.strip().split()[0][1:]
fasta_dict[key] = ""
else:
fasta_dict[key] += line.strip().upper()
return fasta_dict
def split_ali_node(ali_file,treefile, node_name):
"""Split a fasta alignment using a node in a tree passed as input"""
import pickle
fasta_dict = parse_fasta(ali_file)
with open(treefile, 'rb') as handle:
tree = pickle.load(handle)
node = tree&node_name
left,right = node.children
neg_ids = [leaf.name for leaf in left]
pos_ids = [leaf.name for leaf in right]
neg_path = ali_file[:-6] + "_"+node_name+"_neg"+".fasta"
pos_path = ali_file[:-6] + "_"+node_name+"_pos"+".fasta"
with open(neg_path,"w") as f_neg:
with open(pos_path,"w") as f_pos:
for id in fasta_dict:
if id in neg_ids:
f_neg.write(">"+id+"\n"+fasta_dict[id]+"\n")
if id in pos_ids:
f_pos.write(">"+id+"\n"+fasta_dict[id]+"\n")
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
"""
Given an MSA, compute (and aggregate) the contribution at different nodes.
"""
import sys, os, argparse
import gc
import time
import h5py
import torch
import torch.nn.functional as F
torch.backends.cuda.matmul.allow_tf32 = True
from aligner.alignment_cython import compute_ali_mat
from aligner.alignment_cython import compute_alignment
import mulan
from mulan.modules import LightAttModel
import numpy as np
import pickle
from PLMV_common import dim_reduc, project, printProgressBar, parse_fasta
from PLMV_tree_SCUT import SpectralBiCoClustering
from PLMV_compare import squared_euc_dist, compute_similarity_matrix_plain_rbf, pairwise_cos_sim, get_anc_cons_score, load_anchor
def get_pos_dict(fasta_dict):
"""return a dictionary containing the list of positions of each residue in alignment"""
res_dict = {}
for k in fasta_dict:
ali_seq = fasta_dict[k]
res_dict[k] = [e for e,i in enumerate(ali_seq) if i not in [".","-"]]
return res_dict
def get_ali_path(embedding1,embedding2, cons_scores):
sm = cons_scores*compute_similarity_matrix_plain_rbf(embedding1, embedding2)
cs = cons_scores*pairwise_cos_sim(embedding1, embedding2)
val = sm + cs
val_cpu = val.cpu().numpy()
path = np.zeros_like(val_cpu,dtype=np.int32)
exit_code = compute_alignment(path,val_cpu,*val_cpu.shape)
return path
def get_weight_residues_seq_anc(anc,seq,cons_scores):
path = torch.tensor(get_ali_path(anc,seq,cons_scores)).to(anc.device)
denom = cons_scores.sum()
sm = (cons_scores*compute_similarity_matrix_plain_rbf(anc, seq))
cs = (cons_scores*pairwise_cos_sim(anc, seq))
sm = (path * sm).sum(0)/denom
cs = (path * cs).sum(0)/denom
return sm, cs
def get_score_per_pos(ali_file, treefile, node_name, repr_space, anchor_dir, sequence_dir, cons_model, h5_path,exp_var, attentions, th_seq, th,device,preload_device,verbose):
with open(treefile, 'rb') as handle:
tree = pickle.load(handle)
node = tree&node_name
ali_dict = parse_fasta(ali_file)
ali_len = len(next(iter(ali_dict.values())))
anc_list = sorted(os.listdir(anchor_dir))
seq_list = [i+".pt" for i in ali_dict.keys()]
R = torch.load(os.path.join(repr_space,"repr_space_mat.pt"),weights_only=True)
V = node.V
S = node.S
cd = node.cd
with torch.inference_mode():
if verbose: print("[Preloading]")
l_anc = []
l_mw = []
l_cons = []
cpt = 0
tot_iter = len(anc_list)
for anc_name in anc_list:
#load and preprocess anchor, conservation scores, and parameters for projection
anc, cons_scores = get_anc_cons_score(anchor_dir,anc_name,device,preload_device,cons_model,h5_path,th,attentions)
l_anc.append(anc)
l_cons.append(cons_scores)
cpt +=1
if verbose: printProgressBar(cpt,tot_iter)
del anc
if th_seq <= 0:
cons_model = None
del attentions
gc.collect()
torch.cuda.empty_cache()
with open(os.path.join(repr_space,"sequences_used.txt"),"r") as f:
lines = f.readlines()
l_seq = [line[:-1] for line in lines]
with torch.inference_mode():
score = np.zeros((len(seq_list),ali_len))
#score = np.zeros(ali_len)
if verbose: print("[Comparison]")
cpt = 0
tot_iter = len(anc_list) * len(seq_list)
for s,seq_name in enumerate(seq_list):
#get ali pos
seq_fasta = ali_dict[seq_name[:-3]]
pos = [e for e,aa in enumerate(seq_fasta) if aa not in ['-','.']]
seqnum = l_seq.index(seq_name)
#TODO for any seq (not necessarily one that is in the tree) ???
rep = R[seqnum]
rd = np.asarray(1.0 / np.sqrt(rep.sum(axis=-1))).squeeze() #more normalisation
rd = np.where(~np.isfinite(rd), 0, rd)
seq_full = torch.load(os.path.join(sequence_dir,seq_name),map_location=device,weights_only=True).float()
res1 = np.zeros(ali_len)
for k,anc_name in enumerate(anc_list):
#fetching the anchors
anc, cons_scores = load_anchor(k,l_anc,l_cons,preload_device, device)
seq = seq_full
s1,s2 = get_weight_residues_seq_anc(anc,seq,cons_scores)
s1,s2 = np.array(s1.cpu()),np.array(s2.cpu())
s1_n = rd * s1 * cd[2*k]
s2_n = rd * s2 * cd[2*k+1]
val_1 = V[2*k] * s1_n/S
val_2 = V[2*k+1] * s2_n/S
res1[pos] += val_1
res1[pos] += val_2
cpt+=1
if verbose: printProgressBar(cpt,tot_iter)
score[s] = res1
#score += res1
return score
def main():
script_dir = os.path.dirname(__file__)
cons_model_path = os.path.join(script_dir,"cons_models/Mulan/mulan_")
parser = argparse.ArgumentParser()
parser.add_argument('--anchors-dir', dest='anchor_dir', default='anchors', type=str, help='folder containing anchors embeddings')
parser.add_argument('--sequences-dir', dest='sequence_dir', default='sequences', type=str, help='folder containing sequences embeddings')
parser.add_argument('--repr-space', dest='repr_space', default="out", type=str, help='folder containing representation space matrix')
parser.add_argument('--out-dir', dest='out_dir', default="out", type=str, help='output folder')
parser.add_argument('--prefix', dest='prefix', default="score", type=str, help='prefix of output file')
parser.add_argument('--alignment-file', dest='ali_file', default="ali.fasta", type=str, help='path to the fasta alignment file')
parser.add_argument('--tree', dest='tree', default="tree.pkl", type=str, help='path to pickle tree')
parser.add_argument('--nodes', dest='nodes',default="ROOT", type=str, help='name of the nodes to analyze, format should be I0,I1,I2')
parser.add_argument('--h5',dest='h5',default='',type=str,help='path of h5 file containing h5 scores replacing Mulan Attention scores')
parser.add_argument('--explained-variance', dest='exp_var', default="1", type=str, help='explained variance ratio to use in comparison [0:1]')
parser.add_argument('--th',dest='th',default='0',type=str,help='if > 0, filter position in anchors where cons_score > th')
parser.add_argument('--th-seq',dest='th_seq',default='0',type=str,help='if > 0, filter position in sequences where cons_score > th')
parser.add_argument('--force', dest='force', default="false", type=str, help='force execution')
parser.add_argument('--sys-setrecursionlimit', dest='setrecursionlimit', default="", type=str, help='recursion limit for unpickling')
parser.add_argument('--use-cuda', dest='use_cuda', default="True", type=str, help='True to use cuda')
parser.add_argument('--preload-device', dest='preload_device', default="cpu", type=str, help="'cpu' or 'cuda', device where all sequence embeddings will be preloaded")
parser.add_argument('--PLM',dest="PLM",default="ElnaggarLab/ankh-large",type=str,help="Needed for Mulan, assuming its the same one used for embedding. Available models :['facebook/esm2_t36_3B_UR50D', 'ElnaggarLab/ankh-large']")
parser.add_argument('--verbose',dest='verbose', default="True", type=str, help='if True, show progress bar')
args = parser.parse_args()
setrecursionlimit = args.setrecursionlimit
if setrecursionlimit != "":
sys.setrecursionlimit(int(setrecursionlimit))
exp_var = float(args.exp_var)
assert exp_var <= 1
assert exp_var > 0
use_cuda = (args.use_cuda.lower() == "true")
if use_cuda and not torch.cuda.is_available():
print("CUDA not available, using CPU")
device = torch.device('cuda' if torch.cuda.is_available() and use_cuda else 'cpu')
preload_device = torch.device(args.preload_device)
preload = True
verbose = (args.verbose.lower() == 'true')
h5_path = args.h5
attentions = None
if h5_path == '':
PLM = args.PLM
if PLM == 'ElnaggarLab/ankh-large':
cons_model_path += "ankh.ckpt"
cons_model = LightAttModel.from_pretrained(cons_model_path, device=device)
if PLM == 'facebook/esm2_t36_3B_UR50D':
cons_model_path += "esm.ckpt"
cons_model = LightAttModel.from_pretrained(cons_model_path, device=device)
if h5_path != '':
cons_model = None
with h5py.File(h5_path, "r") as f:
attentions = {k: v[()] for k, v in f.items()}
th = float(args.th)
th_seq = float(args.th_seq)
anchor_dir, sequence_dir, repr_space = args.anchor_dir, args.sequence_dir, args.repr_space
out_dir = args.out_dir
prefix = args.prefix
os.makedirs(out_dir, exist_ok=True)
nodes_name = args.nodes
for node_name in nodes_name.split(","):
dest_file = os.path.join(out_dir,prefix+"_"+node_name+".npy") if prefix else os.path.join(out_dir,node_name+".npy")
ali_file = args.ali_file
treefile = args.tree
score = get_score_per_pos(ali_file, treefile, node_name, repr_space, anchor_dir, sequence_dir, cons_model, h5_path, exp_var, attentions, th_seq, th, device, preload_device,verbose)
with open(dest_file, 'wb') as f:
np.save(f,score)
if __name__ == "__main__":
main()
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
import sys, os, argparse
import gc
import time
import h5py
import torch
import torch.nn.functional as F
torch.backends.cuda.matmul.allow_tf32 = True
from aligner.alignment_cython import compute_ali_mat
from aligner.alignment_cython import compute_alignment
import mulan
from mulan.modules import LightAttModel
import numpy as np
import pickle
from PLMV_common import dim_reduc, project, printProgressBar, parse_fasta
from PLMV_tree_SCUT import SpectralBiCoClustering
from PLMV_compare import squared_euc_dist, compute_similarity_matrix_plain_rbf, pairwise_cos_sim, get_anc_cons_score, load_anchor
def get_pos_dict(fasta_dict):
"""return a dictionary containing the list of positions of each residue in alignment"""
res_dict = {}
for k in fasta_dict:
ali_seq = fasta_dict[k]
res_dict[k] = [e for e,i in enumerate(ali_seq) if i not in [".","-"]]
return res_dict
def get_ali_path(embedding1,embedding2, cons_scores):
sm = cons_scores*compute_similarity_matrix_plain_rbf(embedding1, embedding2)
cs = cons_scores*pairwise_cos_sim(embedding1, embedding2)
val = sm + cs
val_cpu = val.cpu().numpy()
path = np.zeros_like(val_cpu,dtype=np.int32)
exit_code = compute_alignment(path,val_cpu,*val_cpu.shape)
return path
def get_weight_residues_seq_anc(anc,seq,cons_scores):
path = torch.tensor(get_ali_path(anc,seq,cons_scores)).to(anc.device)
denom = cons_scores.sum()
sm = (cons_scores*compute_similarity_matrix_plain_rbf(anc, seq))
cs = (cons_scores*pairwise_cos_sim(anc, seq))
sm = (path * sm).sum(0)/denom
cs = (path * cs).sum(0)/denom
return sm, cs
def get_score_per_pos(ali_file, treefile, node_name, repr_space, anchor_dir, sequence_dir, cons_model, h5_path,exp_var, attentions, th_seq, th,device,preload_device,verbose):
with open(treefile, 'rb') as handle:
tree = pickle.load(handle)
node = tree&node_name
ali_dict = parse_fasta(ali_file)
ali_len = len(next(iter(ali_dict.values())))
anc_list = sorted(os.listdir(anchor_dir))
seq_list = [i+".pt" for i in ali_dict.keys()]
R = torch.load(os.path.join(repr_space,"repr_space_mat.pt"),weights_only=True)
V = node.V
S = node.S
cd = node.cd
with torch.inference_mode():
if verbose: print("[Preloading]")
l_anc = []
l_mw = []
l_cons = []
cpt = 0
tot_iter = len(anc_list)
for anc_name in anc_list:
#load and preprocess anchor, conservation scores, and parameters for projection
anc, cons_scores = get_anc_cons_score(anchor_dir,anc_name,device,preload_device,cons_model,h5_path,th,attentions)
l_anc.append(anc)
l_cons.append(cons_scores)
cpt +=1
if verbose: printProgressBar(cpt,tot_iter)
del anc
if th_seq <= 0:
cons_model = None
del attentions
gc.collect()
torch.cuda.empty_cache()
with open(os.path.join(repr_space,"sequences_used.txt"),"r") as f:
lines = f.readlines()
l_seq = [line[:-1] for line in lines]
with torch.inference_mode():
score = np.zeros((len(seq_list),ali_len))
#score = np.zeros(ali_len)
if verbose: print("[Comparison]")
cpt = 0
tot_iter = len(anc_list) * len(seq_list)
for s,seq_name in enumerate(seq_list):
#get ali pos
seq_fasta = ali_dict[seq_name[:-3]]
pos = [e for e,aa in enumerate(seq_fasta) if aa not in ['-','.']]
seqnum = l_seq.index(seq_name)
#TODO for any seq (not necessarily one that is in the tree) ???
rep = R[seqnum]
rd = np.asarray(1.0 / np.sqrt(rep.sum(axis=-1))).squeeze() #more normalisation
rd = np.where(~np.isfinite(rd), 0, rd)
seq_full = torch.load(os.path.join(sequence_dir,seq_name),map_location=device,weights_only=True).float()
res1 = np.zeros(ali_len)
for k,anc_name in enumerate(anc_list):
#fetching the anchors
anc, cons_scores = load_anchor(k,l_anc,l_cons,preload_device, device)
seq = seq_full
s1,s2 = get_weight_residues_seq_anc(anc,seq,cons_scores)
s1,s2 = np.array(s1.cpu()),np.array(s2.cpu())
s1_n = rd * s1 * cd[2*k]
s2_n = rd * s2 * cd[2*k+1]
val_1 = V[2*k] * s1_n/S
val_2 = V[2*k+1] * s2_n/S
res1[pos] += val_1
res1[pos] += val_2
cpt+=1
if verbose: printProgressBar(cpt,tot_iter)
score[s] = res1
#score += res1
return score
def main():
script_dir = os.path.dirname(__file__)
cons_model_path = os.path.join(script_dir,"cons_models/Mulan/mulan_")
parser = argparse.ArgumentParser()
parser.add_argument('--anchors-dir', dest='anchor_dir', default='anchors', type=str, help='folder containing anchors embeddings')
parser.add_argument('--sequences-dir', dest='sequence_dir', default='sequences', type=str, help='folder containing sequences embeddings')
parser.add_argument('--repr-space', dest='repr_space', default="out", type=str, help='folder containing representation space matrix')
parser.add_argument('--out-dir', dest='out_dir', default="out", type=str, help='output folder')
parser.add_argument('--prefix', dest='prefix', default="score", type=str, help='prefix of output file')
parser.add_argument('--alignment-file', dest='ali_file', default="ali.fasta", type=str, help='path to the fasta alignment file')
parser.add_argument('--tree', dest='tree', default="tree.pkl", type=str, help='path to pickle tree')
parser.add_argument('--nodes', dest='nodes',default="ROOT", type=str, help='name of the nodes to analyze, format should be I0,I1,I2')
parser.add_argument('--h5',dest='h5',default='',type=str,help='path of h5 file containing h5 scores replacing Mulan Attention scores')
parser.add_argument('--explained-variance', dest='exp_var', default="1", type=str, help='explained variance ratio to use in comparison [0:1]')
parser.add_argument('--th',dest='th',default='0',type=str,help='if > 0, filter position in anchors where cons_score > th')
parser.add_argument('--th-seq',dest='th_seq',default='0',type=str,help='if > 0, filter position in sequences where cons_score > th')
parser.add_argument('--force', dest='force', default="false", type=str, help='force execution')
parser.add_argument('--sys-setrecursionlimit', dest='setrecursionlimit', default="", type=str, help='recursion limit for unpickling')
parser.add_argument('--use-cuda', dest='use_cuda', default="True", type=str, help='True to use cuda')
parser.add_argument('--preload-device', dest='preload_device', default="cpu", type=str, help="'cpu' or 'cuda', device where all sequence embeddings will be preloaded")
parser.add_argument('--PLM',dest="PLM",default="ElnaggarLab/ankh-large",type=str,help="Needed for Mulan, assuming its the same one used for embedding. Available models :['facebook/esm2_t36_3B_UR50D', 'ElnaggarLab/ankh-large']")
parser.add_argument('--verbose',dest='verbose', default="True", type=str, help='if True, show progress bar')
parser.add_argument("--refnode",dest="refnode",default="None",type=str,help="node to use as reference")
args = parser.parse_args()
setrecursionlimit = args.setrecursionlimit
if setrecursionlimit != "":
sys.setrecursionlimit(int(setrecursionlimit))
exp_var = float(args.exp_var)
assert exp_var <= 1
assert exp_var > 0
use_cuda = (args.use_cuda.lower() == "true")
if use_cuda and not torch.cuda.is_available():
print("CUDA not available, using CPU")
device = torch.device('cuda' if torch.cuda.is_available() and use_cuda else 'cpu')
preload_device = torch.device(args.preload_device)
preload = True
verbose = (args.verbose.lower() == 'true')
h5_path = args.h5
attentions = None
if h5_path == '':
PLM = args.PLM
if PLM == 'ElnaggarLab/ankh-large':
cons_model_path += "ankh.ckpt"
cons_model = LightAttModel.from_pretrained(cons_model_path, device=device)
if PLM == 'facebook/esm2_t36_3B_UR50D':
cons_model_path += "esm.ckpt"
cons_model = LightAttModel.from_pretrained(cons_model_path, device=device)
if h5_path != '':
cons_model = None
with h5py.File(h5_path, "r") as f:
attentions = {k: v[()] for k, v in f.items()}
th = float(args.th)
th_seq = float(args.th_seq)
anchor_dir, sequence_dir, repr_space = args.anchor_dir, args.sequence_dir, args.repr_space
out_dir = args.out_dir
prefix = args.prefix
os.makedirs(out_dir, exist_ok=True)
nodes_name = args.nodes
for node_name in nodes_name.split(","):
dest_file = os.path.join(out_dir,prefix+"_"+node_name+".npy") if prefix else os.path.join(out_dir,node_name+".npy")
ali_file = args.ali_file
treefile = args.tree
score = get_score_per_pos(ali_file, treefile, node_name, repr_space, anchor_dir, sequence_dir, cons_model, h5_path, exp_var, attentions, th_seq, th, device, preload_device,verbose)
with open(dest_file, 'wb') as f:
np.save(f,score)
if __name__ == "__main__":
main()
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
"""
This script can be used to infer a [L,2*A] representation for a given embedding. (with L = sequence length, A = number of anchors).
"""
import sys, os, argparse
import gc
import time
import h5py
import torch
import torch.nn.functional as F
torch.backends.cuda.matmul.allow_tf32 = True
from alignment_cython import compute_ali_mat
from alignment_cython import compute_alignment
import mulan
from mulan.modules import LightAttModel
import numpy as np
import pickle
from PLMV_common import dim_reduc, project, printProgressBar, parse_fasta
from PLMV_tree_SCUT import SpectralBiCoClustering
from PLMV_compare_cuda import squared_euc_dist, compute_similarity_matrix_plain_rbf, pairwise_cos_sim, get_anc_cons_score, load_anchor
def get_pos_dict(fasta_dict):
"""return a dictionary containing the list of positions of each residue in alignment"""
res_dict = {}
for k in fasta_dict:
ali_seq = fasta_dict[k]
res_dict[k] = [e for e,i in enumerate(ali_seq) if i not in [".","-"]]
return res_dict
def get_ali_path(embedding1,embedding2, cons_scores):
sm = cons_scores*compute_similarity_matrix_plain_rbf(embedding1, embedding2)
cs = cons_scores*pairwise_cos_sim(embedding1, embedding2)
val = sm + cs
val_cpu = val.cpu().numpy()
path = np.zeros_like(val_cpu,dtype=np.int32)
exit_code = compute_alignment(path,val_cpu,*val_cpu.shape)
return path
def get_weight_residues_seq_anc(anc,seq,cons_scores):
path = torch.tensor(get_ali_path(anc,seq,cons_scores)).to(anc.device)
denom = cons_scores.sum()
sm = (cons_scores*compute_similarity_matrix_plain_rbf(anc, seq))
cs = (cons_scores*pairwise_cos_sim(anc, seq))
sm = (path * sm).sum(0)/denom
cs = (path * cs).sum(0)/denom
return sm, cs
def get_score_per_pos(ali_file, repr_space, anchor_dir, sequence_dir, cons_model, h5_path,exp_var, attentions, th_seq, th,device,preload_device,verbose):
ali_dict = parse_fasta(ali_file)
ali_len = len(next(iter(ali_dict.values())))
anc_list = sorted(os.listdir(anchor_dir))
seq_list = [i+".pt" for i in ali_dict.keys()]
R = torch.load(os.path.join(repr_space,"repr_space_mat.pt"),weights_only=True)
with torch.inference_mode():
if verbose: print("[Preloading]")
l_anc = []
l_mw = []
l_cons = []
cpt = 0
tot_iter = len(anc_list)
for anc_name in anc_list:
#load and preprocess anchor, conservation scores, and parameters for projection
anc, cons_scores = get_anc_cons_score(anchor_dir,anc_name,device,preload_device,cons_model,h5_path,th,attentions)
l_anc.append(anc)
l_cons.append(cons_scores)
cpt +=1
if verbose: printProgressBar(cpt,tot_iter)
del anc
if th_seq <= 0:
cons_model = None
del attentions
gc.collect()
torch.cuda.empty_cache()
with open(os.path.join(repr_space,"sequences_used.txt"),"r") as f:
lines = f.readlines()
l_seq = [line[:-1] for line in lines]
with torch.inference_mode():
score = np.zeros((len(seq_list), 2*len(anc_list), ali_len))
#score = np.zeros(ali_len)
if verbose: print("[Comparison]")
cpt = 0
tot_iter = len(anc_list) * len(seq_list)
for s,seq_name in enumerate(seq_list):
#get ali pos
seq_fasta = ali_dict[seq_name[:-3]]
pos = [e for e,aa in enumerate(seq_fasta) if aa not in ['-','.']]
seqnum = l_seq.index(seq_name)
#TODO for any seq (not necessarily one that is in the tree) ???
rep = R[seqnum]
rd = np.asarray(1.0 / np.sqrt(rep.sum(axis=-1))).squeeze() #more normalisation
rd = np.where(~np.isfinite(rd), 0, rd)
seq_full = torch.load(os.path.join(sequence_dir,seq_name),map_location=device,weights_only=True).float()
len_seq = len(seq_full)
res1 = np.zeros((2*len(anc_list),ali_len))
for k,anc_name in enumerate(anc_list):
#fetching the anchors
anc, cons_scores = load_anchor(k,l_anc,l_cons,preload_device, device)
seq = seq_full
s1,s2 = get_weight_residues_seq_anc(anc,seq,cons_scores)
s1,s2 = np.array(s1.cpu()),np.array(s2.cpu())
#s1_n = rd * s1 * cd[2*k]
#s2_n = rd * s2 * cd[2*k+1]
#val_1 = V[2*k] * s1_n/S
#val_2 = V[2*k+1] * s2_n/S
res1[2*k][pos] = s1 * len_seq
res1[2*k+1][pos] = s2 * len_seq
cpt+=1
if verbose: printProgressBar(cpt,tot_iter)
score[s] = res1
#score += res1
return score
def main():
script_dir = os.path.dirname(__file__)
cons_model_path = os.path.join(script_dir,"cons_models/Mulan/mulan_")
parser = argparse.ArgumentParser()
parser.add_argument('--anchors-dir', dest='anchor_dir', default='anchors', type=str, help='folder containing anchors embeddings')
parser.add_argument('--sequences-dir', dest='sequence_dir', default='sequences', type=str, help='folder containing sequences embeddings')
parser.add_argument('--repr-space', dest='repr_space', default="out", type=str, help='folder containing representation space matrix')
parser.add_argument('--out-dir', dest='out_dir', default="out", type=str, help='output folder')
parser.add_argument('--prefix', dest='prefix', default="score", type=str, help='prefix of output file')
parser.add_argument('--alignment-file', dest='ali_file', default="ali.fasta", type=str, help='path to the fasta alignment file')
parser.add_argument('--h5',dest='h5',default='',type=str,help='path of h5 file containing h5 scores replacing Mulan Attention scores')
parser.add_argument('--explained-variance', dest='exp_var', default="1", type=str, help='explained variance ratio to use in comparison [0:1]')
parser.add_argument('--th',dest='th',default='0',type=str,help='if > 0, filter position in anchors where cons_score > th')
parser.add_argument('--th-seq',dest='th_seq',default='0',type=str,help='if > 0, filter position in sequences where cons_score > th')
parser.add_argument('--force', dest='force', default="false", type=str, help='force execution')
parser.add_argument('--sys-setrecursionlimit', dest='setrecursionlimit', default="", type=str, help='recursion limit for unpickling')
parser.add_argument('--use-cuda', dest='use_cuda', default="True", type=str, help='True to use cuda')
parser.add_argument('--preload-device', dest='preload_device', default="cpu", type=str, help="'cpu' or 'cuda', device where all sequence embeddings will be preloaded")
parser.add_argument('--PLM',dest="PLM",default="ElnaggarLab/ankh-large",type=str,help="Needed for Mulan, assuming its the same one used for embedding. Available models :['facebook/esm2_t36_3B_UR50D', 'ElnaggarLab/ankh-large']")
parser.add_argument('--verbose',dest='verbose', default="True", type=str, help='if True, show progress bar')
args = parser.parse_args()
setrecursionlimit = args.setrecursionlimit
if setrecursionlimit != "":
sys.setrecursionlimit(int(setrecursionlimit))
exp_var = float(args.exp_var)
assert exp_var <= 1
assert exp_var > 0
use_cuda = (args.use_cuda.lower() == "true")
if use_cuda and not torch.cuda.is_available():
print("CUDA not available, using CPU")
device = torch.device('cuda' if torch.cuda.is_available() and use_cuda else 'cpu')
preload_device = torch.device(args.preload_device)
preload = True
verbose = (args.verbose.lower() == 'true')
h5_path = args.h5
attentions = None
if h5_path == '':
PLM = args.PLM
if PLM == 'ElnaggarLab/ankh-large':
cons_model_path += "ankh.ckpt"
cons_model = LightAttModel.from_pretrained(cons_model_path, device=device)
if PLM == 'facebook/esm2_t36_3B_UR50D':
cons_model_path += "esm.ckpt"
cons_model = LightAttModel.from_pretrained(cons_model_path, device=device)
if h5_path != '':
cons_model = None
with h5py.File(h5_path, "r") as f:
attentions = {k: v[()] for k, v in f.items()}
th = float(args.th)
th_seq = float(args.th_seq)
anchor_dir, sequence_dir, repr_space = args.anchor_dir, args.sequence_dir, args.repr_space
out_dir = args.out_dir
prefix = args.prefix
os.makedirs(out_dir, exist_ok=True)
dest_file = os.path.join(out_dir,prefix+".npy")
ali_file = args.ali_file
score = get_score_per_pos(ali_file, repr_space, anchor_dir, sequence_dir, cons_model, h5_path, exp_var, attentions, th_seq, th, device, preload_device,verbose)
with open(dest_file, 'wb') as f:
np.save(f,score)
if __name__ == "__main__":
main()
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
"""
Given a Tree (.pkl) and a vector in the 2*A dimensional space (A = number of anchors) compute the closest leaf.
"""
import sys, os, argparse
import torch
import numpy as np
import pickle
from ete3 import Tree
from PLMV_common import dim_reduc, project, printProgressBar
#input: seq_dir, rep, tree
def infer_leaf_from_tree_TH(tree,rep):
"""
infer corresponding leaf in tree of the representation given as input
tree should be the output of ClusterDataToTree()
"""
curr_node = tree
while not curr_node.is_leaf():
left,right = curr_node.children
V = curr_node.V
th = curr_node.th
S = curr_node.S
cd = curr_node.cd
rd = np.asarray(1.0 / np.sqrt(rep.sum(axis=-1))).squeeze()
rd = np.where(~np.isfinite(rd), 0, rd)
rep_n = rd * rep * cd
val = (V * rep_n/S).sum()-th
if val < 0:
curr_node = left
else:
curr_node = right
return curr_node
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--repr-space', dest='repr_space', default='out', type=str, help='folder containing representation space matrix obtained by comparing new sequence to anchors')
parser.add_argument('--tree-path', dest='tree_path', default="", type=str, help='path to .pkl tree to use for classification')
parser.add_argument('--out-dir', dest='out_dir', default="out", type=str, help='output directory')
parser.add_argument('--prefix', dest='prefix', default="inferred", type=str, help='output prefix of generated tree')
parser.add_argument('--verbose',dest='verbose', default="False", type=str, help='if True, show progress bar')
parser.add_argument('--sys-setrecursionlimit', dest='setrecursionlimit', default="", type=str, help='recursion limit for unpickling')
args = parser.parse_args()
setrecursionlimit = args.setrecursionlimit
if setrecursionlimit != "":
sys.setrecursionlimit(int(setrecursionlimit))
in_dir, out_dir, prefix,verbose = args.repr_space, args.out_dir, args.prefix, args.verbose
tree_path = args.tree_path
assert tree_path.endswith(".pkl")
verbose = verbose.lower() == "true"
with open(tree_path, 'rb') as handle:
tree = pickle.load(handle)
#printProgressBar(cpt,tot_iter)
with open(os.path.join(in_dir,'sequences_used.txt'),"r") as f:
lines = f.readlines()
seq_ids = [line[:-4] for line in lines]
tot = len(seq_ids)
repr_space_mat = torch.load(os.path.join(in_dir,'repr_space_mat.pt'),weights_only=True)
os.makedirs(out_dir, exist_ok=True)
with open(os.path.join(out_dir,prefix+".txt"),"w") as f:
for i,s in enumerate(seq_ids):
rep = np.array(repr_space_mat[i])
leaf = infer_leaf_from_tree_TH(tree,rep)
pred = leaf.name
f.write(s.split(".")[0]+"\t"+pred+"\n")
if verbose:
printProgressBar(i+1,tot)
if __name__ == "__main__":
main()
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
"""
Unused helper file.
This could be useful if one has multiple GPUs/CPUs. For each device a PLMV_compare.py can be launched, for different batches of sequences (but same anchors). This file could merge the representation space into a single one.
"""
import sys, os, argparse
import torch
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--repr-space1', dest='repr_space1', default='out1', type=str, help='1st folder containing representation space matrix')
parser.add_argument('--repr-space2', dest='repr_space2', default='out2', type=str, help='2nd folder containing representation space matrix obtained by comparing new sequence to anchors')
parser.add_argument('--repr-space-merged', dest='repr_space_merged', default='out_merged', type=str, help='destination folder containing merged representation space')
args = parser.parse_args()
repr_space1, repr_space2, repr_space_merged = args.repr_space1,args.repr_space2,args.repr_space_merged
with open(os.path.join(repr_space1,'anchors_used.txt'),"r") as f:
lines_1 = f.readlines()
anc_ids_1 = {line[:-4] for line in lines_1}
with open(os.path.join(repr_space2,'anchors_used.txt'),"r") as f:
lines_2 = f.readlines()
anc_ids_2 = {line[:-4] for line in lines_2}
if anc_ids_1 != anc_ids_2:
print("Error: repr-space1 and repr-space2 needs to be built using the same anchors")
return -1
repr_space_mat = torch.cat([torch.load(os.path.join(repr_space1,'repr_space_mat.pt'),weights_only=True),torch.load(os.path.join(repr_space2,'repr_space_mat.pt'),weights_only=True)],dim=0)
torch.save(repr_space_mat,os.path.join(repr_space_merged,'repr_space_mat.pt'))
with open(os.path.join(repr_space_merged,'sequences_used.txt'),"w") as f:
with open(os.path.join(repr_space1,'sequences_used.txt'),"r") as f1:
lines1 = f1.readlines()
with open(os.path.join(repr_space2,'sequences_used.txt'),"r") as f2:
lines2 = f2.readlines()
for line in lines1:
f.write(line)
for line in lines2:
f.write(line)
return 0
if __name__ == "__main__":
main()
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
"""
Sample sequence across tree at given nodes.
"""
import os
import argparse
import numpy as np
from ete3 import Tree
from PLMV_common import parse_fasta
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--tree', dest='tree', default="tree.nhx", type=str, help='path to .nhx tree')
parser.add_argument('--nodes', dest='nodes',default="", type=str, help='names of the node to analyze format : "I0,I1,I2", can be left empty')
parser.add_argument('--k', dest='knodes',default="0", type=str, help='number of nodes to sample automatically, ignores --nodes if greaters than 0, default : 0')
parser.add_argument('--n-sample', dest='nsample',default="5", type=str, help='number of samples per child node, default : 5')
parser.add_argument('--sequences', dest='sequence_fn', default='', type=str, help='original input fasta file containing sequences to classify (given to PLMV_embed.py)')
parser.add_argument('--seq-of-interest', dest='seq_int',default="interest.fasta", type=str, help='fasta file containing sequences around which to start the explanations. Can also include out-of-tree sequences.')
parser.add_argument('--out-dir', dest='out_dir', default="out", type=str, help='output folder')
parser.add_argument('--prefix', dest='prefix', default="score", type=str, help='prefix of output file')
parser.add_argument('--seed',dest='seed',default="None",type=str,help="Random seed, for reproducibility")
args = parser.parse_args()
args_dict = vars(args)
out_dir = args_dict['out_dir'] #path
tree = args_dict['tree'] #path
nodes = args_dict['nodes'] #str
knodes = int(args_dict['knodes'])
nsample = int(args_dict['nsample'])
sequence_fn = args_dict['sequence_fn'] #path
seq_int = args_dict['seq_int'] #path
prefix = args_dict['prefix'] #str
seed = int(args_dict['seed'])
np.random.seed(seed)
os.makedirs(out_dir, exist_ok=True)
t = Tree(tree,format=1)
dico_interest = dict()
if seq_int:
dico_interest = parse_fasta(seq_int)
dico = parse_fasta(sequence_fn)
dico_interest_formated = {k.replace(":","_"):v for k,v in dico_interest.items()} #since ":" is replaced to "_" when writing the pkl trees.
set_leaves = [i for i in dico_interest_formated if i in t]
#select interesting nodes
candidates = nodes.split(",")
if knodes > 0:
lca = t.get_common_ancestor(*set_leaves)
#find all candidates
curr = lca.up
list_ancestors = []
while True:
left,right = curr.children
if len(left) < nsample or len(right) < nsample:
curr = curr.up
continue
list_ancestors.append((curr.support,curr.name))
if curr.name == 'ROOT':
break
curr = curr.up
candidates = [i for _,i in sorted(list_ancestors,reverse = True)[:knodes]] #Sort them by "support" ie how well split is defined
#sample sequences in interesting nodes
sample = []
sampled = set()
for candidate in candidates:
node = t&candidate
left,right = node.children
#/!\ DO NOT DO (i not in sample), DO a = set() [[a.add(i) for i in l] for l in sample], (i not in a)
leaves = [i for i in left.get_leaf_names() if (i not in sampled) and (i not in dico_interest_formated)]
curr_sample_left = list(np.random.choice(leaves, min(nsample,len(leaves)), replace=False))
leaves = [i for i in right.get_leaf_names() if (i not in sampled) and (i not in dico_interest_formated)]
curr_sample_right = list(np.random.choice(leaves, min(nsample,len(leaves)), replace=False))
sample.append(curr_sample_left+curr_sample_right)
[sampled.add(i) for i in curr_sample_left+curr_sample_right]
#write fasta
dest_file_fasta = os.path.join(out_dir,prefix+".fasta")
with open(dest_file_fasta,"w") as f:
for h in dico_interest:
f.write(">"+h+"\n"+dico_interest[h]+"\n")
for l in sample:
for h in l:
seq = dico[h]
f.write(">"+h+"\n"+seq+"\n")
dest_file_node = os.path.join(out_dir,prefix+"_nodes.txt")
with open(dest_file_node,"w") as f:
f.write(",".join(candidates))
if __name__ == "__main__":
main()
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
"""
Sample sequence across tree at given nodes.
"""
import os
import argparse
import numpy as np
from ete3 import Tree
from PLMV_common import parse_fasta
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--tree', dest='tree', default="tree.nhx", type=str, help='path to .nhx tree')
parser.add_argument('--nodes', dest='nodes',default="", type=str, help='names of the node to analyze format : "I0,I1,I2", can be left empty')
parser.add_argument('--k', dest='knodes',default="0", type=str, help='number of nodes to sample automatically, ignores --nodes if greaters than 0, default : 0')
parser.add_argument('--n-sample', dest='nsample',default="5", type=str, help='number of samples per child node, default : 5')
parser.add_argument('--sequences', dest='sequence_fn', default='', type=str, help='original input fasta file containing sequences to classify (given to PLMV_embed.py)')
parser.add_argument('--seq-of-interest', dest='seq_int',default="interest.fasta", type=str, help='fasta file containing sequences around which to start the explanations. Can also include out-of-tree sequences.')
parser.add_argument('--out-dir', dest='out_dir', default="out", type=str, help='output folder')
parser.add_argument('--prefix', dest='prefix', default="score", type=str, help='prefix of output file')
parser.add_argument('--seed',dest='seed',default="None",type=str,help="Random seed, for reproducibility")
parser.add_argument("--refnode",dest="refnode",default="None",type=str,help="node to use as reference")
args = parser.parse_args()
args_dict = vars(args)
out_dir = args_dict['out_dir'] #path
tree = args_dict['tree'] #path
nodes = args_dict['nodes'] #str
refnodename = args_dict['refnode'] #str
knodes = int(args_dict['knodes'])
nsample = int(args_dict['nsample'])
sequence_fn = args_dict['sequence_fn'] #path
seq_int = args_dict['seq_int'] #path
prefix = args_dict['prefix'] #str
seed = int(args_dict['seed'])
np.random.seed(seed)
os.makedirs(out_dir, exist_ok=True)
t = Tree(tree,format=1)
dico_interest = dict()
if seq_int:
dico_interest = parse_fasta(seq_int)
dico = parse_fasta(sequence_fn)
dico_interest_formated = {k.replace(":","_"):v for k,v in dico_interest.items()} #since ":" is replaced to "_" when writing the pkl trees.
set_leaves = [i for i in dico_interest_formated if i in t]
#select interesting nodes
candidates = nodes.split(",")
if knodes > 0:
lca = t.get_common_ancestor(*set_leaves)
#find all candidates
curr = lca.up
list_ancestors = []
while True:
left,right = curr.children
if len(left) < nsample or len(right) < nsample:
curr = curr.up
continue
list_ancestors.append((curr.support,curr.name))
if curr.name == 'ROOT':
break
curr = curr.up
candidates = [i for _,i in sorted(list_ancestors,reverse = True)[:knodes]] #Sort them by "support" ie how well split is defined
#sample sequences in interesting nodes
sample = []
sampled = set()
refnode = t&refnodename
leaves = [i for i in refnode.get_leaf_names() if (i not in sampled) and (i not in dico_interest_formated)]
curr_sample = list(np.random.choice(leaves, min(nsample,len(leaves)), replace=False))
sample.append(curr_sample)
[sampled.add(i) for i in curr_sample]
for candidate in candidates:
node = t&candidate
left,right = node.children
if refnode in left or refnode == left: #in is strict inclusion
curr = right
elif refnode in right or refnode == right:
curr = left
else:
assert False #shoul NOT run into this case
leaves = [i for i in curr.get_leaf_names() if (i not in sampled) and (i not in dico_interest_formated)]
curr_sample = list(np.random.choice(leaves, min(nsample,len(leaves)), replace=False))
sample.append(curr_sample)
[sampled.add(i) for i in curr_sample]
#write fasta
dest_file_fasta = os.path.join(out_dir,prefix+".fasta")
with open(dest_file_fasta,"w") as f:
for h in dico_interest:
f.write(">"+h+"\n"+dico_interest[h]+"\n")
for l in sample:
for h in l:
seq = dico[h]
f.write(">"+h+"\n"+seq+"\n")
dest_file_node = os.path.join(out_dir,prefix+"_nodes.txt")
with open(dest_file_node,"w") as f:
f.write(",".join(candidates))
if __name__ == "__main__":
main()
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
"""
Given representation space, compute the Ward dendrogram.
"""
import sys, os, argparse
import torch
import torch.nn.functional as F
import numpy as np
from scipy.cluster.hierarchy import linkage
from scipy.cluster.hierarchy import to_tree
from scipy.cluster.hierarchy import ClusterNode
from PLMV_common import dim_reduc, project
from typing import List
class Counter:
def __init__(self,init_val=-1):
self.count = init_val
def get_new_id(self):
self.count += 1
return self.count
def _scipy_tree_to_newick_list(node: ClusterNode, newick: List[str], parentdist: float, leaf_names: List[str],counter: Counter) -> List[str]:
"""Construct Newick tree from SciPy hierarchical clustering ClusterNode
This is a recursive function to help build a Newick output string from a scipy.cluster.hierarchy.to_tree input with
user specified leaf node names.
Notes:
This function is meant to be used with `to_newick`
Args:
node (scipy.cluster.hierarchy.ClusterNode): Root node is output of scipy.cluster.hierarchy.to_tree from hierarchical clustering linkage matrix
parentdist (float): Distance of parent node of `node`
newick (list of string): Newick string output accumulator list which needs to be reversed and concatenated (i.e. `''.join(newick)`) for final output
leaf_names (list of string): Leaf node names
Returns:
(list of string): Returns `newick` list of Newick output strings
"""
if node.is_leaf():
return newick + [f'{leaf_names[node.id]}:{parentdist - node.dist}']
if len(newick) > 0:
id = "I"+str(counter.get_new_id())
newick.append(")"+id+":"+f'{parentdist - node.dist}')
else:
id = "I"+str(counter.get_new_id())
newick.append(')'+id+';')
newick = _scipy_tree_to_newick_list(node.get_left(), newick, node.dist, leaf_names,counter)
newick.append(',')
newick = _scipy_tree_to_newick_list(node.get_right(), newick, node.dist, leaf_names,counter)
newick.append('(')
return newick
def to_newick(tree: ClusterNode, leaf_names: List[str]) -> str:
"""Newick tree output string from SciPy hierarchical clustering tree
Convert a SciPy ClusterNode tree to a Newick format string.
Use scipy.cluster.hierarchy.to_tree on a hierarchical clustering linkage matrix to create the root ClusterNode for the `tree` input of this function.
Args:
tree (scipy.cluster.hierarchy.ClusterNode): Output of scipy.cluster.hierarchy.to_tree from hierarchical clustering linkage matrix
leaf_names (list of string): Leaf node names
Returns:
(string): Newick output string
"""
counter = Counter()
newick_list = _scipy_tree_to_newick_list(tree, [], tree.dist, leaf_names,counter)
return ''.join(newick_list[::-1])
def build_tree(repr_space,labels,fname):
"""
Hierarchical clustering of the sequence in the representation space, reprensented as a Newick tree
"""
Z = linkage(repr_space,"ward")
T = to_tree(Z, rd = "False")[0]
#return T
print(to_newick(T,labels),file=open(fname,"w"))
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--repr-space', dest='repr_space', default='out', type=str, help='folder containing representation space matrix')
parser.add_argument('--out-dir', dest='out_dir', default="out", type=str, help='output directory')
parser.add_argument('--prefix', dest='prefix', default="tree", type=str, help='output prefix of generated tree')
parser.add_argument('--explained-variance', dest='exp_var', default="1", type=str, help='explained variance ratio used in tree building')
#parser.add_argument('--force', dest='force', default="false", type=str, help='force execution')
args = parser.parse_args()
exp_var = float(args.exp_var)
assert exp_var <= 1
assert exp_var >= 0
in_dir, out_dir, prefix = args.repr_space, args.out_dir, args.prefix
repr_space = torch.load(os.path.join(in_dir,'repr_space_mat.pt'),weights_only=True)
if exp_var < 1 :
mean,weights = dim_reduc(repr_space,explained_var=exp_var)
repr_space = project(repr_space,mean,weights)
list_sequences = []
with open(os.path.join(in_dir,'sequences_used.txt'),'r') as f_in:
for l in f_in.readlines():
list_sequences.append(l[:-1])
labels = [i[:-3] for i in list_sequences]
os.makedirs(out_dir, exist_ok=True)
build_tree(repr_space,labels,os.path.join(out_dir,prefix+".tree"))
return 0
if __name__ == "__main__":
main()
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
"""
Given Residue-level contribution, compute Explanation and Relevance plots.
"""
import sys, os, argparse
import numpy as np
import matplotlib.pyplot as plt
import pickle
from ete3 import Tree
from PLMV_common import parse_fasta
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--explain-dir', dest='explain_dir', default='explain', type=str, help='folder containing the .npy files created by PLMV_explain.py')
parser.add_argument('--out-dir', dest='output_dir', default='out_explain_viz', type=str, help='output folder')
parser.add_argument('--sampled-MSA', dest= "MSA", default="", type=str, help='')
parser.add_argument('--tree', dest='tree', default="tree.nhx", type=str, help='path to .nhx tree')
parser.add_argument('--annot-cols', dest='annot', default="", type=str, help='MSA columns to be annotated, format : "1,2,4"')
#parser.add_argument('--seq-of-interest', dest='seq_int',default="interest.fasta", type=str, help='fasta file containing sequences around which to start the explanations. Can also include out-of-tree sequences.')
args = parser.parse_args()
args_dict = vars(args)
explain_dir = args_dict['explain_dir']
out_dir = args_dict['output_dir']
#seq_int = args_dict['seq_int']
tree = args_dict['tree']
MSA = args_dict['MSA']
annot_cols = []
if args_dict['annot']:
annot_cols = [int(i) for i in args_dict['annot'].split(",")]
os.makedirs(out_dir, exist_ok=True)
tree = Tree(tree,format=1)
dico = parse_fasta(MSA)
key_idx = [(k.replace(":","_"),i) for i,k in zip(range(len(dico)),dico.keys())] #replace to use .nhx format
dico_key_idx = dict(key_idx)
dico_fds = dict()
for i in sorted(os.listdir(explain_dir)):
path_mat = os.path.join(explain_dir,i)
explain_mat = np.load(path_mat)
name = i.split(".")[0]
dest_file = os.path.join(out_dir,name+".png")
if "_" in name : name = name.split("_")[-1]
node = tree&name
left,right = node.children
left_idx = [dico_key_idx[key] for key in left.get_leaf_names() if key in dico_key_idx]
right_idx = [dico_key_idx[key] for key in right.get_leaf_names() if key in dico_key_idx]
explain_mat_left = explain_mat[left_idx].mean(0)
explain_mat_right = explain_mat[right_idx].mean(0)
scale = np.abs((explain_mat_left-explain_mat_right)).max()
scaled_left = explain_mat_left/scale
scaled_right = explain_mat_right/scale
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 8))
for k in annot_cols:
ax1.vlines(k, -1, 1, colors='#008000', linestyles='--')
for ax in [ax2]:
for k in annot_cols:
ax.vlines(k, 0, 1, colors='#008000', linestyles='--')
ax1.plot(scaled_left, label="left : " + left.name)
ax1.plot(scaled_right, label="right : " + right.name, c="tab:red")
ax1.set_title("Explanations " + i[:-4])
ax1.set_ylabel("Importance Score")
ax1.legend()
ax2.plot(scaled_right - scaled_left, label="fd_score : " + node.name,c="tab:orange")
dico_fds[name] = scaled_right - scaled_left
ax2.set_title("Relevancy " + i[:-4])
ax2.set_ylabel("Functional Score")
ax2.set_xlabel("Residue Position")
ax2.legend()
plt.tight_layout()
plt.savefig(dest_file)
dest_file = os.path.join(out_dir,"functional_determinant_scores.pkl")
with open(dest_file, 'wb') as outp:
pickle.dump(dico_fds, outp, pickle.HIGHEST_PROTOCOL)
if __name__ == "__main__":
main()
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
"""
Given Residue-level contribution, compute Explanation and Relevance plots.
"""
import sys, os, argparse
import numpy as np
import matplotlib.pyplot as plt
import pickle
from ete3 import Tree
from PLMV_common import parse_fasta
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--explain-dir', dest='explain_dir', default='explain', type=str, help='folder containing the .npy files created by PLMV_explain.py')
parser.add_argument('--out-dir', dest='output_dir', default='out_explain_viz', type=str, help='output folder')
parser.add_argument('--sampled-MSA', dest= "MSA", default="", type=str, help='')
parser.add_argument('--tree', dest='tree', default="tree.nhx", type=str, help='path to .nhx tree')
parser.add_argument('--annot-cols', dest='annot', default="", type=str, help='MSA columns to be annotated, format : "1,2,4"')
parser.add_argument("--refnode",dest="refnode",default="None",type=str,help="node to use as reference")
#parser.add_argument('--seq-of-interest', dest='seq_int',default="interest.fasta", type=str, help='fasta file containing sequences around which to start the explanations. Can also include out-of-tree sequences.')
args = parser.parse_args()
args_dict = vars(args)
explain_dir = args_dict['explain_dir']
out_dir = args_dict['output_dir']
#seq_int = args_dict['seq_int']
tree = args_dict['tree']
MSA = args_dict['MSA']
refnodename = args_dict['refnode']
annot_cols = []
if args_dict['annot']:
annot_cols = [int(i) for i in args_dict['annot'].split(",")]
os.makedirs(out_dir, exist_ok=True)
tree = Tree(tree,format=1)
dico = parse_fasta(MSA)
key_idx = [(k.replace(":","_"),i) for i,k in zip(range(len(dico)),dico.keys())] #replace to use .nhx format
dico_key_idx = dict(key_idx)
dico_fds = dict()
refnode = tree&refnodename
for i in sorted(os.listdir(explain_dir)):
path_mat = os.path.join(explain_dir,i)
explain_mat = np.load(path_mat)
name = i.split(".")[0]
dest_file = os.path.join(out_dir,name+".png")
if "_" in name : name = name.split("_")[-1]
node = tree&name
left,right = node.children
if refnode in left or refnode == left:
left = refnode
elif refnode in right or refnode == right:
right = refnode
else:
#There is an error somewhere
assert False
left_idx = [dico_key_idx[key] for key in left.get_leaf_names() if key in dico_key_idx]
right_idx = [dico_key_idx[key] for key in right.get_leaf_names() if key in dico_key_idx]
explain_mat_left = explain_mat[left_idx].mean(0)
explain_mat_right = explain_mat[right_idx].mean(0)
scale = np.abs((explain_mat_left-explain_mat_right)).max()
scaled_left = explain_mat_left/scale
scaled_right = explain_mat_right/scale
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(10, 8))
for k in annot_cols:
ax1.vlines(k, -1, 1, colors='#008000', linestyles='--')
for ax in [ax2]:
for k in annot_cols:
ax.vlines(k, 0, 1, colors='#008000', linestyles='--')
ax1.plot(scaled_left, label="left : " + left.name)
ax1.plot(scaled_right, label="right : " + right.name, c="tab:red")
ax1.set_title("Explanations " + i[:-4])
ax1.set_ylabel("Importance Score")
ax1.legend()
ax2.plot(scaled_right - scaled_left, label="fd_score : " + node.name,c="tab:orange")
dico_fds[name] = scaled_right - scaled_left
ax2.set_title("Relevancy " + i[:-4])
ax2.set_ylabel("Functional Score")
ax2.set_xlabel("Residue Position")
ax2.legend()
plt.tight_layout()
plt.savefig(dest_file)
dest_file = os.path.join(out_dir,"functional_determinant_scores.pkl")
with open(dest_file, 'wb') as outp:
pickle.dump(dico_fds, outp, pickle.HIGHEST_PROTOCOL)
if __name__ == "__main__":
main()
from . import alignment_cython
from . import alignment_cuda
\ No newline at end of file
# Copyright (c) 2026, Vinh-Son Pho
# This file is part of PLMView.
# Licensed under CC BY-NC-SA 4.0:
# https://creativecommons.org/licenses/by-nc-sa/4.0/
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef int compute_ali_mat(float[:, ::1] values, float[:, ::1] mat, int m, int n) nogil:
"""
Compute the alignment score of values, also compute the sum of the element of mat following said alignment
"""
cdef int i
cdef int j
cdef float max_val
cdef int direction
for i in range(1, m):
for j in range(1, n):
diag = values[i-1, j-1] + values[i, j]
left = values[i, j-1]
up = values[i-1, j]
max_val = diag
direction = 0
if left > max_val:
max_val = left
direction = 1
if up > max_val:
max_val = up
direction = 2
values[i, j] = max_val
if direction == 0:
mat[i, j] = mat[i-1, j-1] + mat[i, j]
elif direction == 1:
mat[i, j] = mat[i, j-1]
else:
mat[i, j] = mat[i-1, j]
return 0
@cython.boundscheck(False)
@cython.wraparound(False)
cdef int compute_ali_mat_exp(float[:, ::1] values, int m, int n) nogil:
cdef int i
cdef int j
for i in range(1, m):
for j in range(1, n):
values[i, j] = max(values[i-1, j-1] + values[i, j], values[i, j-1], values[i-1, j])
return 0
@cython.boundscheck(False)
@cython.wraparound(False)
cdef int compute_ali_path_exp(int[:, ::1] path, float[:, ::1] values, int m, int n) nogil:
cdef int i = m - 1
cdef int j = n - 1
while i != 0 and j != 0:
if abs(values[i,j] - values[i, j-1]) < 1e-8:
j -= 1
elif abs(values[i,j] - values[i-1, j]) < 1e-8:
i -= 1
else:
path[i, j] = 1
i -= 1
j -= 1
path[i, j] = 1
return 0
@cython.boundscheck(False)
@cython.wraparound(False)
cpdef int compute_alignment(int[:, ::1] path, float[:, ::1] values, int m, int n) nogil:
compute_ali_mat_exp(values, m, n)
compute_ali_path_exp(path, values, m, n)
return 0
// Copyright (c) 2026, Vinh-Son Pho
// This file is part of PLMView.
// Licensed under CC BY-NC-SA 4.0:
// https://creativecommons.org/licenses/by-nc-sa/4.0/
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <cuda_bf16.h>
#include <vector>
#include <algorithm>
#include <iostream>
// ===========================================================
// MathOps: Type traits for add and compare
// ===========================================================
template <typename T>
struct MathOps {
__device__ __forceinline__ static T add(T a, T b) { return a + b; }
__device__ __forceinline__ static bool greater(T a, T b) { return a > b; }
};
template <>
struct MathOps<__half> {
__device__ __forceinline__ static __half add(__half a, __half b) { return __hadd(a, b); }
__device__ __forceinline__ static bool greater(__half a, __half b) { return __hgt(a, b); }
};
template <>
struct MathOps<nv_bfloat16> {
__device__ __forceinline__ static nv_bfloat16 add(nv_bfloat16 a, nv_bfloat16 b) { return __hadd(a, b); }
__device__ __forceinline__ static bool greater(nv_bfloat16 a, nv_bfloat16 b) { return __hgt(a, b); }
};
// ===========================================================
// Templated Kernel
// ===========================================================
template <typename T>
__global__ void fused_ali_mat_kernel(
T* values, T* mat,
int B, int M, int N
) {
using Ops = MathOps<T>;
int b = blockIdx.x; // batch/block index
int tid = threadIdx.x; // thread index within block
if (b >= B) return;
int offset = b * M * N;
// Total number of antidiagonals (including borders)
int max_d = M + N - 2;
// Start from d=2 because row 0 and col 0 are assumed initialized
for (int d = 2; d <= max_d; ++d) {
// Compute valid range of i for this diagonal
int i_start = max(1, d - (N - 1));
int i_end = min(M - 1, d - 1);
int num_threads = i_end - i_start + 1;
// Process the diagonal in chunks of blockDim.x
for (int chunk_start = 0; chunk_start < num_threads; chunk_start += blockDim.x) {
int t = chunk_start + tid;
if (t < num_threads) {
int i = t + i_start;
int j = d - i;
if (j > 0 && j < N && i < M) {
int idx = offset + i * N + j;
int idx_diag = offset + (i - 1) * N + (j - 1);
int idx_left = offset + i * N + (j - 1);
int idx_up = offset + (i - 1) * N + j;
T diag = Ops::add(values[idx_diag], values[idx]);
T left = values[idx_left];
T up = values[idx_up];
T max_val = diag;
int direction = 0;
if (Ops::greater(left, max_val)) { max_val = left; direction = 1; }
if (Ops::greater(up, max_val)) { max_val = up; direction = 2; }
values[idx] = max_val;
if (direction == 0) {
mat[idx] = Ops::add(mat[idx_diag], mat[idx]);
} else if (direction == 1) {
mat[idx] = mat[idx_left];
} else {
mat[idx] = mat[idx_up];
}
}
}
}
// Synchronize before moving to next diagonal
__syncthreads();
}
}
// ===========================================================
// Thread selection helper
// ===========================================================
static const std::vector<int> g_device_max_threads = []() {
int device_count;
cudaGetDeviceCount(&device_count);
std::vector<int> cache(device_count);
for (int i = 0; i < device_count; i++) {
cudaDeviceProp prop;
cudaGetDeviceProperties(&prop, i);
cache[i] = prop.maxThreadsPerBlock;
}
return cache;
}();
static inline int choose_threads_per_block(const torch::Tensor& values) {
int device_id = values.device().index();
int max_threads = g_device_max_threads[device_id]; // just array lookup
int M = values.size(1);
int N = values.size(2);
int diag_len = std::min(M - 1, N - 1);
int threads = ((diag_len + 31) / 32) * 32;
return std::min(threads, max_threads);
}
// ===========================================================
// CUDA error check
// ===========================================================
static inline void check_cuda(const char* where) {
cudaError_t err = cudaGetLastError();
TORCH_CHECK(err == cudaSuccess, where, " (launch): ", cudaGetErrorString(err));
err = cudaDeviceSynchronize();
TORCH_CHECK(err == cudaSuccess, where, " (exec): ", cudaGetErrorString(err));
}
// ===========================================================
// Templated Launcher
// ===========================================================
template <typename T>
void compute_ali_mat_diagonal_t(torch::Tensor values, torch::Tensor mat, bool debug) {
int B = values.size(0);
T* values_ptr = reinterpret_cast<T*>(values.data_ptr());
T* mat_ptr = reinterpret_cast<T*>(mat.data_ptr());
int threads_per_block = choose_threads_per_block(values);
dim3 block(threads_per_block);
dim3 grid(B);
fused_ali_mat_kernel<T><<<grid, block>>>(values_ptr, mat_ptr,
B, values.size(1), values.size(2));
if (debug) {
check_cuda("fused_ali_mat_kernel");
}
}
// ===========================================================
// Public API
// ===========================================================
void compute_ali_mat_diagonal(torch::Tensor values, torch::Tensor mat, bool debug) {
TORCH_CHECK(values.device().is_cuda(), "values must be CUDA tensor");
TORCH_CHECK(mat.device().is_cuda(), "mat must be CUDA tensor");
TORCH_CHECK(values.scalar_type() == mat.scalar_type(),
"values and mat must have the same dtype");
TORCH_CHECK(values.dim() == 3 && mat.dim() == 3,
"values and mat must have shape [B, M, N]");
switch (values.scalar_type()) {
case at::kFloat:
compute_ali_mat_diagonal_t<float>(values, mat, debug);
break;
case at::kHalf:
compute_ali_mat_diagonal_t<__half>(values, mat, debug);
break;
case at::kBFloat16:
compute_ali_mat_diagonal_t<nv_bfloat16>(values, mat, debug);
break;
default:
TORCH_CHECK(false, "Unsupported dtype (float32, float16, bfloat16 only)");
}
}
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
// Single entry point from CUDA file
void compute_ali_mat_diagonal(torch::Tensor values, torch::Tensor mat, bool debug);
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
m.def(
"compute_ali_mat",
&compute_ali_mat_diagonal,
"Compute ali-mat diagonal (CUDA, supports float32/float16/bfloat16)",
py::arg("values"),
py::arg("mat"),
py::arg("debug") = false
);
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment