dArmRP-Assembler / utils.py
HenzProt's picture
Add application file
fd4af8c
Raw History Blame
12.7 kB
# utils.py
import pandas as pd
from itertools import product
from typing import List, Dict, Union
def pockets_reader(excel_path: str) -> List[Dict[str, str]]:
"""
Reads an Excel file containing columns 'M1', 'M2', 'Target', and 'Type',
and processes the data into a list of dictionaries for sequence assembly.
Parameters:
excel_path (str): Path to the input Excel file.
Returns:
List[Dict[str, str]]: A list of dictionaries, each with keys 'M1', 'M2', 'Target', 'Type'.
"""
# Load Excel file
df = pd.read_excel(excel_path)
# Validate expected columns
expected_columns = {'M1', 'M2', 'Target', 'Type'}
if not expected_columns.issubset(df.columns):
raise ValueError(f"Input file must contain columns: {expected_columns}")
# Drop rows with missing values
df = df.dropna(subset=["M1", "M2", "Target", "Type"])
# Convert to list of dicts
data = df[["M1", "M2", "Target", "Type"]].to_dict(orient="records")
return data
def target_processor(seq: str):
"""
Inverts the input sequence and splits it into two sequences:
- One with residues at even indices (0, 2, 4, ...)
- One with residues at odd indices (1, 3, 5, ...)
Splits the resulting sequences into lists of single-letter strings.
Args:
seq (str): Amino acid sequence.
Returns:
tuple: (even_seq, odd_seq) as lists of single-letter strings
"""
seq_inv = seq[::-1] # Invert sequence
even_seq = list(seq_inv[::2]) # Even indices (0, 2, 4, ...), as list
odd_seq = list(seq_inv[1::2]) # Odd indices (1, 3, 5, ...), as list
return even_seq, odd_seq
def assemble_sequences(
database: List[Dict[str, str]],
split_targets: List[str],
as_string: bool = False
) -> List[Union[List[str], str]]:
"""
Assemble all possible unique sequences given a split target sequence and a database of M1/M2/Target.
For n residues in split_targets, each assembled sequence contains n+1 segments, chosen according to:
- Position 0: M1 where Target == split_targets[0]
- Positions 1 to n-1: (M2 where Target == split_targets[i-1]) OR (M1 where Target == split_targets[i])
- Position n: M2 where Target == split_targets[-1]
Args:
database (list of dict): Output from pockets_reader.
split_targets (list of str): e.g., ['A', 'B', 'C', 'D']
as_string (bool): If True, returns concatenated sequences as strings. If False, returns lists.
Returns:
List: Unique assembled sequences (as lists or strings), each of length n+1.
"""
n = len(split_targets)
sequence_choices = []
# Position 0: M1 where Target == split_targets[0]
choices_0 = [row['M1'] for row in database if row['Target'] == split_targets[0]]
sequence_choices.append(choices_0)
# Positions 1 to n-1
for i in range(1, n):
# Choices: (M2 where Target == split_targets[i-1]) OR (M1 where Target == split_targets[i])
choices_m2 = [row['M2'] for row in database if row['Target'] == split_targets[i-1]]
choices_m1 = [row['M1'] for row in database if row['Target'] == split_targets[i]]
sequence_choices.append(choices_m2 + choices_m1)
# Position n: M2 where Target == split_targets[-1]
choices_n = [row['M2'] for row in database if row['Target'] == split_targets[-1]]
sequence_choices.append(choices_n)
# Generate all possible assemblies (each of length n+1)
all_combinations = product(*sequence_choices)
# Remove duplicates for unique assemblies
if as_string:
unique_assemblies = set(''.join(seq) for seq in all_combinations)
return list(unique_assemblies)
else:
unique_assemblies = set(tuple(seq) for seq in all_combinations)
return [list(seq) for seq in unique_assemblies]
def assemble_sequences_match(
database: List[Dict[str, str]],
split_targets: List[str],
as_string: bool = False
) -> List[Union[List[str], str]]:
"""
Assemble all unique sequences with matching dependencies:
- At position 0: (M1, Target=split_targets[0])
- At position i>0: (M2 with matching M1, Target=split_targets[i-1]) or (M1, Target=split_targets[i])
"""
n = len(split_targets)
unique_assemblies = set()
# Find all valid starting M1s for position 0
starters = [row for row in database if row['Target'] == split_targets[0]]
def recurse(current_seq, current_m1, idx):
"""
current_seq: List of assembled segments so far
current_m1: The M1 used at the previous position (for matching)
idx: Current position in split_targets (0-based)
"""
if idx == n:
# At final position: Need M2 with matching M1, Target=split_targets[n-1]
for row in database:
if row['Target'] == split_targets[-1] and row['M1'] == current_m1:
seq = current_seq + [row['M2']]
unique_assemblies.add(tuple(seq))
return
# Option 1: Add M2 where Target == split_targets[idx-1] AND M1 matches current_m1 (if idx > 0)
if idx > 0:
for row in database:
if row['Target'] == split_targets[idx - 1] and row['M1'] == current_m1:
recurse(current_seq + [row['M2']], current_m1, idx + 1)
# Option 2: Add M1 where Target == split_targets[idx] (advance M1)
for row in database:
if row['Target'] == split_targets[idx]:
recurse(current_seq + [row['M1']], row['M1'], idx + 1)
# Start recursion from each valid M1
for row in starters:
recurse([row['M1']], row['M1'], 1)
# Format output
if as_string:
return [''.join(seq) for seq in unique_assemblies]
else:
return [list(seq) for seq in unique_assemblies]
from typing import List, Dict, Union
def assemble_sequences_spec(
database: List[Dict[str, str]],
split_targets: List[str],
as_string: bool = False
) -> List[Union[List[str], str]]:
"""
Assemble all unique sequences with matching dependencies and Type-based specificity:
- Always use Type == 'spec' for a given Target if available; else use Type == 'wc'.
"""
n = len(split_targets)
unique_assemblies = set()
# Helper to get entries by Target and Type (preferring 'spec' over 'wc')
def get_entries(target, key):
# key: 'M1' or 'M2'
entries_spec = [row[key] for row in database if row['Target'] == target and row['Type'] == 'spec']
if entries_spec:
return entries_spec
# Fallback to 'wc'
entries_wc = [row[key] for row in database if row['Target'] == target and row['Type'] == 'wc']
return entries_wc
# Find all valid starting M1s for position 0
starters = [row for row in database if row['Target'] == split_targets[0] and row['Type'] == 'spec']
if not starters:
starters = [row for row in database if row['Target'] == split_targets[0] and row['Type'] == 'wc']
def recurse(current_seq, current_m1, idx):
if idx == n:
# At final position: need M2 with matching M1, Target=split_targets[-1], Type preference
rows_spec = [row for row in database if row['Target'] == split_targets[-1] and row['M1'] == current_m1 and row['Type'] == 'spec']
rows_wc = [row for row in database if row['Target'] == split_targets[-1] and row['M1'] == current_m1 and row['Type'] == 'wc']
rows = rows_spec if rows_spec else rows_wc
for row in rows:
seq = current_seq + [row['M2']]
unique_assemblies.add(tuple(seq))
return
# Option 1: Add M2 where Target == split_targets[idx-1] AND M1 matches current_m1, Type preference
if idx > 0:
rows_spec = [row for row in database if row['Target'] == split_targets[idx-1] and row['M1'] == current_m1 and row['Type'] == 'spec']
rows_wc = [row for row in database if row['Target'] == split_targets[idx-1] and row['M1'] == current_m1 and row['Type'] == 'wc']
rows = rows_spec if rows_spec else rows_wc
for row in rows:
recurse(current_seq + [row['M2']], current_m1, idx+1)
# Option 2: Add M1 where Target == split_targets[idx], Type preference (advance M1)
rows_spec = [row for row in database if row['Target'] == split_targets[idx] and row['Type'] == 'spec']
rows_wc = [row for row in database if row['Target'] == split_targets[idx] and row['Type'] == 'wc']
rows = rows_spec if rows_spec else rows_wc
for row in rows:
recurse(current_seq + [row['M1']], row['M1'], idx+1)
for row in starters:
recurse([row['M1']], row['M1'], 1)
if as_string:
return [''.join(seq) for seq in unique_assemblies]
else:
return [list(seq) for seq in unique_assemblies]
def add_loops(
assemblies: List[List[str]],
loop_targets: List[str],
positions: List[int],
loops: pd.DataFrame
) -> List[List[str]]:
"""
For each assembly, generate all possible assemblies by replacing 'SGGN' at specified positions
with every matching loop sequence for the given target. If no matching loop, keep 'SGGN'.
"""
# Pre-build mapping: Target -> list of loops
from collections import defaultdict
loop_dict = defaultdict(list)
for _, row in loops.iterrows():
loop_dict[row['Target']].append(row['loop'])
final_assemblies = []
for assembly in assemblies:
# For positions to modify, get all possible loop substitutions
loop_options_per_pos = []
for pos in positions:
target = loop_targets[pos]
loops_for_target = loop_dict.get(target, None)
if loops_for_target:
# Generate all versions for this position with loop substituted
loop_options_per_pos.append([assembly[pos].replace("SGGN", loop_seq) for loop_seq in loops_for_target])
else:
# No match, keep the original
loop_options_per_pos.append([assembly[pos]])
# For non-modified positions, always keep original
non_mod_positions = [i for i in range(len(assembly)) if i not in positions]
# Generate all combinations of loop substitutions
for chosen_loops in product(*loop_options_per_pos):
# Build the new assembly
new_assembly = assembly.copy()
for idx, pos in enumerate(positions):
new_assembly[pos] = chosen_loops[idx]
final_assemblies.append(new_assembly)
return final_assemblies
def capping(assemblies: List[List[str]]) -> List[List[str]]:
"""
Add N-terminal cap and special C-terminal capping with residue replacement.
Args:
assemblies (List[List[str]]): Each assembly is a list of sequence strings.
Returns:
List[List[str]]: Assemblies after capping.
"""
N_cap = "GPSLPELVRLLRSSNEEILLRALRALAEIASGGN"
C_cap_template = "EQIQAVIDAGALEKLEELSSHENDEIRRHAIEALRLLR"
c_positions = [-3, -7, -10, -14]
capped_assemblies = []
for assembly in assemblies:
new_assembly = assembly.copy()
# Add N-terminal cap
new_assembly = [N_cap] + new_assembly
# Remove "SGGN" from last segment if present
last_seq = new_assembly[-1].replace("SGGN", "")
# Replace with C_cap_template, but keep residues at [-3, -7, -10, -14] from last_seq
c_seq = list(C_cap_template)
for pos in c_positions:
if abs(pos) <= len(last_seq) and abs(pos) <= len(c_seq):
c_seq[pos] = last_seq[pos]
new_assembly[-1] = "".join(c_seq)
capped_assemblies.append(new_assembly)
return capped_assemblies
def summary(
assemblies: List[List[str]],
target_sequence: str,
name: str,
output_path: str
):
"""
Combine all segments into a single sequence for each assembly.
Write Excel file with columns: name, protein, peptide.
Args:
assemblies (List[List[str]]): Output from capping.
target_sequence (str): The peptide/target sequence.
name (str): Name prefix for each row (e.g., 'her2').
output_path (str): Path for Excel output file.
"""
summary_data = []
for idx, segments in enumerate(assemblies, 1):
protein_seq = "".join(segments)
row = {
"name": f"{name}_{idx}",
"protein": protein_seq,
"peptide": target_sequence
}
summary_data.append(row)
df = pd.DataFrame(summary_data)
df.to_excel(output_path, index=False)