Tools¶
Utility modules providing reusable functionality across REvoDesign.
General Utilities (REvoDesign.tools.utils)¶
Orphaned but widely used utility functions for configuration resolution, color mapping, archiving, device detection, and function inspection.
Key Functions¶
REvoDesign.tools.utils.run_command(*args, **kwargs)
¶
REvoDesign.tools.utils.run_worker_thread_in_pool(*args, **kwargs)
¶
REvoDesign.tools.utils.resolve_dotted_expression(dotted_str)
¶
Import the object referenced by a dotted string such as <module>:attr or
<module>:Class.member.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dotted_str
|
str
|
Fully qualified reference using a colon between the import path and the attribute/member portion. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The resolved attribute, which can be a function, class, descriptor, or any other object exposed by the module or class. |
Raises:
| Type | Description |
|---|---|
InvalidInputError
|
If the string does not contain a colon or otherwise violates the expected pattern. |
AttributeError
|
If the module, class, or attribute cannot be located. |
REvoDesign.tools.utils.resolve_dotted_function(dotted_str)
¶
Resolve a dotted reference to a callable object and return it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dotted_str
|
str
|
Dotted identifier in the form |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
The imported callable referenced by |
Raises:
| Type | Description |
|---|---|
UnsupportedDataTypeError
|
If the resolved object exists but cannot be called. |
REvoDesign.tools.utils.resolve_lambda_expression(expression, as_partial=None)
¶
resolve_lambda_expression(expression: str, as_partial: Literal[True]) -> Callable
resolve_lambda_expression(expression: str, as_partial: Literal[False] | None) -> Any
Resolve a serialized callable expression of the form
LAMBDA:<dotted_callable>[,<arg>|,<key=value>...].
Positional and keyword arguments are converted from their string form into
bools, ints, floats, or left as strings when no other conversion is
possible. When as_partial is truthy the function returns a
functools.partial; otherwise the callable is invoked immediately and its
return value is passed through.
Raises:
| Type | Description |
|---|---|
InvalidInputError
|
If the expression is not prefixed with
|
REvoDesign.tools.utils.resolve_dotted_config_item(config_string)
¶
Resolves a dotted configuration string to retrieve the corresponding configuration value.
The input string can be in one of the following formats:
1. "CFG:<config_section>:<config_item>" - Specifies both the configuration section and item.
2. "CFG:<config_item>" - Specifies only the configuration item, with no section(default for the main config section).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_string
|
str
|
The dotted configuration string to resolve. |
required |
Returns: Any: The configuration value retrieved from the specified section and item. Raises: issues.InvalidInputError: If the input string does not conform to the expected format.
REvoDesign.tools.utils.get_color(cmap, data, min_value, max_value)
¶
Get color value from a colormap based on given data.
Args: - cmap: Colormap name or object. - data: Value to map to a color. - min_value: Minimum value of the data range. - max_value: Maximum value of the data range.
Returns: - list: RGB color value based on the colormap and data.
Notes: - Uses a specified colormap to map data values to color. - Returns a RGB color value in the range [0, 1].
REvoDesign.tools.utils.cmap_reverser(cmap, reverse=False)
¶
Reverses a colormap name if the 'reverse' flag is set to True.
Args: - cmap (str): Name of the colormap. - reverse (bool): Flag indicating whether to reverse the colormap (default is False).
Returns: - str: Reversed colormap name if 'reverse' is True, otherwise returns the original colormap name.
REvoDesign.tools.utils.rescale_number(number, min_value, max_value)
¶
Rescales a number within a specified range to a value between 0 and 1.
Args: - number (float): The number to be rescaled. - min_value (float): The minimum value of the range. - max_value (float): The maximum value of the range.
Returns: - float: The rescaled value between 0 and 1.
Raises: - ValueError: If min_value is greater than or equal to max_value.
REvoDesign.tools.utils.timing(msg, unit='sec')
¶
REvoDesign.tools.utils.require_not_none(attribute_name, fallback_setup=None, error_type=issues.UnexpectedWorkflowError)
¶
Decorator factory to ensure a specific attribute of the instance is not None before the method is called.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attribute_name
|
str
|
Name of the attribute to check. |
required |
fallback_setup
|
callable
|
Function to call if the attribute is None. Defaults to None. |
None
|
error_type
|
type
|
Exception type to raise if the attribute is None and no fallback. Defaults to issues.UnexpectedWorkflowError. |
UnexpectedWorkflowError
|
REvoDesign.tools.utils.require_installed(cls)
¶
Decorator to enforce that the installed attribute of a class is True.
Raises an error if an instance is created with installed set to False.
REvoDesign.tools.utils.get_cited(method)
¶
A decorator that adds citation functionality to a method, automatically calling the appropriate cite() method.
This decorator determines which object's cite() method should be called based on the method type (class method, instance method, static method, or function) and automatically records citation information.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
Callable[P, R]
|
The method to be decorated, can be a class method, instance method, static method, or regular function |
required |
Returns:
| Type | Description |
|---|---|
Callable[P, R]
|
Returns a wrapped method that calls the appropriate cite() method after executing the original method |
REvoDesign.tools.utils.inspect_method_types(method)
¶
Inspect the type of a callable: instance method, class method, static method, or plain function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
Callable
|
The callable to inspect. |
required |
Returns:
| Type | Description |
|---|---|
MethodKind
|
Literal['InstanceMethod', 'ClassMethod', 'StaticMethod', 'Function']: |
MethodKind
|
The inferred kind of method. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the method type cannot be determined or the object |
REvoDesign.tools.utils.minibatches(inputs_data, batch_size)
¶
Generates minibatches from input data with a specified batch size.
Args: - inputs_data (list or iterable): Input data to be divided into minibatches. - batch_size (int): Size of each minibatch.
Yields: - list: Minibatches of data based on the specified batch size.
Note: If the length of the inputs_data is not perfectly divisible by the batch_size, the last batch may have fewer elements.
Example Usage:
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
batch_size = 3
for batch in minibatches(data, batch_size):
print(batch)
REvoDesign.tools.utils.minibatches_generator(inputs_data_generator, batch_size)
¶
Generates minibatches from a generator of input data with a specified batch size.
Args: - inputs_data_generator (generator): Generator yielding input data. - batch_size (int): Size of each minibatch.
Yields: - list: Minibatches of data based on the specified batch size.
Note: If the length of the inputs_data is not perfectly divisible by the batch_size, the last batch may have fewer elements.
Example Usage:
def data_generator():
for i in range(10):
yield i
batch_size = 3
for batch in minibatches_generator(data_generator(), batch_size):
print(batch)
REvoDesign.tools.utils.extract_archive(archive_file, extract_to)
¶
Extracts the contents of an archive file (zip, tar.gz, tar.bz2, tar.xz, or rar) to a specified directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
archive_file
|
str
|
Path to the archive file. |
required |
extract_to
|
str
|
Directory where the contents will be extracted. |
required |
REvoDesign.tools.utils.device_picker()
¶
Detects and returns a list of available devices for deep learning frameworks.
This function checks for the availability of GPU or specialized hardware (like MPS on macOS) using PyTorch or TensorFlow. If no compatible devices are found, it defaults to 'cpu'.
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: A list of available device strings (e.g., ['cuda:0', 'mps', 'gpu', 'cpu']). |
REvoDesign.tools.utils.pairwise_loop(iterable)
¶
Generate a looped pairwise iterable from the input iterable.
This function takes an iterable as input and returns a list of tuples, where each tuple contains a pair of consecutive elements from the iterable. The last element is paired with the first element to form a loop structure.
Parameters: iterable: Iterable - The input iterable used to generate the looped pairwise iterable.
list - A list of tuples, each containing a pair of consecutive elements. The last element is paired with the first element.
REvoDesign.tools.utils.count_and_sort_characters(input_string, characters)
¶
Counts occurrences of specified characters in a string and sorts them based on counts.
Args: - input_string (str): The input string to count characters from. - characters (list): List of characters to count in the input string.
Returns: - dict: Dictionary containing character counts sorted in descending order.
REvoDesign.tools.utils.generate_strong_password(length=16)
¶
Generate a strong random password.
Args: - length (int): Length of the password (default is 16).
Returns: - str: Strong password of the specified length.
Raises: - ValueError: If the password length is not within the range of 16 to 64 characters.
Notes: - Generates a strong password using a mix of ASCII letters, digits, and punctuation. - The password length should be between 16 and 64 characters.
REvoDesign.tools.utils.random_deduplicate(seq, score)
¶
Deduplicates a sequence while preserving random scores for unique items.
Args: - seq (numpy.array): Sequence array to deduplicate. - score (numpy.array): Array of scores corresponding to items in seq.
Returns: - numpy.array: Unique items from seq. - numpy.array: Randomly chosen scores corresponding to unique items.
REvoDesign.tools.utils.convert_residue_ranges(residue_ranges, res_prefix='', resr_prefix='', res_suffix='', resr_suffix='', connector=' | ')
¶
Converts a string of residue ranges into a string of residue segments. Example:
convert_residue_ranges('1-5+7-9+10-12+13', res_prefix='r ', resr_prefix='ri ', connector=' | ') ri 1-5 | r 7-9 | r 10-12 | r 13
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
residue_ranges
|
str
|
String of residue ranges. |
required |
res_prefix
|
str
|
Prefix to add to each residue. |
''
|
resr_prefix
|
str
|
Prefix to add to each residue range. |
''
|
res_suffix
|
str
|
Suffix to add to each residue. |
''
|
resr_suffix
|
str
|
Suffix to add to each residue range. |
''
|
connector
|
str
|
Connector to use between each residue segment. |
' | '
|
Returns: String of residue segments.
REvoDesign.tools.utils.xvg2df(xvg_file)
¶
Converts an xvg file to a pandas dataframe.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
xvg_file
|
str
|
Path to the xvg file. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
pd.DataFrame: DataFrame containing the data from the xvg file. |
Mutant Tools (REvoDesign.tools.mutant_tools)¶
Functions for parsing, manipulating, and extracting mutation data from strings, PyMOL objects, and files.
Key Functions¶
REvoDesign.tools.mutant_tools.aa3_to_aa1(three_letter_code)
¶
Convert a 3-letter amino acid code to its 1-letter equivalent.
Uses standard IUPAC codes (via Biopython) with non-standard codes
from REvoDesign.data.protein_code.rAA as a fallback.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the 3-letter code is not recognised. |
REvoDesign.tools.mutant_tools.extract_mutants_from_mutant_id(mutant_string, sequences, wt_before_chain=False)
¶
Extract mutant info from an mutant id string. This mutant can be virtual from PyMOL session.
mutant_string (str): Underscore-seperated mutant string that contains the mutations and score (if possible).
tuple: Mutant : Mutant object.
REvoDesign.tools.mutant_tools.extract_mutant_score_from_string(mutant_string)
¶
Extract mutant score from an mutant string
mutant_string (str): Underscore-seperated mutant string that contains the mutations and score (if possible).
Returns: float: Mutant score.
REvoDesign.tools.mutant_tools.extract_mutant_from_sequences(mutant_sequence, wt_sequences, chain_id='A', fix_missing=False)
¶
Extract mutant from mutant sequence.
Parameters: mutant_sequence (str): Mutant sequence. wt_sequence (str): Wild-type sequence. chain_id (str): Chain id fix_missing (bool): Fix missing residue ('X') in mutant according to the WT sequence.
Returns: Mutant: Mutant object
REvoDesign.tools.mutant_tools.extract_mutant_from_pymol_object(pymol_object, sequences)
¶
Extract mutant info from an existing pymol object.
Parameters: pymol_object (str): object to extract from. sequences (dict[str]): Wild-type sequence of design molecule and chain
Returns: Mutant : Mutant object.
REvoDesign.tools.mutant_tools.shorter_range(input_list, connector='-', seperator='+')
¶
Shorten a list of integers by representing consecutive ranges with hyphens, and non-consecutive integers with plus signs.
Parameters: input_list (list): A list of integers to be shortened. connector (str): A string for connecting consecutive ranges seperator (str): A string for separating non-consecutive ranges
Returns: str: A string expression representing the shortened integer list.
Example:
input_list = [395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409] result = shorter_range(input_list) print(result) "395-409"
input_list = [395, 396, 397, 398, 399, 400, 401, 403, 404, 405, 406, 407, 408, 409] result = shorter_range(input_list) print(result) "395-401+403-409"
REvoDesign.tools.mutant_tools.expand_range(shortened_str, connector='-', seperator='+')
¶
Expand a shortened string expression representing a list of integers to the original list.
Parameters: shortened_str (str): A shortened string expression representing a list of integers. connector (str): A string for connecting consecutive ranges seperator (str): A string for separating non-consecutive ranges
Returns: list: A list of integers corresponding to the original input.
Example:
shortened_str = "395-401+403-409" result = expand_range(shortened_str) print(result) [395, 396, 397, 398, 399, 400, 401, 403, 404, 405, 406, 407, 408, 409]
REvoDesign.tools.mutant_tools.read_customized_indice(custom_indices_from_input='')
¶
Reads and processes customized indices based on the provided input.
Args: - custom_indices_from_input (str): String containing customized indices.
Returns: - str: Processed customized indices string.
REvoDesign.tools.mutant_tools.existed_mutant_tree(sequences, enabled_only=1)
¶
Creates a tree structure of existing mutants based on PyMOL objects.
- sequences: dict[str,str] A dict of strings representing the designable sequences. eg. {'A': 'MANGHFDTYE', 'B': 'MCSAKLPIQWE'}
- MutantTree An instance of MutantTree class containing the mutant tree structure.
REvoDesign.tools.mutant_tools.quick_mutagenesis(mutant_tree)
¶
run quick mutagenesis on a given mutation tree. Everything else is read from local config bus.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mutant_tree
|
MutantTree
|
input mutant tree object. |
required |
REvoDesign.tools.mutant_tools.save_mutant_choices(output_mut_txt_fn, mutant_tree)
¶
REvoDesign.tools.mutant_tools.write_input_mutant_table(output_mut_txt_fn, mutant_list)
¶
REvoDesign.tools.mutant_tools.determine_profile_type(profile_fp)
¶
REvoDesign.tools.mutant_tools.get_mutant_table_columns(mutfile)
¶
REvoDesign.tools.mutant_tools.pick_design_from_profile(profile, profile_type, prefer_lower_score=False, keep_missing=True, residue_range='', view_highlight='orient', view_highlight_nbr=6)
¶
REvoDesign.tools.mutant_tools.process_mutations(data)
¶
Process mutations based on provided data.
- data (dict): Dictionary containing 'indices' and 'mutations' keys. 'indices': List of positions. 'mutations': Dictionary of mutations with positions as keys.
- list: List containing tuples of processed mutation data. Each tuple contains: - Position - Wild-type residue - Wild-type profile score - Candidates
PyMOL Utilities (REvoDesign.tools.pymol_utils)¶
Molecule-level utilities wrapping the PyMOL cmd API for session management, residue analysis, and structure manipulation.
Key Functions¶
REvoDesign.tools.pymol_utils.is_empty_session()
¶
REvoDesign.tools.pymol_utils.is_hidden_object(selection='(all)')
¶
REvoDesign.tools.pymol_utils.is_polymer_protein(sele='')
¶
Check if the selection represents a protein polymer with at least 10 residues.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sele
|
str
|
Selection string. Defaults to an empty string. |
''
|
Returns:
| Type | Description |
|---|---|
|
bool or None: Returns True if the selection represents a protein polymer with at least 10 residues, otherwise returns False. Returns None if the selection is empty. |
REvoDesign.tools.pymol_utils.find_small_molecules_in_protein(sele)
¶
Find small molecules within a protein selection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sele
|
str
|
Selection string. |
required |
Returns:
| Type | Description |
|---|---|
|
list or None: Returns a list of unique small molecule names found within the selection. Returns an empty list if no small molecules are found or if the selection is empty. Returns None if the selection is not provided. |
REvoDesign.tools.pymol_utils.find_design_molecules()
¶
Find design molecules that are polymer proteins.
Returns:
| Name | Type | Description |
|---|---|---|
list |
Returns a list of design molecules that are identified as polymer proteins. |
REvoDesign.tools.pymol_utils.find_all_protein_chain_ids_in_protein(sele)
¶
Function: find_all_protein_chain_ids_in_protein Usage: chain_ids = find_all_protein_chain_ids_in_protein(selection)
This function finds all chain IDs assigned to a protein molecule within the given selection.
Args: - sele (str): PyMOL selection string
- list: List of chain IDs assigned to a protein molecule within the selection. Returns None if the selection is empty or no protein chains are found.
REvoDesign.tools.pymol_utils.is_distal_residue_pair(molecule, chain_id, resi_1, resi_2, minimal_distance=20, use_sidechain_angle=False)
¶
Check if a pair of amino acid residues are distal based on certain conditions.
Parameters: - molecule (str): The name of the molecule. - chain_id (str): The chain identifier. - resi_1 (int): The residue number of the first amino acid. - resi_2 (int): The residue number of the second amino acid. - minimal_distance (float, optional): The minimum distance threshold for residues to be considered distal. Default is 20. - use_sidechain_angle (bool, optional): Whether to consider the orientation of side chains. Default is False.
Returns: - distal (bool): True if the residues are distal, False otherwise.
REvoDesign.tools.pymol_utils.renumber_chain_ids(target_protein)
¶
Function: renumber_chain_ids Usage: renumber_chain_ids(target_protein)
This function renumbers chain IDs of a given protein molecule using alphabets A-Z. It alters the chain IDs of the protein structure in PyMOL.
Args: - target_protein (str): PyMOL selection string of the target protein
Returns: - None
REvoDesign.tools.pymol_utils.get_molecule_sequence(molecule, chain_id, keep_missing=True)
¶
Function: get_molecule_sequence Usage: sequence = get_molecule_sequence(molecule, chain_id)
This function retrieves the amino acid sequence of a molecule (protein) specified by a given chain ID.
Args: - molecule (str): PyMOL selection string of the molecule - chain_id (str): Chain ID of the molecule - keep_missing (bool): Keep missing residues in structure as 'X'
Returns: - str: Amino acid sequence of the specified molecule and chain
REvoDesign.tools.pymol_utils.get_atom_pair_cst(selection='sele')
¶
Function: get_atom_pair_cst Usage: cst = get_atom_pair_cst(selection='sele')
This function generates a distance constraint (cst) in CHARMM format for a pair of atoms selected in PyMOL.
Args: - selection (str): PyMOL selection string for the atom pair (default is 'sele')
Returns: - str or None: Distance constraint in CHARMM format if exactly 2 atoms are selected; otherwise, returns None
REvoDesign.tools.pymol_utils.autogrid_flexible_residue(molecule, chain_id, selection)
¶
Function: autogrid_flexible_residue Usage: flex_residues = autogrid_flexible_residue(molecule, chain_id, selection)
This function generates a string specifying flexible residues for AutoGrid in AutoDock.
Args: - molecule (str): PyMOL selection string of the molecule - chain_id (str): Chain ID of the molecule - selection (str): PyMOL selection string for residue selection
- str or None: String specifying flexible residues for AutoGrid in AutoDock. Returns None if any of the input parameters (molecule, chain_id, selection) are invalid.
REvoDesign.tools.pymol_utils.refresh_all_selections()
¶
Function: refresh_all_selections Usage: selections = refresh_all_selections()
This function refreshes and logs information about all PyMOL selections except 'sele' and those starting with '_align'.
Returns: - list: List of all non-'sele' selections (excluding those starting with '_align')
REvoDesign.tools.pymol_utils.is_a_REvoDesign_session()
¶
Function: is_a_REvoDesign_session Usage: result = is_a_REvoDesign_session()
This function checks if it's a REvoDesign session by verifying the existence of public group objects.
- bool: True if it's a REvoDesign session (public group objects exist), False otherwise.
REvoDesign.tools.pymol_utils.make_temperal_input_pdb(molecule, chain_id='', segment_id='', resn='', selection='', save_as_format='pdb', wd=os.getcwd(), reload=True)
¶
Function: make_temperal_input_pdb
Usage: input_file = make_temperal_input_pdb(molecule, chain_id=None, segment_id=None, format='pdb', wd=os.getcwd(), reload=True)
exi This function generates a temporary input PDB file from the specified molecule selection. It supports selection by chain ID, segment ID, or both.
Args:
- molecule (str): PyMOL selection string of the molecule
- chain_id (str): Chain id of the molecule (default is None)
- segment_id (str): Segment id of the molecule (default is None)
- resn (str): Residue name of the molecule (useful for small-molecule ligand)
- selection (str): Customized selection in PyMOL syntax.
- format (str): File format for the generated PDB file (default is 'pdb')
- wd (str): Working directory path where the file will be saved (default is current working directory)
- reload (bool): Whether to reload the PyMOL session after generating the file (default is True)
Returns:
- str: Path to the generated temporary input PDB file
REvoDesign.tools.pymol_utils.extract_smiles_from_chain(molecule, chain_id='', segment_id='', resn='', selection='')
¶
REvoDesign.tools.pymol_utils.renumber_protein_chain(molecule, chain=None, offset=0)
¶
Renumbers a protein chain in PyMOL by applying an offset to residue indices.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
molecule
|
str | List[str]
|
Name of the PyMOL molecule object. |
required |
chain
|
Optional[str]
|
Name of the chain to be renumbered. If None, applies to all chains. |
None
|
offset
|
int
|
Residue index offset to apply (default is 0, meaning no change). |
0
|
REvoDesign.tools.pymol_utils.get_pymol_settings(keyword, obj='')
¶
REvoDesign.tools.pymol_utils.list_palettes()
¶
REvoDesign.tools.pymol_utils.exists(name)
¶
REvoDesign.tools.pymol_utils.load_safely(file, name)
¶
Data Classes¶
REvoDesign.tools.pymol_utils.PyMOLSetting
dataclass
¶
Measurement Utilities (REvoDesign.tools.measure_utils)¶
Reads PyMOL measurement objects (distance, angle, dihedral) from the session and produces Gromacs index input strings. Handles PyMOL's internal ObjectDist/DistSet data structures.
Classes¶
REvoDesign.tools.measure_utils.MeasureType
¶
Bases: IntEnum
Measurement types corresponding to C++ cRepDash / cRepAngle / cRepDihedral.
from_atom_count(n)
classmethod
¶
Infer measurement type from the number of atom ids.
This mirrors the C++ logic in MeasureInfoListFromPyList::
item->measureType = (N == 2) ? cRepDash :
(N == 3) ? cRepAngle : cRepDihedral;
REvoDesign.tools.measure_utils.AtomDescriptor
dataclass
¶
Lightweight descriptor for a single atom in the PyMOL scene.
REvoDesign.tools.measure_utils.MeasureInfo
dataclass
¶
A single measurement entry inside a DistSet.
Mirrors the C++ CMeasureInfo struct (layer2/DistSet.h)::
struct CMeasureInfo {
int id[4]; // AtomInfoType.unique_id
int offset; // offset into this distance set's Coord list
int state[4]; // save object state
int measureType; // distance, angle, or dihedral
};
During PyMOL session serialization measureType is not stored
explicitly — it is reconstructed from len(ids) on load. We store it
explicitly on the Python side for clarity.
from_pylist(item)
classmethod
¶
Deserialize a Python list produced by MeasureInfoListAsPyList.
The PyList format is::
[offset, [id0, ...], [state0, ...]]
where the length of the ids list implies the measurement type (2 = distance, 3 = angle, 4 = dihedral).
See layer2/DistSet.cpp:MeasureInfoListAsPyList.
REvoDesign.tools.measure_utils.DistSet
dataclass
¶
One state / frame of measurement coordinates.
Despite its name, DistSet holds distances, angles, AND dihedrals
(the C++ code itself carries the comment: "NOTE: 'Dist' names & symbols
should be updated to 'Measurement'").
Serialized as a 10-element Python list by DistSetAsPyList::
[0] NIndex — number of distance vertices (2× num distances)
[1] Coord — flattened xyz coords for distance atoms
[2] LabCoord — label coords (None; recalculated on load)
[3] NAngleIndex — number of angle vertices (3× num angles)
[4] AngleCoord — flattened xyz coords for angle atoms
[5] NDihedralIndex — number of dihedral vertices (4× num dihedrals)
[6] DihedralCoord — flattened xyz coords for dihedral atoms
[7] Setting — always None (removed before BB 11/14)
[8] LabPos — label positions (list or None)
[9] MeasureInfo — list of ``[offset, [ids], [states]]`` sub-lists
See layer2/DistSet.cpp:DistSetAsPyList and DistSetFromPyList.
from_pylist(py)
classmethod
¶
Deserialize from the 10-element Python list format.
get_vertex_coords_for_measure(mi)
¶
Return (x, y, z) triples for each atom in mi.
Uses the correct coordinate array (distance / angle / dihedral)
based on mi.measure_type. The offset is in units of
vertices (not floats); each vertex is 3 consecutive floats.
REvoDesign.tools.measure_utils.Measurement
dataclass
¶
A PyMOL measurement object (distance, angle, dihedral, or mixed).
Parsed from a cmd.get_session()['names'] entry whose obj_type == 4
(cObjectMeasurement). Can contain multiple DistSet\ s (one per
state / frame).
measurement_type
property
¶
Return the measurement type if all MeasureInfo entries agree.
Returns None for mixed-type measurement objects or empty ones.
is_mixed
property
¶
True when the object contains more than one measurement type.
num_measurements
property
¶
Total number of MeasureInfo entries across all DistSet\ s.
get_value(mi, ds)
¶
Compute the measurement value for a single MeasureInfo.
- distance: Euclidean distance between the 2 atoms (Å).
- angle: bond angle defined by 3 atoms (degrees).
- dihedral: dihedral (torsion) angle defined by 4 atoms (degrees).
atoms(cmd_module=None, coord_tol=0.9)
¶
Resolve measurement atoms to AtomDescriptor objects.
Resolution strategy (in order of preference):
1. Direct unique_id lookup (fast and unambiguous).
2. Coordinate-based nearest-neighbor search within coord_tol (Å).
Results are cached and only recomputed when the scene fingerprint or coord_tol changes.
Parameters¶
cmd_module:
The pymol.cmd module (defaults to pymol.cmd).
coord_tol:
Coordinate tolerance in Å for nearest-neighbor matching.
atoms_for_entry(mi, ds, cmd_module=None, coord_tol=0.9)
¶
Resolve atoms for a single MeasureInfo + DistSet pair.
Unlike atoms(), this does not de-duplicate across entries and
preserves per-entry ordering. The result is NOT cached.
from_names_entry(entry)
classmethod
¶
Parse a single entry from cmd.get_session()['names'].
The entry format (from ExecutiveGetExecObjectAsPyList)::
[name, cExecObject(=1), visible, None, objType, objectPyList, groupName]
For measurement objects objType == cObjectMeasurement == 4 and
objectPyList is the ObjectDistAsPyList result (4 elements)::
[ObjectHeader, DSetCount, [DistSetPyList, ...], 0]
from_session_names(names)
classmethod
¶
Parse all measurement objects from a get_session()['names'] list.
summarize(cmd_module=None)
¶
Human-readable summary of the measurement object.
Functions¶
REvoDesign.tools.measure_utils.build_scene_atom_list(cmd_module)
¶
Return AtomDescriptor for every atom in the session (all objects).
REvoDesign.tools.measure_utils.build_unique_id_map(cmd_module)
¶
Build {unique_id: AtomDescriptor} for all atoms that have a unique_id.
REvoDesign.tools.measure_utils.read_measurement(start=0, debug=0)
¶
Read measurement objects from the PyMOL session and print Gromacs index strings.
For each measurement atom, this prints a Gromacs make_ndx-style
selection and name command, following the convention:
4 & r <resi>for glycine backbone atoms8 & r <resi>for non-glycine sidechain atoms
Works with distance (2 atoms), angle (3 atoms), and dihedral (4 atoms) measurements.
Parameters¶
start : str or int Starting index for Gromacs group numbering. debug : int If non-zero, print debug summaries for each measurement.
Returns¶
list[Measurement] All parsed measurement objects.
Download Registry (REvoDesign.tools.download_registry)¶
Manages automatic downloading, verification, and caching of remote file resources using the Pooch library. Supports retry mechanisms, alternative URLs, and hash-based verification.
REvoDesign.tools.download_registry.FileDownloadRegistry
¶
Bases: CitableModuleAbstract
A file download registry manager for handling remote file resources.
This class implements automatic file downloading, verification, and cache management based on the pooch library. It supports specifying file hash values through a registry and provides convenient methods to fetch and verify remote files.
:param name: Module name, used to construct the default data directory path. :param base_url: Base URL for remote files. :param registry: File registry where keys are filenames and values are corresponding hash values (optional). :param version: Optional version number for creating versioned data directories. :param customized_directory: Optional custom download directory path. If not provided, uses the default user data directory. :param alternative_base_urls: Optional list of alternative base URLs for downloading files. :param retry_count: Number of retries for downloading files.
Retry mechanism
The function will run a nested loop to retry downloading files. It firstly tries to download files from the primary base URL. If the download fails, it will retry with the alternative base URLs if provided. For each base url, a certain number of retries will be attempted.
list_all_files
property
¶
Get a list of all files in the registry.
:return: List of filenames.
preprocess_registry(registry)
staticmethod
¶
Preprocess registry to ensure all hash values conform to pooch requirements.
:param registry: Original registry. :return: Processed registry.
setup(item)
¶
Download and return the local path and related information of the specified file.
:param item: Filename to download. :return: DownloadedFile object containing file information. :raises NetworkError: Raises network error exception if download fails.
has(item)
¶
Check if the specified file exists in the registry.
:param item: Filename. :return: True if exists, False otherwise.
prepare_registry_from_md5(md5_contents)
staticmethod
¶
Parse and generate registry from MD5 content string.
:param md5_contents: String containing MD5 values and filenames, each line in 'hash filename' format. :return: Parsed registry dictionary.
REvoDesign.tools.download_registry.DownloadedFile
dataclass
¶
Represents a downloaded file with its metadata
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Name of the file |
version |
Optional[str]
|
Version of the file, can be None |
url |
str
|
Download URL of the file |
downloaded |
str
|
Local path where the file is downloaded |
registry |
Optional[str]
|
Registry information, defaults to None |
flatten_dir
property
¶
Get or create the flatten directory path
Creates directory if it doesn't exist, with name based on downloaded path plus '_flatten' suffix
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
Path to the flatten directory |
flatten_archive
property
¶
Extract archive file to flatten directory
If flatten directory is empty, extracts the downloaded archive file to that directory and returns the list of extracted files
Returns:
| Type | Description |
|---|---|
|
List[str]: List of extracted file names |
Rosetta Utilities (REvoDesign.tools.rosetta_utils)¶
Environment detection and configuration helpers for integrating with the Rosetta molecular modeling suite.
Key Functions¶
REvoDesign.tools.rosetta_utils.setup_minimal_rosetta_db(subdirectory_to_clone)
¶
Sets up the minimal Rosetta database required by cloning a specific subdirectory from the Rosetta repository.
Args: subdirectory_to_clone (str): The subdirectory in the Rosetta database to clone.
Returns: str: The path to the Rosetta database after cloning.
REvoDesign.tools.rosetta_utils.list_fastrelax_scripts()
¶
Lists the fast relax scripts in the Rosetta database.
Returns: List[str]: A list of names of the fast relax scripts.
REvoDesign.tools.rosetta_utils.extra_res_to_opts(ligands_params)
¶
Generates options for ligand parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ligands_params
|
Union[List[str], str]
|
List of ligand parameters or a single parameter. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: List of command-line options for ligand parameters. |
REvoDesign.tools.rosetta_utils.is_run_node_available(node_hint)
¶
Determine if the specified runtime environment indicated by node_hint is available.
Parameters: - node_hint (Optional[NodeHintT]): A hint that specifies the desired runtime environment.
Returns: - bool: True if the specified runtime environment is available, False otherwise.
REvoDesign.tools.rosetta_utils.is_docker_available()
¶
Checks if Docker is available on the current machine.
This function attempts to connect to Docker using the Docker client from the environment. If the connection is successful, it indicates that Docker is available, and the function returns True. If a DockerException is raised during the connection attempt, it indicates that Docker is not available, and a warning is issued before returning False.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if Docker is available, otherwise False. |
REvoDesign.tools.rosetta_utils.is_wsl_available()
¶
Check if Windows Subsystem for Linux (WSL) is available on the current machine.
This function attempts to determine if WSL is available by trying to locate the WSL binary. If the WSL binary is found, it indicates that WSL is available.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
Returns True if WSL is available, otherwise returns False. |
REvoDesign.tools.rosetta_utils.is_rosetta_runnable()
¶
Check if there are available run nodes to execute Rosetta tasks
This function iterates through all nodes and checks if at least one run node is available. It verifies the availability of each node by calling the is_run_node_available function.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
True if at least one run node is available, False otherwise |
REvoDesign.tools.rosetta_utils.read_rosetta_config(key_path='rosetta.opts.general')
¶
Read Rosetta configuration options and parse them into a list of strings
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key_path
|
str
|
Path to the configuration key, defaults to "rosetta.opts.general" |
'rosetta.opts.general'
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List[str]: Parsed Rosetta configuration options as a list of strings |
REvoDesign.tools.rosetta_utils.read_rosetta_node_config()
¶
Read the Rosetta node configuration from the configuration bus.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict[str, str]: Dictionary containing the Rosetta node configuration. If no node config is found, it returns an empty dictionary. |
REvoDesign.tools.rosetta_utils.copy_rosetta_citation(citetation)
¶
Copy Rosetta citation information and update with custom citation content
This function creates a copy of the Rosetta common citation information and updates it with the provided custom citation information. It is mainly used to generate complete citation information by combining common and specific parts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
citetation
|
dict[str, Union[str, tuple]]
|
Custom citation information dictionary used to update the common citation information |
required |
Returns:
| Type | Description |
|---|---|
dict[str, str | tuple]
|
dict[str, Union[str, tuple]]: Updated complete citation information dictionary |
System Tools (REvoDesign.tools.system_tools)¶
System information collection and environment detection.
REvoDesign.tools.system_tools.check_mac_rosetta2()
¶
Check if the current environment is running on an Apple Silicon Mac with Rosetta 2.
This function first checks if the current operating system is macOS. If not, it returns immediately. It then determines if the machine is an ARM-based Mac and whether it is recognized as an x86_64 architecture. If both conditions are met, a warning is issued indicating that the environment is using Rosetta 2, which may impact performance.
Returns:
| Type | Description |
|---|---|
|
None |
REvoDesign.tools.system_tools.SystemInfoReduced
¶
REvoDesign.tools.system_tools.get_client_info()
¶
CGO Utilities (REvoDesign.tools.cgo_utils)¶
Compiled Graphics Objects (CGO) helpers for programmatic PyMOL rendering. Provides a geometric primitive library — points, spheres, cylinders, cones, arrows, curves (Bezier, Catmull-Rom, B-Spline, Hermite, NURBS), tori, polyhedra, text boards — built on pymol.cgo.
Key Classes¶
REvoDesign.tools.cgo_utils.Point
dataclass
¶
A Point vector object in PyMOL's coordinate system This class represents a point in 3D space with coordinates (x, y, z). It provides methods to convert the point to a numpy array, and to generate CGO commands for vertices and normals.
copy
property
¶
Return a copy of the point.
array
cached
property
¶
Convert the point to a numpy array This method converts the point's coordinates into a numpy array, facilitating subsequent vector operations.
as_vertex
cached
property
¶
Generate a CGO vertex command for the point This method inserts the point's coordinates into a CGO vertex command, used for rendering in PyMOL.
as_normal
cached
property
¶
Generate a CGO normal command for the point This method inserts the point's coordinates into a CGO normal command, used for specifying normals in PyMOL.
move(x=None, y=None, z=None)
¶
Move the point This method allows the point to be moved along the x, y, and z axes. If a coordinate is not provided, the original value is used.
Parameters: - x: Optional[float] = None, the new x-coordinate, if not provided, the original x-coordinate is used - y: Optional[float] = None, the new y-coordinate, if not provided, the original y-coordinate is used - z: Optional[float] = None, the new z-coordinate, if not provided, the original z-coordinate is used
Returns: - Point: The new point after moving
as_arrays(points)
staticmethod
¶
Convert a collection of points to a numpy array This static method converts a collection of Point objects into a single numpy array, facilitating batch processing.
Parameters: - points: Iterable['Point'], a collection of Point objects
Returns: - np.ndarray: A numpy array containing the coordinates of all points
as_vertexes(points)
staticmethod
¶
Convert a collection of points to CGO vertex commands This static method converts a collection of Point objects into CGO vertex commands, used for batch rendering in PyMOL.
Parameters: - points: Iterable['Point'], a collection of Point objects
Returns: - np.ndarray: A numpy array containing the CGO vertex commands for all points
distance_to(point)
¶
Euclidean distance from a point to this Point.
Parameters: - point: Point, a target point object.
Returns: - float: The Euclidean distance
from_array(array)
classmethod
¶
Create a Point object from a NumPy array.
from_atom(atom)
classmethod
¶
Create a Point object from a PyMOL atom.
from_com(selection='(all)')
classmethod
¶
Calculate the center of mass of a selection.
Parameters: - selection: str, a PyMOL selection string.
Returns: - Point: The center of mass as a Point object.
REvoDesign.tools.cgo_utils.Color
dataclass
¶
Represents a color, including its name and alpha value.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The name of the color. |
alpha |
float
|
The alpha value of the color, default is 1.0 for full opacity. |
array
cached
property
¶
Converts the color to an RGB array.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: An RGB array representing the color. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the color name is not valid. |
array_alpha
cached
property
¶
Adds the alpha value to the RGB array to create an RGBA array.
Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray: An RGBA array representing the color. |
as_cgo
cached
property
¶
Converts the color to a CGO (Color Graphics Operations) representation.
Returns:
| Type | Description |
|---|---|
|
np.ndarray: The CGO representation of the color. |
as_arrays(colors)
staticmethod
¶
Converts a series of colors to an array of RGB arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colors
|
Iterable[Color]
|
A series of Color objects. |
required |
Returns:
| Type | Description |
|---|---|
|
np.ndarray: An array consisting of the RGB arrays of all colors. |
as_cgos(colors)
staticmethod
¶
Converts a series of colors to an array suitable for CGO (Color Graphics Operations).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
colors
|
Iterable[Color]
|
A series of Color objects. |
required |
Returns:
| Type | Description |
|---|---|
|
np.ndarray: An array consisting of the CGO representations of all colors. |
REvoDesign.tools.cgo_utils.GraphicObject
dataclass
¶
A base class representing a graphic object, providing methods to rebuild and load graphic data.
data
property
¶
Get the CGO data.
rebuild()
¶
Rebuild the CGO data.
load_as(name, *args, **kwargs)
¶
Load the graphic object as a specified name. If the name is occupied, delete it to regenerate.
Parameters: name (str): The name of the object, used for loading the object data into the software.
If an object with the same name already exists, it is deleted before loading the new object. This prevents loading errors due to duplicate names.
REvoDesign.tools.cgo_utils.Sphere
dataclass
¶
Bases: GraphicObject
Represents a sphere in 3D space, inheriting from GraphicObject.
Attributes:
| Name | Type | Description |
|---|---|---|
center |
Point
|
The center point of the sphere, default is the origin (0, 0, 0). |
radius |
float
|
The radius of the sphere, default is 0.0. |
color |
str
|
The color of the sphere, default is 'w' (white). |
rebuild()
¶
Rebuilds the sphere's data representation using CGO (Chimera Graphics Object) format.
This method constructs the sphere's data by combining the color information and the sphere's geometric properties.
REvoDesign.tools.cgo_utils.Cylinder
dataclass
¶
Bases: GraphicObject
Represents a cylindrical graphic object.
Attributes: - point1 (Point): The first endpoint of the cylinder, defaulting to Point(0, 0, 0). - point2 (Point): The second endpoint of the cylinder, defaulting to Point(1, 1, 1). - radius (float): The radius of the cylinder, defaulting to 1.0. - color1 (str): The color of the first end of the cylinder, defaulting to 'violet'. - color2 (str): The color of the second end of the cylinder, defaulting to 'cyan'.
rebuild()
¶
Rebuilds the cylinder's data representation.
This method constructs the data array for the cylinder using the specified attributes.
REvoDesign.tools.cgo_utils.Cone
dataclass
¶
Bases: GraphicObject
Represents a cone graphic object.
Attributes:
| Name | Type | Description |
|---|---|---|
tip |
Point
|
The position of the cone's tip. |
base_center |
Point
|
The position of the cone's base center. |
radius_tip |
float
|
The radius of the cone at the tip. |
radius_base |
float
|
The radius of the cone at the base. |
color_tip |
str
|
The color of the cone's tip. Default is 'w' for white. |
color_base |
str
|
The color of the cone's base. Default is 'g' for green. |
caps |
tuple[float, float]
|
A tuple indicating whether to add caps to the tip and/or base. 1 for True, 0 for False. Default is (1, 0), meaning the tip has a cap and the base does not. |
rebuild()
¶
Rebuilds cone
This method rebuilds the cone based on its attributes, including position, size, color, and whether to add caps.
REvoDesign.tools.cgo_utils.Arrow
dataclass
¶
Bases: GraphicObject
Represents an arrow object for visualization in PyMOL, with properties for start and end points, line width, and color.
REvoDesign.tools.cgo_utils.TextBoard
dataclass
¶
Bases: GraphicObject
Additional primitive classes: LineVertex, Sausage, Doughnut, Triangle, TriangleSimple, Cube, Square, PolyLines, RoundedRectangle, Ellipse, Ellipsoid, Polygon, Polyhedron.
Curve classes: PseudoCurve, PseudoBezier, PseudoCatmullRom, PseudoBSpline, PseudoHermite, PseudoArc, PseudoNURBS.
Custom Widgets (REvoDesign.tools.customized_widgets)¶
Custom Qt widgets and dialogs used throughout the REvoDesign UI.
Key Classes¶
REvoDesign.tools.customized_widgets.REvoDesignWidget
¶
Bases: QWidget
REvoDesign Widget Window Class
This Widget class represents a custom widget in the REvoDesign application. It inherits from QtWidgets.QWidget, manages its lifecycle by attaching and detaching from a central UI bus, and ensures no duplicate windows are opened unless explicitly allowed.
closeEvent(a0)
¶
Handles the close event triggered when the user closes the window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
a0
|
QCloseEvent
|
The close event object. |
required |
show()
¶
Shows the widget and attaches it to the UI bus.
check_repeat()
¶
Checks if a window with the same name is already open. If found, raises it to the front and raises a RuntimeError.
attach()
¶
Attaches the widget to the UI bus by adding it to the list of open windows.
detach()
¶
Detaches the widget from the UI bus by removing it from the list of open windows.
freeze_to_wait()
¶
Freezes the dialog while the plugin is running.
REvoDesign.tools.customized_widgets.ImageWidget
¶
Bases: QWidget
REvoDesign.tools.customized_widgets.QButtonMatrix
¶
Bases: QWidget
Custom painted matrix widget replacing per-cell QPushButton grids.
Paints a square heatmap matrix with QPainter. Handles hover, click, and crosshair highlighting via mouse events. This avoids native QPushButton size hints that differ between Qt5 and Qt6 and deform the matrix into vertical strips.
Public API is compatible with the previous button-grid implementation:
init_ui(), active_func, report_axes_signal, shape,
alphabet_row, alphabet_col, df_matrix, min_value,
max_value, on_hover, on_leave, signal_process,
_map_value_to_color, and the cellSelected convenience signal.
on_hover(row, col)
¶
Programmatic hover entry point (kept for backward compat).
on_leave()
¶
Programmatic hover-clear entry point (kept for backward compat).
is_wt_button(row_name, col_name, row, col)
¶
Return True if the cell represents a wild-type pair.
signal_process(row, col)
¶
Handle a cell selection — update state, animate, run task.
init_ui()
¶
Build tooltip cache and initialise geometry.
Callers may override alphabet_row / alphabet_col before
calling this method (the old behaviour is preserved).
set_review_annotation(idx, accepted)
¶
Store a persistent review annotation for a cell.
begin_busy(idx)
¶
Start breathing animation on a cell (e.g. during async task).
end_busy()
¶
Stop breathing animation and clear busy state.
pulse_cell(idx, duration_ms=500)
¶
Show a short click-feedback pulse, stops automatically.
REvoDesign.tools.customized_widgets.QButtonMatrixGremlin
¶
Bases: QButtonMatrix
A specialized variant of QButtonMatrix for Gremlin.
Attributes:
| Name | Type | Description |
|---|---|---|
pair_i |
int
|
Index of the first pair. |
pair_j |
int
|
Index of the second pair. |
Methods:
| Name | Description |
|---|---|
is_wt_button |
Redefines wild type button criteria for Gremlin. |
_make_button_tip |
Custom tooltip generation for Gremlin. |
is_wt_button(row_name, col_name, row, col)
¶
Determines if a button corresponds to a wild type (WT) pair for Gremlin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row_name
|
str
|
Name of the row. |
required |
col_name
|
str
|
Name of the column. |
required |
row
|
int
|
Row index. |
required |
col
|
int
|
Column index. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if the button represents a WT pair, False otherwise. |
REvoDesign.tools.customized_widgets.QHoverCross
¶
Bases: QWidget
Floating hover cross widget that visually appears over the buttons as empty rectangular boxes.
update_position(button_rect)
¶
Updates the hover rectangles' position based on the hovered button.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
button_rect
|
QRect
|
Geometry of the hovered button. |
required |
hide_hover()
¶
Hides the hover rectangles.
paintEvent(event)
¶
Paints empty rectangular boxes as hover indicators for row and column.
Rectangles
- Horizontal rectangle: spans horizontally across the widget.
- Vertical rectangle: spans vertically across the widget.
REvoDesign.tools.customized_widgets.ButtonCoords
dataclass
¶
Immutable data class representing the coordinates and names of a button.
Attributes:
| Name | Type | Description |
|---|---|---|
row |
int
|
The row index of the button. |
row_name |
str
|
The name of the row. |
col |
int
|
The column index of the button. |
col_name |
str
|
The name of the column. |
REvoDesign.tools.customized_widgets.QButtonBrick
¶
Bases: QPushButton
Custom QPushButton subclass representing a button in a matrix.
Attributes:
| Name | Type | Description |
|---|---|---|
coords |
ButtonCoords
|
Coordinates and names associated with the button. |
color |
QColor
|
The background color of the button. |
is_wt |
bool
|
Flag indicating if the button represents a wild type (WT) pair. |
Methods:
| Name | Description |
|---|---|
button_name |
Constructs the unique object name for the button. |
style_sheet |
Generates the CSS styling for the button. |
button_name
property
¶
Constructs the unique object name for the button based on its coordinates.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The unique name of the button. |
style_sheet
property
¶
Generates the CSS style for the button, including background color and text color.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The CSS style for the button. |
enterEvent(event)
¶
Trigger when mouse enters the button.
leaveEvent(event)
¶
Trigger when mouse leaves the button.
REvoDesign.tools.customized_widgets.MultiCheckableComboBox
¶
Bases: QComboBox
select_all()
¶
Check all items.
unselect_all()
¶
Uncheck all items.
invert_selection()
¶
Reverse the selection of all items.
get_checked_items()
¶
Retrieve all checked items.
set_checked_items(items)
¶
Set initial checked items.
hidePopup()
¶
Override to update selected items on close.
currentText()
¶
Override to show a comma-separated list of selected items.
REvoDesign.tools.customized_widgets.ValueDialog
¶
Bases: REvoDesignWidget
submit_complete_form()
¶
Handles the OK button click. Collects user inputs and validates required fields.
REvoDesign.tools.customized_widgets.ParallelExecutor
¶
REvoDesign.tools.customized_widgets.QtParallelExecutor
¶
Bases: QThread
USAGE
1. set a bouncing progressbar¶
progress_bar.setRange(0, 0)
2. instantialize a parallel executor that is bound with target function, task option list, and the most¶
importantly, number of processors you would use with.¶
self.parallel_executor = ParallelExecutor(self.process_position, mutagenesis_tasks, n_jobs=nproc)
3. create a single for the progressbar (is it broken?)¶
self.parallel_executor.progress_signal.connect(progress_bar.setValue)
4. start the new thread¶
self.parallel_executor.start()
4. wait for its end and refresh the window, then take a short sleep so that the window UI can still be¶
active¶
while not self.parallel_executor.isFinished(): #logging.info(f'Running ....') refresh_window() time.sleep(0.001)
5. after it is done, reset the progress bar to the job done state¶
progress_bar.setRange(0, len(mutagenesis_tasks)) progress_bar.setValue(len(mutagenesis_tasks))
6. recieve the results¶
self.results=self.parallel_executor.handle_result()
7. continue the following code¶
self.merging_sessions()
REvoDesign.tools.customized_widgets.AskedValue
dataclass
¶
Represents a single input field in the ValueDialog.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
The unique identifier or label for the input field. |
val |
Optional[Any]
|
The default or current value of the field. |
typing |
type
|
The expected data type for the field's value. Specifies available typing for the field. Used as item typing if the val is iterable container like list or tuple |
reason |
Optional[str]
|
Additional description or reason for the field. |
required |
bool
|
Indicates whether the field is mandatory. |
choices |
Optional[Union[Iterable, Callable[[], Iterable]]]
|
Specifies available iterable choices for the field. Can be: - Iterable: - List[Any]: A list of options used as single choice. - Tuple[Any]: A tuple of options used as single choice. - range: A range of values useed as integer options. - filter: A filter of values used as string options. - KeysView: A view of keys used as string options. - ValuesView: A view of values used as string options. - Callable[[], Iterable]: A function to dynamically generate those iterable options. |
source |
Literal['None', 'File', 'Directory', 'JsonInput']
|
Specifies the source of the input field. Can be: - 'None': No specific source. - 'File': Input is expected to be a file path. - 'Files': Input is expected to be a list of file paths, which will be converted as a string of '|' separated file paths. - 'Directory': Input is expected to be a directory path. - 'JsonInput': Input is expected to be a JSON file input. |
ext |
Optional[FileExtensionCollection]
|
File extension filters for file and directory inputs. |
multiple_choices |
bool
|
Whether the multiple choices mode is enabled. |
REvoDesign.tools.customized_widgets.AskedValueCollection
dataclass
¶
Represents a collection of AskedValue objects, along with a banner message.
Attributes:
| Name | Type | Description |
|---|---|---|
asked_values |
List[AskedValue]
|
List of input fields for the dialog. |
banner |
Optional[str]
|
A message to be displayed at the top of the dialog. |
typing_fixed
property
¶
Returns a new object with the asked_values field where each element's val attribute has been type-converted.
This method creates a deep copy of the current object to avoid modifying the original data.
It then iterates over the asked_values list and applies the typing function to each val attribute.
If the typing attribute is bool, a special real_bool function is used for conversion.
Returns:
| Name | Type | Description |
|---|---|---|
AskedValueCollection |
AskedValueCollection
|
A new object with the type-converted |
asdict
property
¶
Converts the collection into a dictionary where the keys are the field labels and the values are their corresponding inputs.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict[str, Any]: A dictionary representation of the collection. |
REvoDesign.tools.customized_widgets.dialog_wrapper(title, banner, allow_real_time_update, options)
¶
A decorator to wrap a function and generate a dialog for user input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title
|
str
|
The title of the dialog. |
required |
banner
|
str
|
A banner message to display at the top of the dialog. |
required |
options
|
Tuple[AskedValue, ...]
|
The static list of AskedValue objects to include in the dialog. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable
|
The wrapped function that collects input from a dialog before execution. |
REvoDesign.tools.customized_widgets.widget_signal_tape(widget, event, disconnect=False)
¶
Connects the appropriate signal of a QWidget to the specified event handler.
This function connects specific signals from different types of QWidgets to a unified event handler. It handles several common Qt widget types such as QDoubleSpinBox, QSpinBox, QProgressBar, QComboBox, QLineEdit, and QCheckBox, binding their respective signals to the provided event handler.
Parameters: - widget (QtWidgets.QWidget): The widget instance whose signal will be connected. - event (callable): The event handler function that will be called when the widget's signal is emitted.
Raises: - NotImplementedError: If the widget type is not supported by this function.
REvoDesign.tools.customized_widgets.create_cmap_icon(cmap)
¶
Creates a square pixmap representing the color pattern of a specified colormap.
Args: - cmap (str): Name of the colormap.
Returns: - QtGui.QPixmap: Pixmap representing the color gradient of the colormap.
Note: This function uses Matplotlib's colormap to generate a color gradient and creates a square pixmap with the color gradient to represent the colormap visually.
Example Usage:
from REvoDesign.Qt import QtWidgets
import matplotlib.pyplot as plt
# Assuming 'my_colormap' is a valid colormap name
icon = create_cmap_icon('my_colormap')
label = QtWidgets.QLabel()
label.setPixmap(icon)
label.show()
plt.show()
REvoDesign.tools.customized_widgets.pick_color(parent, init_color='', disable_native_picker=False, alpha=False)
¶
Package Manager (REvoDesign.tools.package_manager)¶
Thread management, process tracking, and background task execution infrastructure. See README.thread-management.md for the full design document.
Key Classes¶
REvoDesign.tools.package_manager.WorkerThread
¶
Bases: QThread
Custom worker thread for executing a function in a separate thread.
REvoDesign.tools.package_manager.ThreadExecutionManager
¶
Bases: QObject
Binds worker threads with UI affordances (abort button, progress, dashboard).
REvoDesign.tools.package_manager.ThreadPoolRegistry
¶
Global registry tracking running worker threads.
REvoDesign.tools.package_manager.RunningProcessRegistry
¶
Tracks subprocesses spawned within worker threads to allow cancellation.
REvoDesign.tools.package_manager.ThreadDashboard
¶
Bases: QDialog
Simple dashboard that visualises worker threads.
REvoDesign.tools.package_manager.AbortButtonOverlay
¶
Bases: QObject
Overlay that reveals a red abort button on hover.
REvoDesign.tools.package_manager.REvoDesignPackageManager
dataclass
¶
Class to manage the installation of the REvoDesign plugin. This class firstly performs a self-bootstrap including the following: 1. fetch UI file and load it 2. fetch extras table 3. fetch repo release tags if possible 4. add menu items Then it register widget signals and get all things ready.
Attributes:
| Name | Type | Description |
|---|---|---|
dialog |
QWidget
|
The main dialog window for the plugin GUI. |
extra_checkbox |
CheckableListView
|
A checkbox list for selecting extra components. |
upgrade_check(original_file, new_file, title)
staticmethod
¶
Check and apply an upgrade if necessary.
This function compares the original file with a new fetched file, generates a diff file if there are differences, and prompts the user to confirm whether to apply the upgrade. If the user confirms, the new file replaces the original file.
Parameters: - original_file (str): The path to the original file. - new_file (str): The path to the new fetched file. - title (str): The title used in notifications.
Returns: - None
freeze_manager()
¶
Freezes the dialog while the plugin is running.
run_plugin_gui()
¶
Runs the plugin GUI.
This method initializes and displays the plugin's graphical user interface. It also sets up the extra components checkbox list and connects the radio button signals to the appropriate methods for checking or unchecking all items.
Steps: - Initialize the dialog window if it hasn't been created yet. - Display the dialog window. - Create and position the extra components checkbox list. - Connect the 'None' radio button to uncheck all items in the checkbox list. - Connect the 'Everything' radio button to check all items in the checkbox list. - Run a worker thread to fetch tags with a progress bar.
proxy_in_env(proxy=None, mirror=None)
¶
Generates an environment mapping based on the provided proxy string.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
proxy
|
str
|
The proxy string to use for creating the environment variables. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, str]
|
Dict[str, str]: A dictionary containing the proxy settings for environment variables.
If |
refresh_remote_json()
¶
Refreshes the list of available extras by fetching data from a JSON source.
This method uses a worker thread to fetch extras data with a progress bar indication. If fetching fails, it shows an error notification and sets up an empty extras list.
notification_channel(d)
staticmethod
¶
Process notification messages and send them to the notification box
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d
|
dict
|
A dictionary containing notification information, should include 'notification' key |
required |
Returns:
| Type | Description |
|---|---|
|
None |
collect_diagnostic_data(collect_dummy=False, drop_sensitives=True)
staticmethod
¶
Collects diagnostic data and copies it to the clipboard.
This function clears the clipboard, collects diagnostic data by starting a worker thread, and then copies the collected data in JSON format to the clipboard. It finally notifies the user to paste the diagnostic information when creating a new issue on GitHub.
Parameters: collect_dummy (bool): A flag indicating whether to collect dummy data. Default is False. drop_sensitives (bool): A flag indicating whether to drop sensitive data. Default is True.
Returns: None
add_right_click_menu(items)
¶
Adds a right-click context menu to the installer UI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
List[MenuItem]
|
A list of menu items to be added to the right-click menu. |
required |
This method creates a right-click menu with actions defined by the items parameter.
Each item in the list is converted into a QAction, which is then added to the menu.
show_menu(pos)
¶
Shows the context menu at the position of the mouse cursor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pos
|
QPoint
|
The position where the menu should be shown, in widget coordinates. |
required |
make_window()
¶
Creates and configures the application window.
This method initializes a QDialog object and sets up its UI elements using the Ui_Dialog class.
It also connects various buttons to their respective methods for handling user interactions.
Returns:
| Type | Description |
|---|---|
QDialog
|
QtWidgets.QDialog: The configured dialog window. |
animate_to_size(widget, target_size, duration=300)
staticmethod
¶
Animates the given widget to the target size over a specified duration.
:param widget: The widget to animate. :param target_size: A tuple (width, height) representing the target size. :param duration: The duration of the animation in milliseconds.
resize_extra_widget(expand=False)
¶
Resize the extra widget based on the expand parameter.
Parameters: - expand (bool): If True, expands the widget to a larger size; if False, shrinks it to a smaller size.
This function animates the resizing of self.dialog and self.ui.label_header to the specified dimensions.
fetch_tags()
¶
Retrieves the tags of a GitHub repository and sets them as the value of the version combo box.
This method calls the get_github_repo_tags function to obtain the tags information of the
specified GitHub repository,
and then sets the result as the value of the comboBox_version combo box in the UI.
get_existing_directory()
staticmethod
¶
Opens a dialog for the user to select an existing directory.
Returns: - str: The path of the selected directory.
get_open_file_name_with_ext(*args, **kwargs)
staticmethod
¶
Return a file name, append extension from filter if no extension provided.
open_cache_dir()
¶
Opens the cache directory.
This method retrieves an existing directory path and sets it as the value of a line edit widget. If the directory exists, it updates the UI with the directory path.
Returns:
| Type | Description |
|---|---|
|
The method returns the result of |
|
|
status indicating success. |
open_files()
¶
Opens files or directories based on user selection from the UI.
This function checks which radio button is selected (local clone or local file) and then opens the corresponding directory or file.
Returns:
| Name | Type | Description |
|---|---|---|
None |
The function updates the UI with the selected directory or file path. |
uninstall()
¶
Uninstall the REvoDesign package.
This function checks if REvoDesign is installed. If it is installed, it initiates the uninstallation process through a separate thread, displaying the progress on the UI progress bar. After uninstallation is complete, it provides feedback on the operation's success or failure.
remove_depts()
¶
Removes selected dependencies.
This function removes the packages corresponding to the dependencies checked by the user. It first fetches the dependency mapping table, filters out the dependencies that need to be removed, and then calls the uninstall method of pip_installer to remove each package.
Parameters: - self: The instance of the class containing this method.
Returns: - None
install()
¶
Handles the installation process based on user-selected options.
This function determines the installation source and method based on the user's choices, validates the input, and performs the installation process. It also manages network settings, such as proxies and mirrors, and provides feedback on the installation result.
setup_cache_dir()
¶
Set up the custom cache directory.
This function attempts to import ConfigBus and save_configuration from the REvoDesign library
to update the cache directory settings.
If the specified cache directory is valid, it updates the configuration and saves it.
Returns:
| Type | Description |
|---|---|
|
None |
Session Merger (REvoDesign.tools.SessionMerger)¶
Command-line tool for merging multiple PyMOL session files into a single session.
REvoDesign.tools.SessionMerger.PyMOLSessionMerger
¶
Class: PyMOLSessionMerger Usage: - Initialize: merger = PyMOLSessionMerger(session_paths, save_path) - Add Session Path: merger.add_session_path(session_path) - Merge Sessions: merger.merge_sessions()
This class facilitates merging PyMOL sessions by loading multiple sessions and saving the merged session.
Attributes: - session_paths (list): List of paths to PyMOL session files - save_path (str): Path to save the merged PyMOL session - mode (int): Partial or full loading mode (default is 1) - delete (bool): Whether to delete loaded sessions after merging (default is False) - quiet (bool): Whether to suppress informational messages during loading and saving (default is False)
Methods: - add_session_path(session_path): Adds a session path to the list of session_paths. - merge_sessions(): Merges the PyMOL sessions by loading and saving according to provided attributes.
add_session_path(session_path)
¶
Method: add_session_path Usage: merger.add_session_path(session_path)
Adds a session path to the list of session_paths.
Args: - session_path (str): Path to a PyMOL session file
Returns: - None
merge_sessions()
¶
Method: merge_sessions Usage: merger.merge_sessions()
Merges the PyMOL sessions by loading and saving according to the provided attributes.
Returns: - None