Commit 5b03b859 by Vinh-Son PHO

Experimental feature Embedding based MSA (EMSA)

parent 340da943
...@@ -101,6 +101,11 @@ python PLMView/src/PLMV_Logo_scaled.py --viz-dir out_explain_viz --sampled-MSA a ...@@ -101,6 +101,11 @@ python PLMView/src/PLMV_Logo_scaled.py --viz-dir out_explain_viz --sampled-MSA a
``` ```
10. Step 7. 8. and 9. are useful if, given a family, you are interested into the inner functional differences. However if you want to understand what makes a subfamily functionally different from the others, you can use `python <script-basename>_1vsall.py ` with `<refnode>` being your subfamily of interest. and `<script-basename>` the corresponding script from step 7. 8. or 9. 10. Step 7. 8. and 9. are useful if, given a family, you are interested into the inner functional differences. However if you want to understand what makes a subfamily functionally different from the others, you can use `python <script-basename>_1vsall.py ` with `<refnode>` being your subfamily of interest. and `<script-basename>` the corresponding script from step 7. 8. or 9.
## Experimental feature
11. We provide Embedding based MSA (EMSA) using cosine similarity and the PLMV tree as guide tree :
```console
python PLMView/src/PLMV_align.py --sequences input.fasta --sequences-dir sequences --tree out_tree/cluster_tree.nhx --out-dir out_msa --prefix emsa
```
## Remarks ## Remarks
To use `PLMV_explain.py` and `PLMV_infer.py`, if your tree is too large try setting `sys.setrecursionlimit()` to 10000. To use `PLMV_explain.py` and `PLMV_infer.py`, if your tree is too large try setting `sys.setrecursionlimit()` to 10000.
......
# 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 argparse, os
import numpy as np
import torch
import torch.nn.functional as F
from ete3 import Tree
from aligner import alignment_cython
from PLMV_common import printProgressBar, parse_fasta
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 Needleman_Wunsch(sim_mat):
"""
Compute the alignement using the Needleman-Wunsch algorithm
Note : gap penality is set to 0 for now
"""
value_matrix = np.array(sim_mat)
path = np.zeros(value_matrix.shape,dtype=np.int32)
alignment_cython.compute_alignment(path,value_matrix,*value_matrix.shape)
return path, value_matrix
def alignment_positions(l1, l2, pairs):
"""
Given length os seq1 and seq2, and pairs, create mapping from sequence to alignment
"""
pos1 = np.empty(l1, dtype=np.int64)
pos2 = np.empty(l2, dtype=np.int64)
i = j = 0
aln_pos = 0
for pi, pj in pairs:
while i < pi:
pos1[i] = aln_pos
aln_pos += 1
i += 1
while j < pj:
pos2[j] = aln_pos
aln_pos += 1
j += 1
pos1[i] = aln_pos
pos2[j] = aln_pos
aln_pos += 1
i += 1
j += 1
while i < l1:
pos1[i] = aln_pos
aln_pos += 1
i += 1
while j < l2:
pos2[j] = aln_pos
aln_pos += 1
j += 1
return pos1, pos2, aln_pos
def merge_profiles(
l_repr,
r_repr,
pos1,
pos2,
):
"""
Merges 2 Embedding Profiles given pairwise alignment (Sum for simplicity, works only with cosine similarity)
"""
L = max(pos1.max(), pos2.max()) + 1
d = l_repr.shape[-1]
merged_repr = torch.zeros(
(L, d),
dtype=l_repr.dtype,
device=l_repr.device,
)
# Place left profile
merged_repr[pos1] = l_repr
# Find columns present in both profiles
common, idx1, idx2 = np.intersect1d(
pos1,
pos2,
assume_unique=True,
return_indices=True,
)
# Columns only in right profile
only_right = np.setdiff1d(
pos2,
common,
assume_unique=True,
)
if len(common):
merged_repr[common] = (l_repr[idx1] + r_repr[idx2])
if len(only_right):
mask = np.isin(pos2, only_right)
right_idx = np.nonzero(mask)[0]
merged_repr[only_right] = r_repr[right_idx]
return merged_repr
def merge_childs(node):
"""
Align recursively the Embedding Profiles.
"""
#Base case, the alignment profile is a sequence embedding.
if node.is_leaf():
if node.name in DICO:
seq_path = os.path.join(SEQDIR,node.name+".pt")
repr = torch.load(seq_path, weights_only=True)
node.pos = np.arange(repr.shape[0])
return repr
return None
left, right = node.children
l_repr = merge_childs(left)
r_repr = merge_childs(right)
if l_repr is None and r_repr is None:
return None
if l_repr is None:
L = r_repr.shape[0]
right.posmap = np.arange(L)
left.posmap = None
node.pos = np.arange(L)
return r_repr
if r_repr is None:
L = l_repr.shape[0]
left.posmap = np.arange(L)
right.posmap = None
node.pos = np.arange(L)
return l_repr
sim_mat = pairwise_cos_sim(l_repr, r_repr)
path, _ = Needleman_Wunsch(sim_mat)
pairs = sorted(zip(*np.where(path)))
posl, posr, L = alignment_positions(
len(l_repr),
len(r_repr),
pairs
)
repr = merge_profiles(
l_repr,
r_repr,
posl,
posr,
)
node.pos = np.arange(L)
left.posmap = posl
right.posmap = posr
if VERBOSE:
PROGBAR.print_progress()
return repr
def finalize(node, mapping=None, L=None):
"""
Propagate the alignment to leaves
"""
assert mapping is not None or L is not None
if mapping is None:
mapping = np.arange(L)
if node.is_leaf():
node.pos = mapping
return
left, right = node.children
if left.posmap is not None:
finalize(left, mapping[left.posmap])
if right.posmap is not None:
finalize(right, mapping[right.posmap])
class ProgressBar:
def __init__(self,total,init_val=0):
self.count = init_val
self.total = total
printProgressBar(self.count,self.total)
def print_progress(self):
self.count += 1
printProgressBar(self.count,self.total)
def main():
global SEQDIR
global DICO
global VERBOSE
parser = argparse.ArgumentParser()
parser.add_argument('--sequences', dest='sequence_fn', default='', type=str,
help='input fasta file containing sequences to classify (can be empty)')
parser.add_argument('--sequences-dir', dest='sequence_dir', default='sequences', type=str,
help='folder containing sequences embeddings')
parser.add_argument('--tree', dest='tree', default="tree.nhx", type=str,
help='path to .nhx tree')
parser.add_argument('--out-dir', dest='out_dir', default="out_msa", type=str,
help='output folder')
parser.add_argument('--prefix', dest='prefix', default="emsa", type=str,
help='prefix of output file')
parser.add_argument('--verbose',dest='verbose', default="True",
type=str, help='if True, show progress bar')
args = parser.parse_args()
#Argument parsing
SEQDIR = args.sequence_dir
tree_path = args.tree
os.makedirs(args.out_dir, exist_ok=True)
out_path = os.path.join(args.out_dir,args.prefix+".fasta")
VERBOSE = (args.verbose.lower() == "true")
#Load tree and sequences
t = Tree(tree_path,format=1)
DICO = parse_fasta(args.sequence_fn)
if VERBOSE:
global PROGBAR
PROGBAR= ProgressBar(len(DICO))
#Embedding MSA
repr = merge_childs(t.children[0]) #t is the fake root
L = repr.shape[0]
finalize(t.children[0],L=L)
#Save to fasta
with open(out_path,"w") as f:
for l in t.get_leaves():
h = l.name
if h not in DICO: continue
sequence = DICO[h]
l_aa = ["-"]*L
for e,aa in enumerate(sequence):
pos = l.pos[e]
l_aa[pos] = aa
s = "".join(l_aa)
f.write(">"+h+"\n"+s+"\n")
if VERBOSE:
PROGBAR.print_progress()
if __name__ == "__main__":
main()
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