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
Attribution-NonCommercial-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International Public License
("Public License"). To the extent this Public License may be
interpreted as a contract, You are granted the Licensed Rights in
consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the
Licensor receives from making the Licensed Material available under
these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
l. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
# 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/
"""
Given MSA + Residue-level contribution, compute Logo figure.
"""
import os
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from scipy.stats import entropy
import pickle
from math import gcd
import re
from Bio import AlignIO, SeqIO
from Bio.Align import MultipleSeqAlignment
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
import logomaker
from ete3 import Tree
from pypdf import PdfWriter
from PLMV_common import parse_fasta
# Standard 20 amino acids (uppercase) + lowercase + gap
standard_chars = 'ACDEFGHIKLMNPQRSTVWYacdefghiklmnpqrstvwy-'
def replace_nonstandard_with_gap_regex(alignment):
"""
Replace non-standard amino acids with '-' using regex.
Preserves alignment structure and sequence metadata.
"""
new_records = []
for record in alignment:
seq_str = str(record.seq)
# Replace anything NOT in standard set with '-'
# ^ inside [] means "not", so [^standard_chars] matches non-standard
modified_seq = re.sub(f'[^{standard_chars}]', '-', seq_str)
new_record = SeqRecord(
Seq(modified_seq),
id=record.id,
name=record.name,
description=record.description,
annotations=record.annotations.copy(),
dbxrefs=record.dbxrefs[:], # Shallow copy of dbxrefs
letter_annotations=record.letter_annotations.copy()
)
new_records.append(new_record)
return MultipleSeqAlignment(new_records)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--viz-dir', dest='viz_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('--out-dir',dest="out_dir")
args = parser.parse_args()
args_dict = vars(args)
viz_dir = args_dict['viz_dir']
out_dir = args_dict['out_dir']
os.makedirs(out_dir, exist_ok=True)
os.makedirs(os.path.join(out_dir, "merged_logos"), exist_ok=True)
tree = args_dict['tree']
MSA = args_dict['MSA']
t = Tree(tree,format=1)
alignment = alignment = replace_nonstandard_with_gap_regex(AlignIO.read(MSA, "fasta"))
for i in os.listdir(viz_dir):
if i.endswith(".pkl"):
with open(os.path.join(viz_dir,i),"rb") as f:
scores = pickle.load(f)
ali_mapping =dict()
for e,i in enumerate(alignment):
ali_mapping[(i.name).replace(":","_")]=e
for k,v in scores.items():
#print(k)
node = t&k
ali_node = alignment[0:0]
cpt = 0
id_node = dict()
for l in node.get_leaf_names():
if l in ali_mapping:
e = ali_mapping[l]
ali_node.append(alignment[e])
id_node[l] = cpt
cpt += 1
#Below code can be used to prune fully gapped columns but it might be harder to then interpret the scores + ali
#node_func_score = []
#pruned_ali_node = ali_node[::,0:0]
#for i in range(len(ali_node[0])):
# col = ali_node[::,i]
# if col != "-"*len(ali_node):
# pruned_ali_node += ali_node[::,i:i+1]
# node_func_score.append(scores[k][i])
#node_func_score = np.array(node_func_score)
node_func_score = scores[k]
pruned_ali_node = ali_node
left, right = node.children
ali_left = alignment[0:0]
ali_right = alignment[0:0]
for l in left.get_leaf_names():
if l in id_node:
id = id_node[l]
ali_left.append(pruned_ali_node[id])
for l in right.get_leaf_names():
if l in id_node:
id = id_node[l]
ali_right.append(pruned_ali_node[id])
#print(len(pruned_ali_node),pruned_ali_node.get_alignment_length())
#print(len(ali_left),ali_left.get_alignment_length())
#print(len(ali_right),ali_right.get_alignment_length())
AlignIO.write(ali_left, os.path.join(out_dir, k+"_left"+".fasta"), "fasta")
AlignIO.write(ali_right, os.path.join(out_dir, k+"_right"+".fasta"), "fasta")
for i in os.listdir(out_dir):
if not i.endswith(".fasta"): continue
path = os.path.join(out_dir, i)
# Read sequences from FASTA
seqs = list(SeqIO.parse(path, "fasta"))
seq_strings = [str(seq.seq) for seq in seqs]
# Compute count matrix
count_mat = logomaker.alignment_to_matrix(seq_strings, to_type="counts")
score = scores[i.split("_")[-2]]#np.maximum(0.0, scores[i.split("_")[-2]])
prob_mat = count_mat.div(count_mat.sum(axis=1), axis=0).fillna(0) # Position-wise probabilities
weight_mat = prob_mat.multiply(score[:, None], axis=0)
parent_name, side = i.split("_")
parent_node = t & parent_name
left, right = parent_node.children
if side.startswith("left"):
node_name = left.name
else:
node_name = right.name
fig_x = len(seqs[0])
fig_y = 6
while (fig_x > 2**16) or (fig_y > 2**16):
fig_x /= 2
fig_y /= 2
logo = logomaker.Logo(weight_mat, color_scheme='chemistry', figsize=(fig_x, fig_y))
# Customize (mimic WebLogo options)
logo.ax.set_title(i[:-6] + " | " + node_name + " : Functional Score",
fontsize=80, pad=20)
logo.ax.set_ylabel("") # No y-label (like yaxis_label="")
logo.ax.set_ylim(score.min(), 1.0) # Scale y to max score
logo.ax.margins(x=0, y=0)
logo.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
logo.style_xticks(spacing=5, rotation=0)
logo.ax.tick_params(axis='both', which='major', labelsize=40)
logo.ax.tick_params(axis='x', which='major', pad=10, labelsize=40)
#logo.ax.xaxis.labelpad = 5
out_prefix = i.split(".")[-2]
out_path = os.path.join(out_dir, out_prefix + ".pdf")
#logo.ax.figure.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
logo.fig.savefig(out_path, bbox_inches='tight', pad_inches=0.2, format='pdf')
plt.close(logo.fig)
alphabet = weight_mat.columns
aa_to_idx = {aa: i for i, aa in enumerate(alphabet)}
def alignment_to_count_matrix(alignment):
"""
alignment: list of str, all same length L
Returns: np.array (L, 20) with counts in alphabet order
"""
L = len(alignment[0])
ali_size = len(alignment)
counts = np.zeros((L, len(alphabet)))
for seq in alignment:
for i, aa in enumerate(seq):
if aa in aa_to_idx: # Ignore gaps/other chars
idx = aa_to_idx[aa]
counts[i, idx] += 1
return counts, ali_size
for i in os.listdir(out_dir):
if not i.endswith("_left.fasta"): continue
base = i.split("_")[-2]
dico_left = parse_fasta(os.path.join(out_dir,base+"_left.fasta"))
dico_right = parse_fasta(os.path.join(out_dir,base+"_right.fasta"))
counts_1, ali_size_1 = alignment_to_count_matrix(list(dico_left.values()))
counts_2, ali_size_2 = alignment_to_count_matrix(list(dico_right.values()))
g = gcd(ali_size_1, ali_size_2)
balanced_counts = (counts_1 * (ali_size_2 // g) + counts_2 * (ali_size_1 // g))
non_gaps = balanced_counts.sum(axis=1)
num_seq = 2*(ali_size_2 * ali_size_1) / g
widths = non_gaps/num_seq
with np.errstate(divide='ignore', invalid='ignore'):
effective_n = balanced_counts.sum(axis=1)
raw_freqs = balanced_counts / effective_n[:, None]
raw_freqs = np.where(np.isfinite(raw_freqs), raw_freqs, 0.0)
observed_entropy = entropy(raw_freqs, axis=1, base=2)
observed_entropy = entropy(raw_freqs, axis=1, base=2)
info_content = np.log2(20) - observed_entropy # shape = (positions,)
info_content = np.where(np.isfinite(info_content), info_content, 0.0)
scaled_freqs = raw_freqs * info_content[:, None]
pwm = pd.DataFrame(scaled_freqs,
index=[i for i in range(scaled_freqs.shape[0])], # '0', '1', '2'...
columns=['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y'])
fig_x = len(seqs[0])
fig_y = 6
while (fig_x > 2**16) or (fig_y > 2**16):
fig_x /= 2
fig_y /= 2
logo = logomaker.Logo(pwm, color_scheme='chemistry', figsize=(fig_x, fig_y))
for pos in range(len(widths)):
for char in ['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y']:
logo.style_single_glyph(pos, char, width=widths[pos]*0.95) #base width
# Customize (mimic WebLogo options)
logo.ax.set_title(base+" Entropy (bits)",
fontsize=80, pad=20)
logo.ax.set_ylabel("") # No y-label (like yaxis_label="")
logo.ax.set_ylim(0, np.log2(20)) # Scale y to max score
logo.ax.margins(x=0, y=0)
logo.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
logo.style_xticks(spacing=5, rotation=0)
logo.ax.tick_params(axis='both', which='major', labelsize=40)
logo.ax.tick_params(axis='x', which='major', pad=10, labelsize=40)
#logo.ax.xaxis.labelpad = 5
out_prefix = base
out_path = os.path.join(out_dir, out_prefix + ".pdf")
#logo.ax.figure.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
logo.fig.savefig(out_path, bbox_inches='tight', pad_inches=0.2, format='pdf')
plt.close(logo.fig)
out_path = os.path.join(out_dir, out_prefix + ".pdf")
ordered_pdfs = [os.path.join(out_dir,base+".pdf"), os.path.join(out_dir,base+"_left.pdf"), os.path.join(out_dir,base+"_right.pdf")]
merger = PdfWriter()
for pdf in ordered_pdfs:
merger.append(pdf)
with open(os.path.join(out_dir,"merged_logos", base + ".pdf"), "wb") as output_file:
merger.write(output_file)
merger.close()
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 MSA + Residue-level contribution, compute Logo figure. Width scale with column occupanncy.
"""
import os
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from scipy.stats import entropy
import pickle
from math import gcd
import re
from Bio import AlignIO, SeqIO
from Bio.Align import MultipleSeqAlignment
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
import logomaker
from ete3 import Tree
from pypdf import PdfWriter
from PLMV_common import parse_fasta
# Standard 20 amino acids (uppercase) + lowercase + gap
standard_chars = 'ACDEFGHIKLMNPQRSTVWYacdefghiklmnpqrstvwy-'
def replace_nonstandard_with_gap_regex(alignment):
"""
Replace non-standard amino acids with '-' using regex.
Preserves alignment structure and sequence metadata.
"""
new_records = []
for record in alignment:
seq_str = str(record.seq)
# Replace anything NOT in standard set with '-'
# ^ inside [] means "not", so [^standard_chars] matches non-standard
modified_seq = re.sub(f'[^{standard_chars}]', '-', seq_str)
new_record = SeqRecord(
Seq(modified_seq),
id=record.id,
name=record.name,
description=record.description,
annotations=record.annotations.copy(),
dbxrefs=record.dbxrefs[:], # Shallow copy of dbxrefs
letter_annotations=record.letter_annotations.copy()
)
new_records.append(new_record)
return MultipleSeqAlignment(new_records)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--viz-dir', dest='viz_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('--out-dir',dest="out_dir")
args = parser.parse_args()
args_dict = vars(args)
viz_dir = args_dict['viz_dir']
out_dir = args_dict['out_dir']
os.makedirs(out_dir, exist_ok=True)
os.makedirs(os.path.join(out_dir, "merged_logos"), exist_ok=True)
tree = args_dict['tree']
MSA = args_dict['MSA']
t = Tree(tree,format=1)
alignment = alignment = replace_nonstandard_with_gap_regex(AlignIO.read(MSA, "fasta"))
for i in os.listdir(viz_dir):
if i.endswith(".pkl"):
with open(os.path.join(viz_dir,i),"rb") as f:
scores = pickle.load(f)
ali_mapping =dict()
for e,i in enumerate(alignment):
ali_mapping[(i.name).replace(":","_")]=e
for k,v in scores.items():
#print(k)
node = t&k
ali_node = alignment[0:0]
cpt = 0
id_node = dict()
for l in node.get_leaf_names():
if l in ali_mapping:
e = ali_mapping[l]
ali_node.append(alignment[e])
id_node[l] = cpt
cpt += 1
#Below code can be used to prune fully gapped columns but it might be harder to then interpret the scores + ali
#node_func_score = []
#pruned_ali_node = ali_node[::,0:0]
#for i in range(len(ali_node[0])):
# col = ali_node[::,i]
# if col != "-"*len(ali_node):
# pruned_ali_node += ali_node[::,i:i+1]
# node_func_score.append(scores[k][i])
#node_func_score = np.array(node_func_score)
node_func_score = scores[k]
pruned_ali_node = ali_node
left, right = node.children
ali_left = alignment[0:0]
ali_right = alignment[0:0]
for l in left.get_leaf_names():
if l in id_node:
id = id_node[l]
ali_left.append(pruned_ali_node[id])
for l in right.get_leaf_names():
if l in id_node:
id = id_node[l]
ali_right.append(pruned_ali_node[id])
#print(len(pruned_ali_node),pruned_ali_node.get_alignment_length())
#print(len(ali_left),ali_left.get_alignment_length())
#print(len(ali_right),ali_right.get_alignment_length())
AlignIO.write(ali_left, os.path.join(out_dir, k+"_left"+".fasta"), "fasta")
AlignIO.write(ali_right, os.path.join(out_dir, k+"_right"+".fasta"), "fasta")
for i in os.listdir(out_dir):
if not i.endswith(".fasta"): continue
path = os.path.join(out_dir, i)
# Read sequences from FASTA
seqs = list(SeqIO.parse(path, "fasta"))
seq_strings = [str(seq.seq) for seq in seqs]
# Compute count matrix
count_mat = logomaker.alignment_to_matrix(seq_strings, to_type="counts")
score = scores[i.split("_")[-2]]#np.maximum(0.0, scores[i.split("_")[-2]])
prob_mat = count_mat.div(count_mat.sum(axis=1), axis=0).fillna(0) # Position-wise probabilities
weight_mat = prob_mat.multiply(score[:, None], axis=0)
parent_name, side = i.split("_")
parent_node = t & parent_name
left, right = parent_node.children
if side.startswith("left"):
node_name = left.name
else:
node_name = right.name
fig_x = len(seqs[0])
fig_y = 6
while (fig_x > 2**16) or (fig_y > 2**16):
fig_x /= 2
fig_y /= 2
logo = logomaker.Logo(weight_mat, color_scheme='chemistry', figsize=(fig_x, fig_y))
alphabet = weight_mat.columns
aa_to_idx = {aa: i for i, aa in enumerate(alphabet)}
def alignment_to_count_matrix(alignment):
"""
alignment: list of str, all same length L
Returns: np.array (L, 20) with counts in alphabet order
"""
L = len(alignment[0])
ali_size = len(alignment)
counts = np.zeros((L, len(alphabet)))
for seq in alignment:
for i, aa in enumerate(seq):
if aa in aa_to_idx: # Ignore gaps/other chars
idx = aa_to_idx[aa]
counts[i, idx] += 1
return counts, ali_size
dico_left = parse_fasta(path)
counts_1, ali_size_1 = alignment_to_count_matrix(list(dico_left.values()))
non_gaps = counts_1.sum(axis=1)
num_seq = ali_size_1
widths = non_gaps/num_seq
for pos in range(len(widths)):
for char in ['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y']:
logo.style_single_glyph(pos, char, width=widths[pos]*0.95) #base width
# Customize (mimic WebLogo options)
logo.ax.set_title(i[:-6] + " | " + node_name + " : Functional Score",
fontsize=80, pad=20)
logo.ax.set_ylabel("") # No y-label (like yaxis_label="")
logo.ax.set_ylim(score.min(), 1.0) # Scale y to max score
logo.ax.margins(x=0, y=0)
logo.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
logo.style_xticks(spacing=5, rotation=0)
logo.ax.tick_params(axis='both', which='major', labelsize=40)
logo.ax.tick_params(axis='x', which='major', pad=10, labelsize=40)
#logo.ax.xaxis.labelpad = 5
out_prefix = i.split(".")[-2]
out_path = os.path.join(out_dir, out_prefix + ".pdf")
#logo.ax.figure.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
logo.fig.savefig(out_path, bbox_inches='tight', pad_inches=0.2, format='pdf')
plt.close(logo.fig)
alphabet = weight_mat.columns
aa_to_idx = {aa: i for i, aa in enumerate(alphabet)}
def alignment_to_count_matrix(alignment):
"""
alignment: list of str, all same length L
Returns: np.array (L, 20) with counts in alphabet order
"""
L = len(alignment[0])
ali_size = len(alignment)
counts = np.zeros((L, len(alphabet)))
for seq in alignment:
for i, aa in enumerate(seq):
if aa in aa_to_idx: # Ignore gaps/other chars
idx = aa_to_idx[aa]
counts[i, idx] += 1
return counts, ali_size
for i in os.listdir(out_dir):
if not i.endswith("_left.fasta"): continue
base = i.split("_")[-2]
dico_left = parse_fasta(os.path.join(out_dir,base+"_left.fasta"))
dico_right = parse_fasta(os.path.join(out_dir,base+"_right.fasta"))
counts_1, ali_size_1 = alignment_to_count_matrix(list(dico_left.values()))
counts_2, ali_size_2 = alignment_to_count_matrix(list(dico_right.values()))
g = gcd(ali_size_1, ali_size_2)
balanced_counts = (counts_1 * (ali_size_2 // g) + counts_2 * (ali_size_1 // g))
non_gaps = balanced_counts.sum(axis=1)
num_seq = 2*(ali_size_2 * ali_size_1) / g
widths = non_gaps/num_seq
with np.errstate(divide='ignore', invalid='ignore'):
effective_n = balanced_counts.sum(axis=1)
raw_freqs = balanced_counts / effective_n[:, None]
raw_freqs = np.where(np.isfinite(raw_freqs), raw_freqs, 0.0)
observed_entropy = entropy(raw_freqs, axis=1, base=2)
observed_entropy = entropy(raw_freqs, axis=1, base=2)
info_content = np.log2(20) - observed_entropy # shape = (positions,)
info_content = np.where(np.isfinite(info_content), info_content, 0.0)
scaled_freqs = raw_freqs * info_content[:, None]
pwm = pd.DataFrame(scaled_freqs,
index=[i for i in range(scaled_freqs.shape[0])], # '0', '1', '2'...
columns=['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y'])
fig_x = len(seqs[0])
fig_y = 6
while (fig_x > 2**16) or (fig_y > 2**16):
fig_x /= 2
fig_y /= 2
logo = logomaker.Logo(pwm, color_scheme='chemistry', figsize=(fig_x, fig_y))
for pos in range(len(widths)):
for char in ['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y']:
logo.style_single_glyph(pos, char, width=widths[pos]*0.95) #base width
# Customize (mimic WebLogo options)
logo.ax.set_title(base+" Entropy (bits)",
fontsize=80, pad=20)
logo.ax.set_ylabel("") # No y-label (like yaxis_label="")
logo.ax.set_ylim(0, np.log2(20)) # Scale y to max score
logo.ax.margins(x=0, y=0)
logo.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
logo.style_xticks(spacing=5, rotation=0)
logo.ax.tick_params(axis='both', which='major', labelsize=40)
logo.ax.tick_params(axis='x', which='major', pad=10, labelsize=40)
#logo.ax.xaxis.labelpad = 5
out_prefix = base
out_path = os.path.join(out_dir, out_prefix + ".pdf")
#logo.ax.figure.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
logo.fig.savefig(out_path, bbox_inches='tight', pad_inches=0.2, format='pdf')
plt.close(logo.fig)
out_path = os.path.join(out_dir, out_prefix + ".pdf")
ordered_pdfs = [os.path.join(out_dir,base+".pdf"), os.path.join(out_dir,base+"_left.pdf"), os.path.join(out_dir,base+"_right.pdf")]
merger = PdfWriter()
for pdf in ordered_pdfs:
merger.append(pdf)
with open(os.path.join(out_dir,"merged_logos", base + ".pdf"), "wb") as output_file:
merger.write(output_file)
merger.close()
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 MSA + Residue-level contribution, compute Logo figure. Width scale with column occupanncy.
"""
import os
import argparse
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from scipy.stats import entropy
import pickle
from math import gcd
import re
from Bio import AlignIO, SeqIO
from Bio.Align import MultipleSeqAlignment
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
import logomaker
from ete3 import Tree
from pypdf import PdfWriter
from PLMV_common import parse_fasta
# Standard 20 amino acids (uppercase) + lowercase + gap
standard_chars = 'ACDEFGHIKLMNPQRSTVWYacdefghiklmnpqrstvwy-'
def replace_nonstandard_with_gap_regex(alignment):
"""
Replace non-standard amino acids with '-' using regex.
Preserves alignment structure and sequence metadata.
"""
new_records = []
for record in alignment:
seq_str = str(record.seq)
# Replace anything NOT in standard set with '-'
# ^ inside [] means "not", so [^standard_chars] matches non-standard
modified_seq = re.sub(f'[^{standard_chars}]', '-', seq_str)
new_record = SeqRecord(
Seq(modified_seq),
id=record.id,
name=record.name,
description=record.description,
annotations=record.annotations.copy(),
dbxrefs=record.dbxrefs[:], # Shallow copy of dbxrefs
letter_annotations=record.letter_annotations.copy()
)
new_records.append(new_record)
return MultipleSeqAlignment(new_records)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--viz-dir', dest='viz_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('--out-dir',dest="out_dir")
parser.add_argument("--refnode",dest="refnode",default="None",type=str,help="node to use as reference")
args = parser.parse_args()
args_dict = vars(args)
viz_dir = args_dict['viz_dir']
out_dir = args_dict['out_dir']
os.makedirs(out_dir, exist_ok=True)
os.makedirs(os.path.join(out_dir, "merged_logos"), exist_ok=True)
tree = args_dict['tree']
MSA = args_dict['MSA']
refnodename = args_dict['refnode']
t = Tree(tree,format=1)
alignment = alignment = replace_nonstandard_with_gap_regex(AlignIO.read(MSA, "fasta"))
refnode = t&refnodename
for i in os.listdir(viz_dir):
if i.endswith(".pkl"):
with open(os.path.join(viz_dir,i),"rb") as f:
scores = pickle.load(f)
ali_mapping =dict()
for e,i in enumerate(alignment):
ali_mapping[(i.name).replace(":","_")]=e
for k,v in scores.items():
#print(k)
node = t&k
ali_node = alignment[0:0]
cpt = 0
id_node = dict()
for l in node.get_leaf_names():
if l in ali_mapping:
e = ali_mapping[l]
ali_node.append(alignment[e])
id_node[l] = cpt
cpt += 1
#Below code can be used to prune fully gapped columns but it might be harder to then interpret the scores + ali
#node_func_score = []
#pruned_ali_node = ali_node[::,0:0]
#for i in range(len(ali_node[0])):
# col = ali_node[::,i]
# if col != "-"*len(ali_node):
# pruned_ali_node += ali_node[::,i:i+1]
# node_func_score.append(scores[k][i])
#node_func_score = np.array(node_func_score)
node_func_score = scores[k]
pruned_ali_node = ali_node
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
ali_left = alignment[0:0]
ali_right = alignment[0:0]
for l in left.get_leaf_names():
if l in id_node:
id = id_node[l]
ali_left.append(pruned_ali_node[id])
for l in right.get_leaf_names():
if l in id_node:
id = id_node[l]
ali_right.append(pruned_ali_node[id])
#print(len(pruned_ali_node),pruned_ali_node.get_alignment_length())
#print(len(ali_left),ali_left.get_alignment_length())
#print(len(ali_right),ali_right.get_alignment_length())
AlignIO.write(ali_left, os.path.join(out_dir, k+"_left"+".fasta"), "fasta")
AlignIO.write(ali_right, os.path.join(out_dir, k+"_right"+".fasta"), "fasta")
for i in os.listdir(out_dir):
if not i.endswith(".fasta"): continue
path = os.path.join(out_dir, i)
# Read sequences from FASTA
seqs = list(SeqIO.parse(path, "fasta"))
seq_strings = [str(seq.seq) for seq in seqs]
# Compute count matrix
count_mat = logomaker.alignment_to_matrix(seq_strings, to_type="counts")
score = scores[i.split("_")[-2]]#np.maximum(0.0, scores[i.split("_")[-2]])
prob_mat = count_mat.div(count_mat.sum(axis=1), axis=0).fillna(0) # Position-wise probabilities
weight_mat = prob_mat.multiply(score[:, None], axis=0)
parent_name, side = i.split("_")
parent_node = t & parent_name
left, right = parent_node.children
if side.startswith("left"):
node_name = left.name
else:
node_name = right.name
fig_x = len(seqs[0])
fig_y = 6
while (fig_x > 2**16) or (fig_y > 2**16):
fig_x /= 2
fig_y /= 2
logo = logomaker.Logo(weight_mat, color_scheme='chemistry', figsize=(fig_x, fig_y))
alphabet = weight_mat.columns
aa_to_idx = {aa: i for i, aa in enumerate(alphabet)}
def alignment_to_count_matrix(alignment):
"""
alignment: list of str, all same length L
Returns: np.array (L, 20) with counts in alphabet order
"""
L = len(alignment[0])
ali_size = len(alignment)
counts = np.zeros((L, len(alphabet)))
for seq in alignment:
for i, aa in enumerate(seq):
if aa in aa_to_idx: # Ignore gaps/other chars
idx = aa_to_idx[aa]
counts[i, idx] += 1
return counts, ali_size
dico_left = parse_fasta(path)
counts_1, ali_size_1 = alignment_to_count_matrix(list(dico_left.values()))
non_gaps = counts_1.sum(axis=1)
num_seq = ali_size_1
widths = non_gaps/num_seq
for pos in range(len(widths)):
for char in ['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y']:
logo.style_single_glyph(pos, char, width=widths[pos]*0.95) #base width
# Customize (mimic WebLogo options)
logo.ax.set_title(i[:-6] + " | " + node_name + " : Functional Score",
fontsize=80, pad=20)
logo.ax.set_ylabel("") # No y-label (like yaxis_label="")
logo.ax.set_ylim(score.min(), 1.0) # Scale y to max score
logo.ax.margins(x=0, y=0)
logo.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
logo.style_xticks(spacing=5, rotation=0)
logo.ax.tick_params(axis='both', which='major', labelsize=40)
logo.ax.tick_params(axis='x', which='major', pad=10, labelsize=40)
#logo.ax.xaxis.labelpad = 5
out_prefix = i.split(".")[-2]
out_path = os.path.join(out_dir, out_prefix + ".pdf")
#logo.ax.figure.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
logo.fig.savefig(out_path, bbox_inches='tight', pad_inches=0.2, format='pdf')
plt.close(logo.fig)
alphabet = weight_mat.columns
aa_to_idx = {aa: i for i, aa in enumerate(alphabet)}
def alignment_to_count_matrix(alignment):
"""
alignment: list of str, all same length L
Returns: np.array (L, 20) with counts in alphabet order
"""
L = len(alignment[0])
ali_size = len(alignment)
counts = np.zeros((L, len(alphabet)))
for seq in alignment:
for i, aa in enumerate(seq):
if aa in aa_to_idx: # Ignore gaps/other chars
idx = aa_to_idx[aa]
counts[i, idx] += 1
return counts, ali_size
for i in os.listdir(out_dir):
if not i.endswith("_left.fasta"): continue
base = i.split("_")[-2]
dico_left = parse_fasta(os.path.join(out_dir,base+"_left.fasta"))
dico_right = parse_fasta(os.path.join(out_dir,base+"_right.fasta"))
counts_1, ali_size_1 = alignment_to_count_matrix(list(dico_left.values()))
counts_2, ali_size_2 = alignment_to_count_matrix(list(dico_right.values()))
g = gcd(ali_size_1, ali_size_2)
balanced_counts = (counts_1 * (ali_size_2 // g) + counts_2 * (ali_size_1 // g))
non_gaps = balanced_counts.sum(axis=1)
num_seq = 2*(ali_size_2 * ali_size_1) / g
widths = non_gaps/num_seq
with np.errstate(divide='ignore', invalid='ignore'):
effective_n = balanced_counts.sum(axis=1)
raw_freqs = balanced_counts / effective_n[:, None]
raw_freqs = np.where(np.isfinite(raw_freqs), raw_freqs, 0.0)
observed_entropy = entropy(raw_freqs, axis=1, base=2)
observed_entropy = entropy(raw_freqs, axis=1, base=2)
info_content = np.log2(20) - observed_entropy # shape = (positions,)
info_content = np.where(np.isfinite(info_content), info_content, 0.0)
scaled_freqs = raw_freqs * info_content[:, None]
pwm = pd.DataFrame(scaled_freqs,
index=[i for i in range(scaled_freqs.shape[0])], # '0', '1', '2'...
columns=['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y'])
fig_x = len(seqs[0])
fig_y = 6
while (fig_x > 2**16) or (fig_y > 2**16):
fig_x /= 2
fig_y /= 2
logo = logomaker.Logo(pwm, color_scheme='chemistry', figsize=(fig_x, fig_y))
for pos in range(len(widths)):
for char in ['A','C','D','E','F','G','H','I','K','L','M','N','P','Q','R','S','T','V','W','Y']:
logo.style_single_glyph(pos, char, width=widths[pos]*0.95) #base width
# Customize (mimic WebLogo options)
logo.ax.set_title(base+" Entropy (bits)",
fontsize=80, pad=20)
logo.ax.set_ylabel("") # No y-label (like yaxis_label="")
logo.ax.set_ylim(0, np.log2(20)) # Scale y to max score
logo.ax.margins(x=0, y=0)
logo.ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
logo.style_xticks(spacing=5, rotation=0)
logo.ax.tick_params(axis='both', which='major', labelsize=40)
logo.ax.tick_params(axis='x', which='major', pad=10, labelsize=40)
#logo.ax.xaxis.labelpad = 5
out_prefix = base
out_path = os.path.join(out_dir, out_prefix + ".pdf")
#logo.ax.figure.subplots_adjust(left=0, right=1, top=1, bottom=0, wspace=0, hspace=0)
logo.fig.savefig(out_path, bbox_inches='tight', pad_inches=0.2, format='pdf')
plt.close(logo.fig)
out_path = os.path.join(out_dir, out_prefix + ".pdf")
ordered_pdfs = [os.path.join(out_dir,base+".pdf"), os.path.join(out_dir,base+"_left.pdf"), os.path.join(out_dir,base+"_right.pdf")]
merger = PdfWriter()
for pdf in ordered_pdfs:
merger.append(pdf)
with open(os.path.join(out_dir,"merged_logos", base + ".pdf"), "wb") as output_file:
merger.write(output_file)
merger.close()
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 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/
"""
This script compare sequences to anchors as described in the paper.
"""
import sys, os, argparse
import gc
import time
import h5py
import torch
import torch.nn.functional as F
from aligner import alignment_cython
try:
from aligner import alignment_cuda
except:
alignment_cuda = None
import mulan
from mulan.modules import LightAttModel
import numpy as np
import math
from PLMV_common import printProgressBar
def squared_euc_dist(X, Y):
"""
Compute the euclidean distance between each pairs of position in embeddings
:param X: residues embedding representation for sequence 1
:param Y: residues embedding representation for sequence 2
:type X: pytorch tensor [*,L1,D]
:type Y: pytorch tensor [L2,D]
:return: distance matrix [*,L1,L2]
"""
sx = torch.sum(X**2, dim=-1, keepdim=True)
sy = torch.sum(Y**2, dim=-1, keepdim=True)
return -2 * (X @ Y.T) + sx + sy.T
def compute_similarity_matrix_plain_rbf(embedding1, embedding2):
""" Take as input 2 sequence embeddings (at a residue level) and returns the rbf
similarity matrix.
:param X: residues embedding representation for sequence 1
:param Y: residues embedding representation for sequence 2
:type X: pytorch tensor [*,L1,D]
:type Y: pytorch tensor [L2,D]
:return: distance matrix [*,L1,L2]
"""
return torch.exp(-squared_euc_dist(embedding1,embedding2))
def pairwise_cos_sim(x1: torch.Tensor, x2: torch.Tensor):
"""
return pair-wise similarity matrix between two tensors
:param x1: [*,L1,D]
:param x2: [L2,D]
:return: similarity matrix [*,L1,L2]
"""
x1 = F.normalize(x1, dim=-1)
x2 = F.normalize(x2, dim=-1)
sim = torch.matmul(x1, x2.transpose(-2, -1))
return sim
def get_anc_cons_score(anchor_dir,anc_name,device,preload_device,cons_model,
h5_path,th,attentions):
"""
Retrieve the embedding of the anchor, compute the functional relevance, and given the other arguments, apply the desired transformation
"""
anc_full = torch.load(os.path.join(anchor_dir,anc_name),map_location=device,weights_only=True).float()
#loading/computing conservation scores
if h5_path != '':
cons_scores = torch.from_numpy(attentions[anc_name[:-3]]).unsqueeze(1).float() #shape L x 1
else:
#sums to L and shape L x 1
cons_scores = (cons_model([anc_full.unsqueeze(0)] * 4, output_attentions=True).attention[0]).squeeze(0).mean(dim=(-2,-3)).unsqueeze(1)*anc_full.shape[-2]
anc = anc_full
#filtering low relevance sites
if th > 0:
idx = torch.where(cons_scores.squeeze(1) >= th)
anc = anc[idx]
cons_scores = cons_scores[idx]
#switching device
anc = anc.to(preload_device)
cons_scores = cons_scores.to(preload_device)
return anc, cons_scores
#change
def load_anchor(a,l_anc,l_cons,
preload_device, device):
"""
Move the anchor representation from the preloading device to computing device.
"""
if preload_device != device:
anc = l_anc[a].to(device)
cons_scores = l_cons[a].to(device)
else:
anc = l_anc[a]
cons_scores = l_cons[a]
return anc, cons_scores
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('--out-dir', dest='out_dir', default="out", type=str, help='output directory')
parser.add_argument('--force', dest='force', default="false", type=str, help='force execution')
parser.add_argument('--use-cuda', dest='use_cuda', default="True", type=str, help='True to use cuda, default:True')
#parser.add_argument('--allow-tf32', dest='allow_tf32', default="False", type=str, help='True to use allow TF32 (faster), default:False')
#parser.add_argument('--use-fp16', dest='use_fp16', default="False", type=str, help='True to use fp16, default:False')
#parser.add_argument('--use-bf16', dest='use_bf16', default="False", type=str, help='True to use bf16, default:False')
parser.add_argument('--dtype', dest='dtype', default="fp32", type=str, help='bf16, fp16, tf32 or fp32(default)')
parser.add_argument('--force-cuda-ali', dest='force_cuda_ali', default="False", type=str, help='True to use force cuda alignment, default:False')
parser.add_argument('--batch-size', dest='batch_size', default="16", type=str, help='batch_size, ignored if --use-cuda = False, default:16')
parser.add_argument('--preload-device', dest='preload_device', default="cpu", type=str, help="'cpu' or 'cuda', device where all sequence embeddings will be preloaded, default:cpu")
parser.add_argument('--h5',dest='h5',default='',type=str,help="path of h5 file containing h5 scores replacing Mulan Attention scores, default:''")
parser.add_argument('--th',dest='th',default='0',type=str,help='if > 0, filter position in anchors where cons_score > th, default:0')
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, default:True')
parser.add_argument('--th-seq',dest='th_seq',default='0',type=str,help='if > 0, filter position in sequences where cons_score > th, default:0')
parser.add_argument('--debug',dest='debug',default='False',type=str,help='debug mode, useful to time and track error in alignment code, (slightly slower), default:False')
#Parsing arguments
args = parser.parse_args()
debug = (args.debug).lower() == "true"
not_force = (args.force).lower() == "false"
use_cuda = (args.use_cuda.lower() == "true")
force_cuda_ali = (args.force_cuda_ali.lower() == "true")
if use_cuda and not torch.cuda.is_available():
print("CUDA not available, using CPU")
use_bf16 = False
use_fp16 = False
dtype = args.dtype
if dtype == "bf16":
torch_dtype = torch.bfloat16
use_bf16 = True
elif dtype == "fp16":
torch_dtype = torch.float16
use_fp16 = True
else: # fp32
torch_dtype = torch.float32
allow_tf32 = (dtype == "tf32")
torch.backends.cuda.matmul.allow_tf32 = allow_tf32
device = torch.device('cuda' if torch.cuda.is_available() and use_cuda else 'cpu')
preload_device = torch.device(args.preload_device)
preload = True
batch_size = int(args.batch_size)
use_cuda_nw = (force_cuda_ali or ((batch_size > 1) and (device.type == 'cuda'))) and alignment_cuda
h5_path = args.h5
#load functional relevance score
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, out_dir = args.anchor_dir, args.sequence_dir, args.out_dir
verbose = (args.verbose.lower() == "true")
if not_force and os.path.isfile(os.path.join(out_dir,'repr_space_mat.pt')):
print('destination already exists')
return 0
os.makedirs(out_dir, exist_ok=True)
anc_list = sorted(os.listdir(anchor_dir)) #anchors are now always in the same order since there can't be two files with the same name
seq_list = os.listdir(sequence_dir)
num_seq = str(len(seq_list))
repr_space_mat = torch.zeros(len(seq_list),2*len(anc_list))
#Load all anchors in RAM and store int in l_anc
if preload:
with torch.inference_mode():
start = time.time()
if verbose: print("[Preloading]")
l_anc = []
l_cons = []
l_anc_len = []
anc_2_id = dict()
cpt = 0
tot_iter = len(anc_list)
for e,anc_name in enumerate(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_len.append(anc.size(0))
l_anc.append(anc)
l_cons.append(cons_scores)
anc_2_id[anc_name] = e
cpt +=1
if verbose: printProgressBar(cpt,tot_iter)
del anc
if th_seq <= 0:
cons_model = None
del attentions
if use_cuda_nw:
#sort by length to pad as little as possible
ref = sorted(zip(l_anc_len, range(len(l_anc_len))))
l_anc_b = []
l_cons_b = []
anc_list_b = []
_ = [(l_anc_b.append(l_anc[i]),anc_list_b.append(anc_list[i]),l_cons_b.append(l_cons[i])) for _,i in ref]
l_mask = []
l_anc_padded = []
l_cols = []
#l_a_indices = []
#l_anc_name_batched = []
#initialize batches
for b in range(math.ceil(len(l_anc_len)/batch_size)):
#pad with one to avoid numerical instability with fp16 (multiplied by 0 anyway)
anc_padded = torch.nn.utils.rnn.pad_sequence(l_anc_b[b*batch_size:(b+1)*batch_size],batch_first=True,padding_value=1.0).to(preload_device)
if use_fp16:
anc_padded = anc_padded.half()
if use_bf16:
anc_padded = anc_padded.bfloat16()
mask_numeric = torch.nn.utils.rnn.pad_sequence(l_cons_b[b*batch_size:(b+1)*batch_size],batch_first=True).to(preload_device)
if use_fp16:
mask_numeric = mask_numeric.half()
if use_bf16:
mask_numeric = mask_numeric.bfloat16()
l_mask.append(mask_numeric)
l_anc_padded.append(anc_padded)
anc_name_batched = anc_list_b[b*batch_size:(b+1)*batch_size]
a_indices = torch.tensor([anc_2_id[name] for name in anc_name_batched])
cols = torch.stack([2 * a_indices, 2 * a_indices + 1], dim=1)
l_cols.append(cols)
#l_a_indices.append(a_indices)
del mask_numeric
del l_cons
del l_anc
del l_anc_b
del anc_padded
del anc_list_b
gc.collect()
torch.cuda.empty_cache()
stop = time.time()
time_preload = stop-start
#main loop
with torch.inference_mode():
if verbose: print("[Comparison]")
time_total= 0
tot_iter = len(anc_list) * len(seq_list)
cpt = 0
for s,seq_name in enumerate(seq_list): #for each sequence
start_seq = time.time()
seq_full = torch.load(os.path.join(sequence_dir,seq_name),map_location=device,weights_only=True)
if cons_model and th_seq > 0:
cons_scores = (cons_model([seq_full.unsqueeze(0)] * 4, output_attentions=True).attention[0]).squeeze(0).mean(dim=(-2,-3)).unsqueeze(1)*seq_full.shape[-2]
idx = torch.where(cons_scores.squeeze(1) >= th_seq)
seq_full = seq_full[idx]
seq = seq_full
if use_fp16:
seq = seq.half()
if use_bf16:
seq = seq.bfloat16()
if use_cuda_nw:
for b,(anc_padded,cols,mask) in enumerate(zip(l_anc_padded,l_cols,l_mask)):
anc_padded = anc_padded.to(device)
mask = mask.to(device)
#weights position by importance (0 for padding)
sm = mask*compute_similarity_matrix_plain_rbf(anc_padded,seq)
cs = mask*pairwise_cos_sim(anc_padded,seq)
val = sm + cs #align on this to maximize sim1 + sim2
alignment_cuda.compute_ali_mat(val,cs,debug=debug)
denom = mask.sum((-1,-2))
sim2 = cs[:,-1,-1]/denom
sim1 = val[:,-1,-1]/denom
sim1 = sim1 - sim2 # sm = sm + cs - cs
distances = torch.stack((sim1,sim2),dim=-1).float()
repr_space_mat[s, cols] = distances.cpu()
cpt += mask.size(0)
if not use_cuda_nw:
for a,anc_name in enumerate(anc_list):
#fetching the anchors
anc, cons_scores = load_anchor(a,l_anc,l_cons, preload_device, device)
#Compare the sequence to the anchor
sm = cons_scores*compute_similarity_matrix_plain_rbf(anc, seq)
cs = cons_scores*pairwise_cos_sim(anc, seq)
val = sm + cs #align on this to maximize sim1 + sim2
val_cpu = val.cpu().numpy()
cs_cpu = cs.cpu().numpy()
alignment_cython.compute_ali_mat(val_cpu,cs_cpu,*val_cpu.shape)
denom = cons_scores.sum()
sim2 = cs_cpu[-1,-1]/denom
sim1 = val_cpu[-1,-1]/denom
sim1 = sim1 - sim2 # sm = sm + cs - cs
distances = torch.stack((sim1,sim2)).cpu()
repr_space_mat[s,2*a:2*a+2] = distances
cpt += 1
if verbose: printProgressBar(cpt,tot_iter)
#can unload seq and clear the GPU VRAM
del seq
if s%100 == 0: gc.collect()
torch.cuda.empty_cache()
stop_seq = time.time()
time_total += stop_seq-start_seq
#logging wall time
if s%100 == 0 or s+1 == len(seq_list):
with open(os.path.join(out_dir,"log.txt"),"w") as f:
f.write("Sequences done : "+str(s+1)+"/"+num_seq+"\n")
f.write("Preloading time : "+str(time_preload)+" s\n")
f.write("Total comparison time : "+str(time_total)+" s\n")
#saving the representation space + name of rows/columns
torch.save(repr_space_mat,os.path.join(out_dir,'repr_space_mat.pt'))
with open(os.path.join(out_dir,'sequences_used.txt'),'w') as f_out:
for i in seq_list:
f_out.write(i+"\n")
with open(os.path.join(out_dir,'anchors_used.txt'),'w') as f_out:
for i in anc_list:
f_out.write(i+"\n")
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/
"""
This script Compute PLM embeddings for anchors and sequences. Sequences(/anchors) are first sorted by descending length. The batch size varies, it it initialized at 1, and the script tries to guess how many sequences could fit in the next batch based on memory usage.
"""
import sys, os, argparse, shutil
import gc
import torch
import time
from transformers import logging
logging.set_verbosity_error()
from PLMV_common import printProgressBar, parse_fasta
def get_vram_info(device=0):
# returns (free_bytes, total_bytes)
return torch.cuda.mem_get_info(device)
def make_embed_path(out_dir: str, header: str) -> str:
header_sanitized = header.replace("/", "_")
return os.path.join(out_dir, header_sanitized + ".pt")
def sizeof_fmt(num, suffix="B"):
for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"):
if abs(num) < 1024.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1024.0
return f"{num:.1f}Yi{suffix}"
def copy_overlap_embeddings(anchor_data, sequence_data, anchor_dir, seq_dir, replace: bool):
os.makedirs(seq_dir, exist_ok=True)
anchor_ids = set(anchor_data.keys())
seq_ids = set(sequence_data.keys())
overlap_ids = anchor_ids & seq_ids
for header in overlap_ids:
src = make_embed_path(anchor_dir, header)
dst = make_embed_path(seq_dir, header)
if not os.path.isfile(src):
continue # anchor embedding not present, nothing to copy
if (not replace) and os.path.isfile(dst):
continue # already have a seq embedding, and we don't replace
shutil.copy2(src, dst)
def embed_set_adaptive(
data,
out_dir,
model,
tokenizer,
device,
max_seq_len,
replace,
verbose,
vram_threshold=0.8,
start_bs=1,
max_bs=0,
max_vram=0,
gc_every=100,
log_fn="",
):
os.makedirs(out_dir, exist_ok=True)
items = list(data.items())
# sort by length, longest first (makes memory use easier to estimate)
items = sorted(
items,
key=lambda kv: len(kv[1]) if kv[1] is not None else 0,
reverse=True,
)
if verbose:
print(f"[Embedding into {out_dir}]")
tot_iter = len(items)
done = 0
if device.type == "cuda":
_, total_vram = get_vram_info(device.index if device.index is not None else 0)
allowed_bytes = int(total_vram * vram_threshold)
if max_vram > 0:
allowed_bytes = min(max_vram,allowed_bytes)
else:
allowed_bytes = None # unused on CPU
last_bs = start_bs
last_batch_bytes = None
i = 0
with torch.inference_mode():
while i < len(items):
# choose batch size
if device.type == "cuda" and last_batch_bytes is not None and last_batch_bytes > 0:
est_bs = int(last_bs * allowed_bytes / last_batch_bytes)
batch_size = max(1, est_bs)
if max_bs > 0:
batch_size = min(max_bs,batch_size)
else:
batch_size = last_bs
batch_headers, batch_seqs, batch_paths = [], [], []
# collect a batch, respecting max_seq_len & replace
while i < len(items) and len(batch_headers) < batch_size:
header, sequence = items[i]
i += 1
if sequence is None:
done += 1
continue
if len(sequence) > max_seq_len:
# skip very long sequences, as in original code
done += 1
if verbose:
printProgressBar(done, tot_iter)
continue
if sequence and sequence[-1] == "*":
sequence = sequence[:-1]
header_sanitized = header.replace("/", "_")
savepath = os.path.join(out_dir, header_sanitized + ".pt")
if (not replace) and os.path.isfile(savepath):
done += 1
if verbose:
printProgressBar(done, tot_iter)
continue
batch_headers.append(header_sanitized)
batch_seqs.append(sequence)
batch_paths.append(savepath)
if not batch_headers:
continue
# forward pass with OOM backoff
success = False
while not success:
try:
if log_fn:
start_total = time.time()
start_gen = time.time()
inputs = tokenizer(
batch_seqs,
return_tensors="pt",
add_special_tokens=True,
return_special_tokens_mask=True,
padding=True,
).to(device)
outputs = model(
input_ids=inputs["input_ids"],
attention_mask=inputs["attention_mask"],
)
hidden = outputs.last_hidden_state # (B, L, D)
special_mask = inputs["special_tokens_mask"].bool() # (B, L)
if log_fn:
if device.type == "cuda":
torch.cuda.synchronize() # Sync model forward
time_gen = time.time() - start_gen
start_write = time.time()
# save loop
for b_idx, savepath in enumerate(batch_paths):
mask = ~special_mask[b_idx]
emb = hidden[b_idx][mask]
torch.save(emb.cpu(), savepath) # .cpu() is async
del emb
if log_fn:
if device.type == "cuda":
torch.cuda.synchronize() # Sync .cpu() transfers
time_write = time.time() - start_write
success = True
except RuntimeError as e:
if "CUDA out of memory" in str(e) and device.type == "cuda":
# backoff: shrink batch and retry
print(
f"[WARNING] CUDA out of memory with batch_size={len(batch_headers)}; "
"reducing batch size and retrying."
)
gc.collect()
torch.cuda.empty_cache()
new_bs = max(1, len(batch_headers) // 2)
if new_bs == len(batch_headers):
# cannot shrink further; re-raise
raise
# move half of the batch back into the pool
# (shortest ones first: they were added last)
n_keep = new_bs
rollback = list(
zip(
batch_headers[n_keep:],
batch_seqs[n_keep:],
)
)
# put them back into the queue
for header_sanitized, seq in reversed(rollback):
items.insert(i, (header_sanitized, seq))
batch_headers = batch_headers[:n_keep]
batch_seqs = batch_seqs[:n_keep]
batch_paths = batch_paths[:n_keep]
last_bs = n_keep
continue
else:
raise
if log_fn:
time_total = time.time() - start_total
# measure VRAM for this batch
if device.type == "cuda":
last_bs = len(batch_headers)
last_batch_bytes = torch.cuda.max_memory_allocated(device)
torch.cuda.empty_cache() #do it everytime ???
torch.cuda.reset_peak_memory_stats(device)
if log_fn:
if device.type == "cuda":
with open(log_fn, "a+", encoding="utf-8") as f:
f.write(
f"{len(batch_headers)}\t{len(batch_seqs[0])}\t"
f"{sizeof_fmt(last_batch_bytes)}\t"
f"{time_gen:.3f}s\t{time_write:.3f}s\t{time_total:.3f}s\n"
)
else:
with open(log_fn, "a+", encoding="utf-8") as f:
f.write(
f"{len(batch_headers)}\t{len(batch_seqs[0])}\t"
f"{time_gen:.3f}s\t{time_write:.3f}s\t{time_total:.3f}s\n"
)
# cleanup
del outputs, hidden, inputs
done += len(batch_headers)
if done % gc_every == 0:
gc.collect()
if verbose:
printProgressBar(done, tot_iter)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--anchors', dest='anchor_fn', default='', type=str,
help='input fasta file containing anchors (can be empty)')
parser.add_argument('--sequences', dest='sequence_fn', default='', type=str,
help='input fasta file containing sequences to classify (can be empty)')
parser.add_argument('--anchors-dir', dest='anchor_dir', default="anchors", type=str,
help='output directory of the anchors embeddings')
parser.add_argument('--sequences-dir', dest='seq_dir', default="sequences", type=str,
help='output directory of the sequences embeddings')
parser.add_argument('--use-cuda', dest='use_cuda', default="True", type=str,
help='True if you want to use cuda, default : True')
parser.add_argument('--dtype', dest='dtype', default="fp32", type=str,
help='bf16, fp16, tf32 or fp32(default)')
parser.add_argument('--use-flash-attn', dest='use_flash_attn', default="False", type=str,
help='requires flash-attn, default : False')
parser.add_argument('--compile', dest='compile', default="False", type=str,
help='requires torch>2.0, default : False')
parser.add_argument('--replace', dest='replace', default="False", type=str,
help='replace embeddings if True, default : False')
parser.add_argument('--model', dest='f_model', default="ElnaggarLab/ankh-large", type=str,
help="model to use, default:ElnaggarLab/ankh-large.")
parser.add_argument('--max-seq-len', dest='max_seq_len', default="3000", type=str,
help='sequence over that length will be ignored, default : 3000')
parser.add_argument('--verbose', dest='verbose', default="True", type=str,
help='if True, show progress bar, default : True')
parser.add_argument('--vram-threshold', dest='vram_th', default="0.8", type=str,
help='fraction of total VRAM to use as threshold, default : 0.8')
parser.add_argument('--start-batch-size', dest='start_bs', default="1", type=str,
help='initial batch size guess, default : 1')
parser.add_argument('--max-batch-size', dest='max_bs', default="0", type=str,
help='max batch size, if > 0, default : 0')
parser.add_argument('--max-vram', dest='max_vram', default="0", type=str,
help='max VRAM in bytes, if > 0, default : 0')
parser.add_argument('--log', dest='log', default="", type=str,
help='log directory for batch sizes and seq lengths, default : ""')
args = parser.parse_args()
use_flash_attn = (args.use_flash_attn.lower() == "true")
if use_flash_attn:
torch.backends.cuda.enable_flash_sdp(True)
torch.backends.cuda.enable_mem_efficient_sdp(False)
torch.backends.cuda.enable_math_sdp(False)
dtype = args.dtype
if dtype == "bf16":
torch_dtype = torch.bfloat16
elif dtype == "fp16":
torch_dtype = torch.float16
else: # fp32
torch_dtype = torch.float32
allow_tf32 = (dtype == "tf32")
torch.backends.cuda.matmul.allow_tf32 = allow_tf32
use_torch_compile = (args.compile.lower() == "true")
attn_impl = "sdpa" if use_flash_attn else "eager"
anchor_fn, sequence_fn = args.anchor_fn, args.sequence_fn
anchor_dir, seq_dir = args.anchor_dir, args.seq_dir
if (anchor_fn == '') and (sequence_fn == ''):
return 0
replace = (args.replace.lower() == "true")
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')
logging.set_verbosity_error()
f_model = args.f_model
if "esm2" in f_model:
from transformers import EsmModel, AutoTokenizer
model = EsmModel.from_pretrained(
f_model,
torch_dtype=torch_dtype,
attn_implementation=attn_impl,
)
tokenizer = AutoTokenizer.from_pretrained(f_model, clean_up_tokenization_spaces=False)
elif "ankh" in f_model:
from transformers import T5EncoderModel, AutoTokenizer
model = model = T5EncoderModel.from_pretrained(
f_model,
torch_dtype=torch_dtype,
attn_implementation=attn_impl,
)
tokenizer = AutoTokenizer.from_pretrained(f_model, clean_up_tokenization_spaces=False)
else:
from transformers import AutoTokenizer, AutoModel
model = AutoModel.from_pretrained(
f_model,
torch_dtype=torch_dtype,
attn_implementation=attn_impl,
)
tokenizer = AutoTokenizer.from_pretrained(f_model, clean_up_tokenization_spaces=False)
model = model.to(device).eval()
if use_torch_compile:
model = torch.compile(model, dynamic=True, mode="reduce-overhead", fullgraph=False)
max_seq_len = int(args.max_seq_len)
verbose = (args.verbose.lower() == "true")
vram_th = float(args.vram_th)
start_bs = int(args.start_bs)
max_bs = int(args.max_bs)
max_vram = int(args.max_vram)
log = args.log
os.makedirs(log, exist_ok=True)
anchor_data = None
sequence_data = None
if anchor_fn != '':
anchor_data = parse_fasta(anchor_fn)
embed_set_adaptive(
data=anchor_data,
out_dir=anchor_dir,
model=model,
tokenizer=tokenizer,
device=device,
max_seq_len=max_seq_len,
replace=replace,
verbose=verbose,
vram_threshold=vram_th,
start_bs=start_bs,
max_bs=max_bs,
max_vram=max_vram,
log_fn= os.path.join(log,os.path.basename(args.anchor_dir)+".log")
)
if sequence_fn != '':
sequence_data = parse_fasta(sequence_fn)
if anchor_data is not None:
copy_overlap_embeddings(
anchor_data=anchor_data,
sequence_data=sequence_data,
anchor_dir=anchor_dir,
seq_dir=seq_dir,
replace=replace,
)
embed_set_adaptive(
data=sequence_data,
out_dir=seq_dir,
model=model,
tokenizer=tokenizer,
device=device,
max_seq_len=max_seq_len,
replace=replace,
verbose=verbose,
vram_threshold=vram_th,
start_bs=start_bs,
max_bs=max_bs,
max_vram=max_vram,
log_fn= os.path.join(log,os.path.basename(args.seq_dir)+".log")
)
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 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 a representation space, compute SCUT dendrogram.
"""
import sys, os, argparse
import numpy as np
import torch
sys.setrecursionlimit(100000)
import pickle
from sklearn.utils.extmath import randomized_svd, make_nonnegative
from scipy.sparse import diags, csr_matrix, issparse
from scipy.sparse.linalg import svds
from scipy.signal import argrelextrema
from ete3 import Tree
from sklearn.cluster import KMeans
from scipy.special import logsumexp
from scipy.fft import fft, ifft, next_fast_len
from PLMV_common import printProgressBar
def kde_logdensity_lse(X, n_s=256):
X = np.asarray(X).ravel()
n = X.size
xmin, xmax = X.min(), X.max()
X_eval = np.linspace(xmin, xmax, n_s)
std = X.std()
bw = 0.5 * 1.06 * std * n ** (-1/5) if std > 0 else 1.0
diff2 = (X_eval[None, :] - X[:, None])**2
log_kernel = -0.5 * diff2 / (bw**2)
log_density = (
logsumexp(log_kernel, axis=0)
- np.log(n)
- np.log(bw)
- 0.5 * np.log(2*np.pi)
)
return X_eval[:, None], log_density
#inititialization, later can be modified
SMOOTHING_FACTOR=0.5
def kde_logdensity_fft_padded(X, n_s=256,smoothing_factor=SMOOTHING_FACTOR):
X = np.asarray(X).ravel()
n = X.size
xmin, xmax = X.min(), X.max()
X_eval = np.linspace(xmin, xmax, n_s)
dx = X_eval[1] - X_eval[0]
# Bandwidth
std = X.std()
#we use 0.5 * Scott
bw = (1.06 * std * n ** (-1/5))*smoothing_factor if std > 0 else 1.0
# Histogram
hist, _ = np.histogram(X, bins=n_s, range=(xmin, xmax))
# --- Proper zero-centered kernel for linear convolution ---
k_grid = np.arange(-n_s + 1, n_s)
distances = k_grid * dx
kernel = np.exp(-0.5 * (distances / bw) ** 2)
kernel /= kernel.sum()
# --- Linear convolution via FFT ---
m = next_fast_len(len(hist) + len(kernel) - 1)
hist_pad = np.zeros(m)
kernel_pad = np.zeros(m)
hist_pad[:len(hist)] = hist
kernel_pad[:len(kernel)] = kernel
density_full = np.real(ifft(fft(hist_pad) * fft(kernel_pad)))
# Extract central part corresponding to histogram support
start = len(kernel) // 2
density = density_full[start:start + n_s]
# Normalize
density /= (n * dx)
density = np.maximum(density, 0.0)
log_density = np.log(density + 1e-300) #avoid log(0)
return X_eval[:, None], log_density
def merge_alternating(loc_max, loc_min):
i = j = 0
last = -1
use_max = True
extrema = []
while True:
if use_max:
while i < len(loc_max) and loc_max[i] <= last:
i += 1
if i >= len(loc_max):
break
idx = loc_max[i]
i += 1
else:
while j < len(loc_min) and loc_min[j] <= last:
j += 1
if j >= len(loc_min):
break
idx = loc_min[j]
j += 1
extrema.append(idx)
last = idx
use_max = not use_max
# enforce last element is a max
if len(extrema) > 0 and use_max:
extrema.pop()
return np.array(extrema, dtype=int)
class Counter:
def __init__(self,init_val=-1):
self.count = init_val
def get_new_id(self):
self.count += 1
return self.count
class ProgressBar:
def __init__(self,total,init_val=0):
self.count = init_val
self.total = total
def print_progress(self):
self.count += 1
printProgressBar(self.count,self.total)
def SpectralBiCoClustering(data,random_state=None,n_components=2,n_iter=5):
"""
extract both fiedler vector from "data"
"""
data[data < 0] = 0
with np.errstate(divide='ignore'):
row_diag = np.asarray(1.0 / np.sqrt(data.sum(axis=1))).squeeze()
col_diag = np.asarray(1.0 / np.sqrt(data.sum(axis=0))).squeeze()
row_diag = np.where(~np.isfinite(row_diag), 0, row_diag)
col_diag = np.where(~np.isfinite(col_diag), 0, col_diag)
an = row_diag[:, np.newaxis] * data * col_diag
U, S, Vt = randomized_svd(an,
n_components=n_components,
n_iter=n_iter,
random_state=random_state)
Fiedler_U = U[:,1]
Fiedler_V = Vt[1]
return Fiedler_U, Fiedler_V,S[1],col_diag
def th_selection(th_mode,lendata,n_min,K,U,n_s,mode):
"""
Select the threshold
"""
th = None
if th_mode == "kde" and lendata >= n_min:
#const = K/ (U.max() - U.min()) #can probably remove that, only useful with sklearn KDE
X_eval, log_dens = kde_logdensity_fft_padded(U, n_s=n_s,smoothing_factor=SMOOTHING_FACTOR)
try:
if mode == "min": #smallest local min of density
argm = argrelextrema(log_dens,np.less)[0]
th_id = argm[log_dens[argm].argmin()]
th = (X_eval)[th_id][0]
conf = 0
if mode == "valley": #search for 2 high density peaks and the deepest valley between them
# --- Get Local extremas ---
loc_min = argrelextrema(log_dens, np.less_equal)[0]
loc_max = argrelextrema(log_dens, np.greater_equal)[0]
# --- Merge extrema for cumputation ---
extrema_idx = merge_alternating(loc_max,loc_min)
extrema_vals = log_dens[extrema_idx]
# --- Distance to highest peak on the left ---
left_peak = np.maximum.accumulate(extrema_vals)
left_dist = left_peak - extrema_vals
# --- Distance to highest peak on the right ---
right_peak = np.maximum.accumulate(extrema_vals[::-1])[::-1]
right_dist = right_peak - extrema_vals
# --- Valley scoring ---
dist_prod = left_dist * right_dist
# Only valleys (odd indices in alternating sequence)
valley_scores = dist_prod[1::2]
valley_extrema = extrema_idx[1::2]
best_valley_idx = valley_extrema[np.argmax(valley_scores)]
th = (X_eval)[best_valley_idx][0]
conf = 1 - np.exp(-0.5 * np.sqrt(valley_scores.max()))
except:
pass
if th == None: #search for largest gap between datapoints in the projection
u_cpy = U.copy()
u_cpy.sort()
idx = np.argmax(u_cpy[1:]-u_cpy[:-1])
th = (u_cpy[idx+1]+u_cpy[idx])/2
conf = 0
if th_mode == "zero":
th = 0
conf = 0
if th_mode == "median":
conf = 0
th = np.median(U)
if th_mode == "kmeans++":
kmeans = KMeans(n_clusters=2, random_state=42, n_init=10,init="k-means++")
U_reshaped = U.reshape(-1, 1)
kmeans.fit(U_reshaped)
centers = kmeans.cluster_centers_.flatten()
th = centers.mean()
conf = 0
if th_mode == "kmeans":
kmeans = KMeans(n_clusters=2, random_state=42, n_init=10,init="random")
U_reshaped = U.reshape(-1, 1)
kmeans.fit(U_reshaped)
centers = kmeans.cluster_centers_.flatten()
th = centers.mean()
conf = 0
return th, conf
def _RecClusterDataToTree(full_data,data_ids,seq_ids,treenode,counter,distsum,th_mode="kde",K=10,mode='valley',n_min=1,n_s=256,seed=None,prog_bar=None):
"""
Recursively build a clustering dendrogram
"""
data = full_data[data_ids]
if data.shape[0] == 2: #cherry case
treenode.support = 0
is_sparse = issparse(data)
# --- Compute row/column scaling factors ---
with np.errstate(divide='ignore'):
if is_sparse:
row_diag = 1.0 / np.sqrt(data.sum(axis=1)).A1
col_diag = 1.0 / np.sqrt(data.sum(axis=0)).A1
else:
row_diag = 1.0 / np.sqrt(data.sum(axis=1))
col_diag = 1.0 / np.sqrt(data.sum(axis=0))
row_diag = np.where(np.isfinite(row_diag), row_diag, 0)
col_diag = np.where(np.isfinite(col_diag), col_diag, 0)
if is_sparse:
data = diags(row_diag) @ data @ diags(col_diag)
else:
data = row_diag[:, None] * data * col_diag
cd = col_diag
x1 = data[0]
x2 = data[1]
V = x2 - x1 #classifier is determined with closed form formula in the normalized space
if is_sparse:
th = -((x1 @ x1.T).toarray()[0,0] - (x2 @ x2.T).toarray()[0,0]) / 2
else:
th = -((x1 @ x1) - (x2 @ x2)) / 2
treenode.add_feature("V",V)
treenode.add_feature("th",th)
treenode.add_feature("S",1)
treenode.add_feature("cd",cd)
neg_node = treenode.add_child(name=seq_ids[0])
neg_node.dist = distsum
neg_node.support = 0
if prog_bar is not None:
prog_bar.print_progress()
pos_node = treenode.add_child(name=seq_ids[1])
pos_node.dist = distsum
pos_node.support = 0
if prog_bar is not None:
prog_bar.print_progress()
elif data.shape[0] > 2:
U,V,S,cd = SpectralBiCoClustering(data,random_state=seed)
lendata = data.shape[0]
th, conf = th_selection(th_mode,lendata,n_min,K,U,n_s,mode)
treenode.support = conf
neg_idx = np.where(U < th)[0]
pos_idx = np.where(U >= th)[0]
# only happens with median, if median is also the smallest element
if len(neg_idx) == 0:
sorted_idx = np.argsort(U)
mid = len(U) // 2
neg_idx = sorted_idx[:mid]
pos_idx = sorted_idx[mid:]
assert (len(neg_idx) > 0)
assert (len(pos_idx) > 0)
val_neg = (data[neg_idx]).sum()
val_pos = (data[pos_idx]).sum()
del data
mask_neg = np.zeros(len(seq_ids), dtype=bool)
mask_neg[neg_idx] = True
mask_pos = np.zeros(len(seq_ids), dtype=bool)
mask_pos[pos_idx] = True
neg_seq_ids = [seq_id for seq_id, m in zip(seq_ids, mask_neg) if m]
pos_seq_ids = [seq_id for seq_id, m in zip(seq_ids, mask_pos) if m]
treenode.add_feature("V",V)
treenode.add_feature("th",th)
treenode.add_feature("S",S)
treenode.add_feature("cd",cd)
neg_distsum = len(neg_idx) * (full_data).shape[1] - val_neg
pos_distsum = len(pos_idx) * (full_data).shape[1] - val_pos
#add neg first so left == {U < th}
if (len(neg_idx) > 1):
name = "I"+str(counter.get_new_id())
neg_node = treenode.add_child(name=name)
neg_node.dist = distsum - neg_distsum
_RecClusterDataToTree(full_data,data_ids[neg_idx],neg_seq_ids,neg_node,counter,neg_distsum,
th_mode=th_mode,K=K,mode=mode,n_min=n_min,n_s=n_s,seed=seed,prog_bar=prog_bar)
if (len(neg_idx) == 1):
neg_node = treenode.add_child(name=neg_seq_ids[0])
neg_node.dist = distsum
neg_node.support = 0
if prog_bar is not None:
prog_bar.print_progress()
#add pos second so right == {U >= th}
if (len(pos_idx) > 1):
name = "I"+str(counter.get_new_id())
pos_node = treenode.add_child(name=name)
pos_node.dist = distsum - pos_distsum
_RecClusterDataToTree(full_data,data_ids[pos_idx],pos_seq_ids,pos_node,counter,pos_distsum,
th_mode=th_mode,K=K,mode=mode,n_min=n_min,n_s=n_s,seed=seed,prog_bar=prog_bar)
if (len(pos_idx) == 1):
pos_node = treenode.add_child(name=pos_seq_ids[0])
pos_node.dist = distsum
pos_node.support = 0
if prog_bar is not None:
prog_bar.print_progress()
def ClusterDataToTree(data,seq_ids,fname = "tree.treefile",pickle_name = "",th_mode="kde",mode="valley",K=10,n_min=64,n_s=1000,seed=None,verbose=False):
"""
Build clustering dendrogram and save it in extended newick format and pickle format
"""
counter = Counter()
root = Tree()
root.dist = 0
root.name = "ROOT"
n = data.shape[0]
data_ids = np.array(list(range(n)))
distsum = data.shape[0] * data.shape[1] - data.sum()
if verbose:
prog_bar= ProgressBar(len(data))
else:
prog_bar = None
_RecClusterDataToTree(data,data_ids,seq_ids,root,counter,distsum,th_mode=th_mode,K=K,mode=mode,n_min=n_min,n_s=n_s,seed=seed,prog_bar=prog_bar)
#we divide the distance by n so that it scales with n and not n^2 (easier for iTOL)
for node in root.traverse():
node.dist = node.dist/n
if fname != "":
trickroot = Tree()
trickroot.dist = 0
trickroot.add_child(root)
trickroot.write(format=1, features=["support"],outfile=fname) #Use trick root for newick file only, because iTOL display
if pickle_name != "":
with open(pickle_name, 'wb') as handle: #CAREFUL! trick root is not saved in pickle file
pickle.dump(root, handle, protocol=pickle.HIGHEST_PROTOCOL)
return root
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('--verbose',dest='verbose', default="True", type=str, help='if True, show progress bar')
parser.add_argument('--mode',dest='mode', default="valley", type=str, help='"valley" or "min"')
parser.add_argument('--seed',dest='seed',default="None",type=str,help="Random seed, for reproducibility")
parser.add_argument('--n-min',dest='n_min',default='64',type=str,help="Min. number of samples to use density estimation")
parser.add_argument('--n-samples-kde',dest='n_s',default='1000',type=str,help="Number of density samples using KDE")
parser.add_argument('--smoothing',dest='smoothing_factor',default='0.5',type=str,help="smooting factor for KDE default:0.5")
#parser.add_argument('--force', dest='force', default="false", type=str, help='force execution')
args = parser.parse_args()
global SMOOTHING_FACTOR
in_dir, out_dir, prefix,verbose,mode,seed,n_min,n_s,SMOOTHING_FACTOR = args.repr_space,args.out_dir,args.prefix,args.verbose,args.mode, args.seed,args.n_min,args.n_s,float(args.smoothing_factor)
if seed == "None":
seed = None
else:
seed = int(seed)
n_min = int(n_min)
n_s = int(n_s)
verbose = verbose.lower() == "true"
with open(os.path.join(in_dir,'sequences_used.txt'),"r") as f:
lines = f.readlines()
seq_ids = [line[:-4] for line in lines]
os.makedirs(out_dir, exist_ok=True)
out_nhx = os.path.join(out_dir,prefix+".nhx")
out_pkl = os.path.join(out_dir,prefix+".pkl")
repr_space = np.array(torch.load(os.path.join(in_dir,'repr_space_mat.pt'),weights_only=True))
if verbose: print("[Building tree]")
autodt = ClusterDataToTree(repr_space,seq_ids,fname = out_nhx ,pickle_name = out_pkl, th_mode="kde",mode=mode,K=10,n_min=n_min,n_s=n_s,seed=seed,verbose=verbose)
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/
"""
Compute SCUT, and give visualization of a given split.
This needs a rewrite.
This operation should be done given an already built .nhx Tree, and only done on given nodes, instead of rebuilding the whole tree.
"""
import sys, os, argparse
import torch
import numpy as np
import pickle
from sklearn.utils.extmath import randomized_svd, make_nonnegative
from sklearn.neighbors import KernelDensity
from scipy.signal import argrelextrema
from ete3 import Tree
import matplotlib.pyplot as plt
from PLMV_common import printProgressBar
class Counter:
def __init__(self,init_val=-1):
self.count = init_val
def get_new_id(self):
self.count += 1
return self.count
class ProgressBar:
def __init__(self,total,init_val=0):
self.count = init_val
self.total = total
def print_progress(self):
self.count += 1
printProgressBar(self.count,self.total)
def SpectralBiCoClustering(data,random_state=None,n_components=2,n_iter=5):
"""
extract both fiedler vector from "data"
"""
data[data < 0] = 0
with np.errstate(divide='ignore'):
row_diag = np.asarray(1.0 / np.sqrt(data.sum(axis=1))).squeeze()
col_diag = np.asarray(1.0 / np.sqrt(data.sum(axis=0))).squeeze()
row_diag = np.where(~np.isfinite(row_diag), 0, row_diag)
col_diag = np.where(~np.isfinite(col_diag), 0, col_diag)
an = row_diag[:, np.newaxis] * data * col_diag
U, S, Vt = randomized_svd(an,
n_components=n_components,
n_iter=n_iter,
random_state=random_state)
Fiedler_U = U[:,1]
Fiedler_V = Vt[1]
return Fiedler_U, Fiedler_V,S[1],col_diag
def SpectralBiCoClustering_exp(data,random_state=None,n_components=3,n_iter=5):
"""
extract both fiedler vector from "data"
"""
data[data < 0] = 0
with np.errstate(divide='ignore'):
row_diag = np.asarray(1.0 / np.sqrt(data.sum(axis=1))).squeeze()
col_diag = np.asarray(1.0 / np.sqrt(data.sum(axis=0))).squeeze()
row_diag = np.where(~np.isfinite(row_diag), 0, row_diag)
col_diag = np.where(~np.isfinite(col_diag), 0, col_diag)
an = row_diag[:, np.newaxis] * data * col_diag
U, S, Vt = randomized_svd(an,
n_components=n_components,
n_iter=n_iter,
random_state=random_state)
Fiedler_U = U[:,1]
U_2 = U[:,2]
Fiedler_V = Vt[1]
return Fiedler_U, U_2, Fiedler_V,S[1],col_diag
def parse_itol_colorstrip(filename):
"""
Parse an iTOL DATASET_COLORSTRIP file and return a dict mapping:
leaf_name -> hex_color
Supports:
- SEPARATOR TAB / COMMA / SPACE
- Multi-column DATA lines: leaf, color, (optional group/index)
"""
leaf_to_color = {}
separator = None
in_data = False
with open(filename, "r") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
# Detect separator
if line.upper().startswith("SEPARATOR"):
# Example: "SEPARATOR TAB"
_, sep = line.split(None, 1)
sep = sep.strip().upper()
if sep == "TAB":
separator = "\t"
elif sep == "COMMA":
separator = ","
else:
separator = None # whitespace fallback
continue
# Detect start of DATA section
if line.upper() == "DATA":
in_data = True
continue
# Parse DATA lines
if in_data:
# Split according to chosen separator
if separator is None:
parts = line.split()
else:
parts = line.split(separator)
if len(parts) < 2:
continue # malformed line
leaf = parts[0].strip()
color = parts[1].strip()
leaf_to_color[leaf] = color
continue
return leaf_to_color
def th_selection(th_mode,U,lendata,n_min,K=10,n_s=500,mode="valley"):
"""
Select the threshold
"""
th = None
if th_mode == "kde" and lendata >= n_min:
const = int(K/ (U[:, np.newaxis].max() - U[:, np.newaxis].min()))
X = U[:, np.newaxis]*const #scale of data seems to be important for kde (bandwidth)
X_eval = np.linspace(X.min(), X.max(), n_s)[:, np.newaxis]
kde = KernelDensity(kernel="gaussian", bandwidth="scott").fit(X)
log_dens = kde.score_samples(X_eval)
try:
if mode == "min": #smallest local min of density
argm = argrelextrema(log_dens,np.less)[0]
th_id = argm[log_dens[argm].argmin()]
th = (X_eval/const)[th_id][0]
conf = 0
if mode == "valley": #search for 2 high density peaks and the deepest valley between them
loc_min = argrelextrema(log_dens,np.less)[0]
loc_max = argrelextrema(log_dens,np.greater_equal)[0]
local_extrema = [loc_max[0]]
for i in range(len(loc_min)):
local_extrema.append(loc_min[i])
local_extrema.append(loc_max[i+1])
left_dist = [] #highest peak at the left of the valley
curr_l_max = log_dens[local_extrema][0]
for i in log_dens[local_extrema]:
if i > curr_l_max:
curr_l_max = i
left_dist.append(curr_l_max-i)
right_dist = [] #highest peak at the right of the valley
curr_r_max = log_dens[local_extrema][-1]
for i in log_dens[local_extrema][::-1]:
if i > curr_r_max:
curr_r_max = i
right_dist.append(curr_r_max-i)
dist_prod = np.array(left_dist)*np.array(right_dist[::-1])
th_id = loc_min[(dist_prod.argmax()-1)//2]
th = (X_eval/const)[th_id][0]
conf = 1 - np.exp(-np.sqrt(dist_prod.max()) * 0.5)
except:
pass
if th == None: #search for largest gap between datapoints in the projection
u_cpy = U.copy()
u_cpy.sort()
idx = np.argmax(u_cpy[1:]-u_cpy[:-1])
th = (u_cpy[idx+1]+u_cpy[idx])/2
conf = 0
return th, conf
def _RecClusterDataToTree(full_data,data_ids,seq_ids,treenode,counter,distsum,th_mode="kde",K=10,mode='valley',n_min=64,n_s=1000,seed=None,prog_bar=None):
"""
Recursively build a clustering dendrogram
"""
data = full_data[data_ids]
if data.shape[0] == 2: #cherry case
treenode.support = 0
data[data < 0] = 0
with np.errstate(divide='ignore'):
row_diag = np.asarray(1.0 / np.sqrt(data.sum(axis=1))).squeeze()
col_diag = np.asarray(1.0 / np.sqrt(data.sum(axis=0))).squeeze()
row_diag = np.where(~np.isfinite(row_diag), 0, row_diag)
col_diag = np.where(~np.isfinite(col_diag), 0, col_diag)
data = row_diag[:, np.newaxis] * data * col_diag
cd = col_diag
x1 = data[0]
x2 = data[1]
V = x2 - x1 #classifier is determined with closed form formula in the normalized space
th = - ((x1@x1)-(x2@x2)) /2
treenode.add_feature("V",V)
treenode.add_feature("th",th)
treenode.add_feature("S",1)
treenode.add_feature("cd",cd)
neg_node = treenode.add_child(name=seq_ids[0])
neg_node.dist = distsum
neg_node.support = 0
if prog_bar is not None:
prog_bar.print_progress()
pos_node = treenode.add_child(name=seq_ids[1])
pos_node.dist = distsum
pos_node.support = 0
if prog_bar is not None:
prog_bar.print_progress()
elif data.shape[0] > 2:
if treenode.name in nodes_explain:
U,U2,V,S,cd = SpectralBiCoClustering_exp(data,random_state=seed)
else:
U,V,S,cd = SpectralBiCoClustering(data,random_state=seed)
lendata = data.shape[0]
th, conf = th_selection(th_mode,U,lendata,n_min,K,n_s,mode)
treenode.support = conf
neg_idx = np.where(U < th)[0]
pos_idx = np.where(U >= th)[0]
val_neg = (data[neg_idx]).sum()
val_pos = (data[pos_idx]).sum()
del data
assert (len(neg_idx) > 0)
assert (len(pos_idx) > 0)
mask_neg = np.zeros(len(seq_ids), dtype=bool)
mask_neg[neg_idx] = True
mask_pos = np.zeros(len(seq_ids), dtype=bool)
mask_pos[pos_idx] = True
neg_seq_ids = [seq_id for seq_id, m in zip(seq_ids, mask_neg) if m]
pos_seq_ids = [seq_id for seq_id, m in zip(seq_ids, mask_pos) if m]
treenode.add_feature("V",V)
if treenode.name in nodes_explain:
treenode.add_feature("seq_ids",seq_ids)
treenode.add_feature("data_ids",data_ids)
treenode.add_feature("U",U)
treenode.add_feature("U2",U2)
treenode.add_feature("th",th)
treenode.add_feature("S",S)
treenode.add_feature("cd",cd)
neg_distsum = len(neg_idx) * (full_data).shape[1] - val_neg
pos_distsum = len(pos_idx) * (full_data).shape[1] - val_pos
#add neg first so left == {U < th}
if (len(neg_idx) > 1):
name = "I"+str(counter.get_new_id())
neg_node = treenode.add_child(name=name)
neg_node.dist = distsum - neg_distsum
_RecClusterDataToTree(full_data,data_ids[neg_idx],neg_seq_ids,neg_node,counter,neg_distsum,
th_mode=th_mode,K=K,mode=mode,n_min=n_min,n_s=n_s,seed=seed,prog_bar=prog_bar)
if (len(neg_idx) == 1):
neg_node = treenode.add_child(name=neg_seq_ids[0])
neg_node.dist = distsum
neg_node.support = 0
if prog_bar is not None:
prog_bar.print_progress()
#add pos second so right == {U >= th}
if (len(pos_idx) > 1):
name = "I"+str(counter.get_new_id())
pos_node = treenode.add_child(name=name)
pos_node.dist = distsum - pos_distsum
_RecClusterDataToTree(full_data,data_ids[pos_idx],pos_seq_ids,pos_node,counter,pos_distsum,
th_mode=th_mode,K=K,mode=mode,n_min=n_min,n_s=n_s,seed=seed,prog_bar=prog_bar)
if (len(pos_idx) == 1):
pos_node = treenode.add_child(name=pos_seq_ids[0])
pos_node.dist = distsum
pos_node.support = 0
if prog_bar is not None:
prog_bar.print_progress()
def ClusterDataToTree(data,seq_ids,fname = "tree.treefile",pickle_name = "",th_mode="kde",mode="valley",K=10,n_min=64,n_s=500,seed=None,verbose=False):
"""
Build clustering dendrogram and save it in extended newick format and pickle format
"""
counter = Counter()
root = Tree()
root.dist = 0
root.name = "ROOT"
n = data.shape[0]
data_ids = np.array(list(range(n)))
distsum = data.shape[0] * data.shape[1] - data.sum()
if verbose:
prog_bar= ProgressBar(len(data))
else:
prog_bar = None
_RecClusterDataToTree(data,data_ids,seq_ids,root,counter,distsum,th_mode=th_mode,K=K,mode=mode,n_min=n_min,n_s=n_s,seed=seed,prog_bar=prog_bar)
#we divide the distance by n so that it scales with n and not n^2 (easier for iTOL)
for node in root.traverse():
node.dist = node.dist/n
if fname != "":
trickroot = Tree()
trickroot.dist = 0
trickroot.add_child(root)
trickroot.write(format=1, features=["support"],outfile=fname) #Use trick root for newick file only, because iTOL display
if pickle_name != "":
with open(pickle_name, 'wb') as handle: #CAREFUL! trick root is not saved in pickle file
pickle.dump(root, handle, protocol=pickle.HIGHEST_PROTOCOL)
return root
def th_selection_plot(th_mode, U, lendata, n_min=1, K=10, n_s=500, mode="valley"):
th = None
X_eval = None
log_dens = None
if th_mode == "kde" and lendata >= n_min:
const = int(K / (U[:, np.newaxis].max() - U[:, np.newaxis].min()))
X = U[:, np.newaxis] * const # scale for KDE
X_eval = np.linspace(X.min(), X.max(), n_s)[:, np.newaxis]
kde = KernelDensity(kernel="gaussian", bandwidth="scott").fit(X)
log_dens = kde.score_samples(X_eval) # shape (n_s,)
# ... your existing threshold logic here, setting th ...
return th, X_eval, log_dens
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('--verbose',dest='verbose', default="True", type=str, help='if True, show progress bar')
parser.add_argument('--mode',dest='mode', default="valley", type=str, help='"valley" or "min"')
parser.add_argument('--seed',dest='seed',default="None",type=str,help="Random seed, for reproducibility")
parser.add_argument('--n-min',dest='n_min',default='64',type=str,help="Min. number of samples to use density estimation")
parser.add_argument('--n-samples-kde',dest='n_s',default='1000',type=str,help="Number of density samples using KDE")
parser.add_argument('--nodes-explain',dest='nodes_explain',default='I0',type=str,help="Nodes where split needs to be explained, format should be I0,I1,I2 ")
parser.add_argument('--iTOL-annot',dest='iTOL_annot',default='',type=str,help="path to file containing iTOL color strip annotation")
#parser.add_argument('--force', dest='force', default="false", type=str, help='force execution')
args = parser.parse_args()
global nodes_explain # Needed to modify global copy of globvar
nodes_explain = (args.nodes_explain).split(",")
in_dir, out_dir, prefix,verbose,mode,seed,n_min,n_s = args.repr_space,args.out_dir,args.prefix,args.verbose,args.mode, args.seed,args.n_min,args.n_s
if seed == "None":
seed = None
else:
seed = int(seed)
n_min = int(n_min)
n_s = int(n_s)
verbose = verbose.lower() == "true"
with open(os.path.join(in_dir,'sequences_used.txt'),"r") as f:
lines = f.readlines()
seq_ids = [line[:-4] for line in lines]
os.makedirs(out_dir, exist_ok=True)
out_nhx = os.path.join(out_dir,prefix+".nhx")
out_pkl = os.path.join(out_dir,prefix+".pkl")
repr_space = np.array(torch.load(os.path.join(in_dir,'repr_space_mat.pt'),weights_only=True))
if verbose: print("[Building tree]")
autodt = ClusterDataToTree(repr_space,seq_ids,fname = out_nhx ,pickle_name = out_pkl, th_mode="kde",mode=mode,K=10,n_min=n_min,n_s=n_s,seed=seed,verbose=verbose)
mapping = parse_itol_colorstrip(args.iTOL_annot)
for node_name in nodes_explain:
node = autodt & node_name
U = node.U
U2 = node.U2
th, X_eval, log_dens = th_selection_plot("kde", U, lendata=len(U), n_min=n_min,K=10,n_s=n_s)
fig, ax = plt.subplots()
# --- 1) Plot log density over x-axis ---
# X_eval is in scaled space, divide by const to go back if needed
# If you want to show it in the same units as U, undo scaling:
const = int(10 / (U[:, np.newaxis].max() - U[:, np.newaxis].min()))
x_plot = X_eval[:, 0] / const
ax.plot(x_plot, log_dens, color="black")
# --- 2) Rescale U2 to match log_dens range ---
ld_min, ld_max = log_dens.min(), log_dens.max()
u2_min, u2_max = U2.min(), U2.max()
if u2_max > u2_min:
scale = (ld_max - ld_min) / (u2_max - u2_min)
else:
scale = 1.0 # degenerate case, all equal
U2_scaled = (U2 - u2_min) * scale + ld_min # map to same span as log_dens
# --- 3) Shift U2 so it is strictly positive ---
u2s_min = U2_scaled.min()
U2_shifted = U2_scaled - u2s_min
# --- 4) Add a horizontal dashed line to separate the two parts ---
ax.axhline(y=0.0, color="grey", linestyle="--")
# --- 5) Scatter plots on the same figure ---
# 5a) All points in neutral color
ax.scatter(U, U2_shifted, color="lightgrey", zorder=1)
ax.vlines(node.th, U2_shifted.min(), U2_shifted.max(), color="pink")
# 5b) Colored points where mapping has an entry (using short IDs if needed)
seq_ids = node.seq_ids
short_ids = [s.split("~", 1)[0] for s in seq_ids]
has_color = [sid in mapping for sid in short_ids]
U_col = [u for u, keep in zip(U, has_color) if keep]
U2_col = [v for v, keep in zip(U2_shifted, has_color) if keep]
c = [mapping[sid] for sid, keep in zip(short_ids, has_color) if keep]
ax.scatter(U_col, U2_col, c=c, zorder=2)
ax.set_title(f"Split at node {node_name}")
ax.set_xlabel("U")
ax.set_ylabel("log density / rescaled U2")
outfile = os.path.join(out_dir, f"{prefix}_{node_name}.png")
fig.savefig(outfile)
plt.close(fig)
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 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