Phylogenetics / Co-Evolution¶
The phylogenetics module provides tools for evolutionary coupling analysis using GREMLIN (Generative REgularized ModeLs of proteINs), co-evolved residue pair discovery, and mutation design driven by co-evolutionary signals.
Module Layout¶
REvoDesign/phylogenetics/
__init__.py # Exports: GremlinAnalyser, MutateWorker, VisualizingWorker
gremlin_tools.py # CoevolvedPair, GREMLIN_Tools
gremlin_pytorch.py # GremlinTorch (PyTorch), GREMLIN(), CustomAdamOpt, get_mtx()
evo_mutator.py # GremlinAnalyser, MutateWorker, VisualizingWorker, ChainBinder
revo_designer.py # REvoDesigner — iterative mutation design engine
Core Classes¶
GremlinAnalyser¶
The central high-level orchestrator for co-evolutionary analysis within the REvoDesign UI. It manages the full workflow:
- Loading -- Loads a GREMLIN MRF (Markov Random Field) pickle file and
initializes a
GREMLIN_Toolsinstance. - Pair discovery -- Runs all-vs-all or one-vs-all co-evolved pair analysis, depending on whether the user has a PyMOL selection active.
- Chain binding -- Calculates CA-CA distances for each co-evolved pair
via
ChainBinder, optionally in inter-chain (homooligomeric) mode. - Visualization -- Renders co-evolved pairs as colored stick bonds in
PyMOL using
cmd.pseudoatomfor lightweight pseudo-atom creation (avoids the overhead ofcmd.create()). - Navigation -- Provides previous/next pair navigation with a
QButtonMatrixGremlinwidget for interactive mutation. - Mutation -- When the user clicks a cell in the co-evolution matrix, a
Mutantobject is constructed, scored (via the activeMagicianscorer or raw matrix value), and visualized as a mutagenesis object. - Decision -- Accepted mutants are stored in
mutant_tree_coevolvedand saved to the mutants text file.
REvoDesign.phylogenetics.evo_mutator.GremlinAnalyser
¶
GREMLIN_Tools¶
Provides all GREMLIN analysis functions except the PyTorch model itself.
It loads an MRF, computes contact scores (raw, APC-corrected, z-score
normalized), identifies top co-evolving pairs, plots W matrices for individual
pairs, and returns CoevolvedPair dataclasses.
REvoDesign.phylogenetics.gremlin_tools.GREMLIN_Tools
¶
Bases: CitableModuleAbstract
CoevolvedPair¶
A dataclass representing a single co-evolved residue pair identified by GREMLIN. Tracks zero-indexed positions, wild-type amino acids, z-scores, per-chain-pair distances (for homooligomeric analysis), and output file paths (PNG, CSV). Provides convenience properties for residue selections and PyMOL selection strings.
REvoDesign.phylogenetics.gremlin_tools.CoevolvedPair
dataclass
¶
A data class that represents a coevolved pair of amino acids.
CoevolvedPairState¶
Maps visual states of co-evolved pairs to colors:
| State | Color | Meaning |
|---|---|---|
available |
marine |
Within distance cutoff, available for interaction |
out_of_range |
salmon |
Beyond distance cutoff, excluded |
in_design |
tv_yellow |
Currently being inspected/designed |
REvoDesign.phylogenetics.evo_mutator.CoevolvedPairState
dataclass
¶
A data class that represents the state-color mapping for coevolved pairs.
state2color: mapping states to colors:
- 'available' -> 'marine'
- 'out_of_range' -> 'salmon'
- 'in_design' -> 'tv_yellow'
color(state)
¶
Returns the color associated with a given state keyword
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
state_type
|
the state for the corresponding color. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
ChainBinder¶
Calculates CA-CA distances between residue pairs, supporting both intra-chain
and inter-chain (homooligomeric) modes. Uses Biopython's PDB parser for
distance calculation and joblib.Parallel for speed.
REvoDesign.phylogenetics.evo_mutator.ChainBinder
dataclass
¶
A class for managing chain binding distance calculations in molecular structures.
Attributes: - design_molecule (str): Name of the design molecule. - design_chain_id (str): ID of the main chain for calculations. - max_interact_dist (float): Maximum distance to consider two residues as interacting. - chain_binding_enabled (bool): Enable interchain binding calculations. - chains_to_bind (tuple): Chains to bind in interchain binding mode. - n_jobs (int): Number of jobs for parallel execution.
get_input_pdb()
¶
Retrieve and parse the input PDB file into a Biopython structure. Returns: - Structure object parsed from PDB.
bind_chains(coevolved_pairs)
¶
Record chain binding: distances and maximum distance to be accepted.
Parameters: - coevolved_pairs (tuple): Coevolved pairs for which distances are calculated.
Returns: - Tuple of updated CoevolvedPair objects with distance data.
MutateWorker¶
Handles profile-driven mutation design within the "Mutate" tab of the UI.
Loads a design profile (custom or Magician-based), configures the
REvoDesigner, and runs the mutation pipeline.
REvoDesign.phylogenetics.evo_mutator.MutateWorker
¶
VisualizingWorker¶
Handles the visualization tab: loads a mutant table CSV, scores mutations against a design profile, and creates a color-coded PyMOL session.
REvoDesign.phylogenetics.evo_mutator.VisualizingWorker
¶
GremlinTorch (PyTorch Model)¶
The gremlin_pytorch.py module provides a pure-PyTorch reimplementation of
the original TensorFlow-based GREMLIN model. Key components:
GremlinTorch¶
The PyTorch nn.Module implementing the GREMLIN pairwise undirected
graphical model. It learns one-body potentials (V) and two-body coupling
potentials (W) from a multiple sequence alignment (MSA).
CustomAdamOpt¶
Replicates the original TensorFlow opt_adam behavior:
- Single-scalar vt for gradient variance (sum of squared gradients)
- Per-parameter mt for momentum
- Optional bias-correction via b_fix parameter
GREMLIN() Function¶
The main training entry point:
from REvoDesign.phylogenetics.gremlin_pytorch import GREMLIN, mk_msa
msa = mk_msa(sequence_strings)
mrf = GREMLIN(msa, opt_type="adam", opt_iter=100, device="cpu")
Returns an MRF dict compatible with GREMLIN_Tools.load_mrf():
- mrf["v"] -- One-body parameters (ncol, states)
- mrf["w"] -- Two-body parameters (#pairs, states, states)
- mrf["v_idx"] -- Column index mapping for V
- mrf["w_idx"] -- Pair index mapping for W
MSA Preparation¶
parse_fasta()-- Reads FASTA files into numpy arraysfilt_gaps()-- Removes columns exceeding a gap fraction thresholdget_eff()-- Computes per-sequence weights from pairwise identitymk_msa()-- Full MSA processing pipeline returning a dict with aligned sequences, weights, effective sequence count (Neff), and index mappings
Contact Map Utilities¶
normalize()-- Box-Cox + z-score normalizationget_mtx()-- Extracts contact scores from the MRF (raw, APC, z-score). Note: there are two implementations — a module-level function ingremlin_pytorch.pyand an instance methodGREMLIN_Tools.get_mtx()ingremlin_tools.py.plot_mtx()-- Quick Matplotlib visualization of the contact map
Workflow Summary¶
MSA (FASTA)
|
v
mk_msa() # Prepare alignment, assign weights
|
v
GREMLIN() # Train model, produce MRF
|
v
GREMLIN_Tools # Load MRF, compute scores, rank pairs
|-- get_mtx() # Contact scores (raw, APC, z-score)
|-- get_to_coevolving_pairs() # Build DataFrame
|-- plot_w() # Visualize W matrix for a pair
|-- plot_w_a2a() # All-vs-all pairs
|-- plot_w_o2a() # One-vs-all pairs
|
v
ChainBinder.bind_chains() # Calculate CA-CA distances
|
v
GremlinAnalyser # UI interaction, navigation, mutation
|-- plot_coevolved_pair_in_pymol() # Render as sticks
|-- load_co_evolving_pairs() # Navigate pairs (contains nested
| # mutate_with_gridbuttons helper)
|-- coevoled_mutant_decision() # Accept/reject mutant