superpose module

Superimposition of structures by rigid-group / torsion optimization.

usage: - SuperPose <moving>.pdb <target>.pdb
  • superpose.py <moving>.pdb <target>.pdb

Module author: Michael S. Chapman <chapmanms@missouri.edu>

Authors:

Michael S. Chapman <chapmanms@missouri.edu>

Oregon Health & Science University & University of Missouri

Version:

1, Nov 26, 2024

Changed in version 0.1: 10/23/2012

Changed in version 0.5: 05/02/2015 ReStructuredText docs

Changed in version 0.5.5: 10/13/15 Anisotropic Us ride with atom rotations.

Changed in version 0.5.6: 03/23/16 Comparative analysis of anisotropic Us.

Changed in version 1.0.0: 09/26/20 Python 2.7 –> 3.6 cmd2: optparse –> argparse: changed calls and decorators

Todo

Pairing by sequence alignment.

class superpose.Accumulator

Bases: object

Running total, mean etc.

add(value, weight=1.0)
mean()
std()
class superpose.Arguments(imports=[], main=None, *args, **kwargs)

Bases: Arguments

Manager for command-line arguments from main and imported modules.

This is a template to be copied into modules, for the handling of command- line options.

methods export() and domestic() should be overridden by the module subclass with declarations of the command-line arguments needed by the module.

Parameters:
  • imports ((list of) ArgumentParser(s)) – (list of) module(s) from which to obtain “parent” ArgumentParser objects for inclusion.

  • main (bool|NoneType) – Add information and arguments appropriate for a main program (or not); if None, will determine by whether this class is defined in __main__.

domestic()

Defines options used only when main program and not when imported.

export()

Defines options used in both stand-alone and imported modes.

finalize()

Completion of the parser after program sub-class initialized.

class superpose.Objective(target_atoms, target_selection, parameters, moving_selection, reference=None, verbosity=0, answer=None)

Bases: object

Callable methods for function, partials to be optimized.

Variables:

continuation (bool) – True (only) if additional cycles w/o changes to model or map calculation parameters. (Continues w/ prior numbering and skips first function evaluation.

Parameters:
  • target_atoms (Atoms) – on which moving structure to be superposed

  • target_selection (atoms.Selection) – which atoms are to be used.

  • parameters (Parameters) – refinement parameters

  • moving_selection (atoms.Selection) – atoms from moving_structure to be superposed on target_selection (must correspond 1-to-1)

  • reference (Atoms or NoneType) – if torsion angle changes are to be restrained (option.torsion_weight), an optional reference state of the moving structure (same atoms, order etc.) can be provided (eg. input structure); else any restraint will apply from the start of each refinement batch.

  • verbosity (int) – increase for greater diagnostic output

  • answer (Atoms) – known correct structure (for testing)

Prone to large initial shift on 1st cycle when model is ~perfect with bfgs. Should be used with l_bgfs_b.

add_torsion_restraint()

Begin applying restraint on changes if torsion angle refinement.

callback(param, parameters_only=False)

Function to be called by optimizer at the end of each iteration.

Optionally calculates the correlation between the latest shifts and the gradients from the last evaluation of the previous cycle. (Empirically, get higher correlations with the final gradient estimate rather then the first.)

Parameters:
  • param (1D ndarray) – refining parameters, xk; Note not yet updated to xk+1 as one might expect at the end of a cycle.

  • parameters_only – Only the parameters have been updated from xk to xk+1, as occurs between the last callback and the end of refinement. Use True after end of refinement.

depends_on_anisou = False

If False, Objective independent of anisotropic U which are “riding” and can be ignored until final update.

f(param, preAlign=False)

Objective function callable for optimizer, with diagnostic output.

Parameters:
  • param (1D ndarray) – refining parameters

  • preAlign (bool) – Overall rigid-group superposition prior to function calculation. Should only use in diagnostics, not refinement, as incompatible with fprime which must be able to calculate derivatives for rigid-group refinement.

fprime(param)

Partials callable for optimizer, with diagnostic output.

Partial derivatives are mostly calculated by methods called and documented therein. Exceptions are some of the group and overall partial derivatives calculated from atomic partials.

Parameters:

param (1D ndarray) – refining parameters

function_detail = 3
progress = 1
step_detail = 2
class superpose.OldArguments(imports=[], main=True, *args, **kwargs)

Bases: ArgumentParser

Subclass, adding program-specific command-line options.

Parameters:
  • imports ((list of) ArgumentParser method(s)) – method(s) adding arguments to ArgumentParser instance. (Alternative to ArgumentParser parents w/ better maintained groups.)

  • main (bool) – Parser for main program (i.e. not listed within an ArgumentParser parents argument). Adds default program information.

static export(self)

Adding options used in both stand-alone and imported modes.

finalize()

Completion of the parser after program sub-class initialized.

class superpose.PairItem(atoms)

Bases: object

One of the structures in a Pairing.

Variables:
  • atoms – coordinates

  • selection – atoms with which pairing to be tried

  • paired – atoms successfully paired.

  • equiv (dict) – indices of another structure paired to this one (see also matched_to)

  • matched_to (ndarray) – indices of atoms of paired structure (only where self.paired)

One of the two structures in a pair.

Parameters:

atoms (Atoms, Group or Selection) – coordinates, Group or Selection

copy(atoms, *attributes)

In-place copy of attributes from Atoms.

Does not re-pair atoms. It is unlikely, but conceivable that a user might want re-pairing if the pairing were based on xyz, b or o, or o as implicit through conformer.

Parameters:
  • atoms (atoms.Atoms) – Coordinate set.

  • attributes (str [, str...]) – names of attributes to be copied.

Returns:

updated Pairing coordinate set.

Return type:

Pairing.Item

from_pair(array)

Copy by index of paired atoms into an array, masked where unpaired.

Parameters:

array (ndarray) – shape[0] must equal number of atoms in paired structure.

Return mapped:

values copied according to order in self.atoms

Rtype numpy.MaskedArray:

property index

ndarray of indices of atoms matched.

matched_to

Indices for paired atoms where self.paired, calculated by Pairing.

property reordered

Subset of atoms matched, in order of other structure.

property reordered_paired

Trivial ‘all’ Selection for self.reordered when needed.

(As reordered contains only atoms paired with the other structure, Selection is, by definition ‘all’.)

class superpose.PairSubCommands(parent, prompt='sub-command')

Bases: SubCmd, ProgCmd

Sub-commands for pairing.

Parameters:
  • parent (TopCmd instance) – Cmd object whence this call was made, usually self.

  • prompt (str) – concatonated with the parent’s prompt.

do_match(args)

Pair atoms by attribute value (-v) and/or position (-p; order).

Through the overall (pair -m/-t) and current (within -m/-t) selections and use of sufficient paired attributes, the specified match must be unambiguous 1:1.

do_print(args)

Pairing statistics.

do_within(args)

Limit atom matching to moving and/or target selection until redefined.

Selections are remembered between pair commands. These selections are combined (logical AND) with those of the parent pair command. Limits need only be defined for one of the structures, but both can be used if more convenient.

help_SELECTION_EXPR()
match_parser = ArgumentParser(prog='sphinx-build', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
within_parser = ArgumentParser(prog='sphinx-build', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
class superpose.Pairing(atomsA, atomsB)

Bases: object

Equivalences between two Atoms() coordinate sets, a & b.

Instantiate an empty Pairing.

Parameters:
  • atomsA (Atoms|Group|Selection) – atomic coordinates, Group or Selection

  • atomsB (Atoms|Group|Selection) – atomic coordinates, Group or Selection

See also

Pairing.add to fill it with atoms.

add(value=['atnam', 'resnum', 'conformer'], position=['chain'], selectionA=None, selectionB=None, verbose=True)

Add pairs of atoms with matching attributes.

Finds pairs of atoms in the selections that can be matched unambiguously by attribute value or order (position). Attributes are matched in a progression from chain-level to atomic. Those in ‘value’ require an exact match. Those in ‘position’ are matched by order of appearance at the current state, i.e. ignoring atoms that have already been excluded with a higher level attribute. (Thus for example, residues might be matched by position in each chain as long as the chains contain the same number of selected residues.) One could pair homologous proteins by selecting residues of each structure that are not in gaps, and then aligning residue-number by position.

May be called repeatedly to expand a pairing.

Time is proportional to the product of the selection sizes, so large structures can be paired faster by repeated calls with different chains selected.

Parameters:
  • value (list of strings) – attributes that must match exactly. Synonyms in Selection._attributes are recognized.

  • position (list of strings) – attributes that will be matched by order, providing that the selections contain the same numbers of each. Synonyms in Selection._attributes are recognized.

  • selectionA (Selection or Group) – optional subset selection.

  • selectionB (Selection or Group) – optional subset selection.

Raises:

LookupError – if any ambiguity remains in pairing.

attributeOrder = ['segid', 'chain', 'resnum', 'resnam', 'insert', 'atnam', 'atype', 'element', 'charge', 'conformer', 'altloc', 'o', 'b']

Order in which attributes will be paired.

bfactors(selection=None, name='User_selection', scaling=None, verbose=False, quiet=False, plot_screen=True, plot_files=None, color=None, residue_ttest=False, a_wt=True, b_wt=True, delta_wt=False, plot_hetatms=False)

Comparison of atomic displacement parameters of “a” (moving) to “b” (target).

Parameters:
  • selection (Selection|Group|NoneType) – subset(s) of atoms (from self.a) to analyze

  • name (str) – python-valid dict key name to be used for an unnamed selection.

  • scaling (str|NoneType) – how the U values are to be scaled (atoms resized) to best match target atoms: “individual”, “group” or None. (The group(s) is/are defined by selection; selection=None for all-atom uniform).

  • verbose (bool) – statistics by atom and residue

  • quiet (bool) – statistics totaled by selection (only)

  • plot_screen (bool) – comparative analysis of anisotropic Bs and coordinate differences graphed to screen. Requires user to close window, so use False for batch jobs.

  • plot_files (str-2-uple) – file names for same graphical analysis, one comparing anisotropic Us, other comparing Us of moving structure to coordinate differences. Extension indicates file format: .emf, eps, jpeg, jpg, pdf, png, ps, raw, rgba, svg, svgz, tif, tiff. Can be used with plot_screen or independently.

  • color (str-tuple) – names for pdb output of moving structure in which B-factors will be replaced by anisotropy of moving structure, 100 x |cos(U mis-alignment between paired atoms)|, and 100 x |cos(moving structure U mis-alignment vs. coordinate difference vectors)|, and (if names are provided), 100 x (1 - Kulback-Liebler divergence), and (if not already scaled), 100 x (1 - scaled Kulback- Liebler divergence). So the tuple should contain 0 or 3 to 5 file names, the 5th optionally None.

  • residue_ttest (bool) – compare to randomized (shuffled atoms) using Welch’s t-test for unequal means. This is usually overkill, per-residue, as P(random) is usually tiny.

  • a_wt (bool) – Weight weighted means by (1-Anisotropy) (i.e. asymmetry). (Can be used with other weights.)

  • b_wt (bool) – Weight weighted means by B_iso (size of atom). (Can be used with other weights.)

  • delta_wt (bool) – Weight weighted means by size of coordinate difference. (Use with care, because effects on U vs. U alignment might be different from U vs. delta xyz.) (Can be used with other weights.)

  • plot_hetatms (bool) – include ligands and solvent in plots, else just polymers.

Return None:

Warning

Averages do not weight by occupancy of multiconformer parts.

Warning

Statistics calculated only for atoms input with anisotropic U tensors, not those input with only an ATOM (isotropic) record.

property connectivity

Covalent connectivity of paired atoms.

Changed in version ?: For generality, don’t think that can restrict moving selection to self.a.paired, but this may have multiple consequences???

continuable

Superposition refinement just completed and can be extended.

deprecated_3ax = True
difference(verbose=False)

Difference between coordinate sets: rmsd(xyz), <|O1-O2|>, <|B1-B2|>

Returns:

RMS deviation in coordinates, mean absolute difference in coordinates, occupancy & B-factor

Return type:

4 floats

See also

Atoms.difference provides similar functionality for coordinates that are not yet paired and will be paired by attribute value.

differences(quiet=False)

Print differences between coordinates by residue: each atom, rms.

Parameters:

quiet (bool) – return vectors without printed output

Returns:

difference vector (a - b) for each paired atom

Return type:

numpy.MaskedArray of same (3, N) shape as self.a.atoms.xyz

See also

Atoms.differences provides similar functionality for coordinates that are not yet paired and will be paired by attribute value.

differences_vs_bs(scale=False, individual=False, map_to_a=True, intermediate=(0.0, 1.0), diagnostics=[0, 50.0])

Compare coordinate differences to B-factors.

Parameters:
  • scale (Group|Selection|bool) – normalize for average b_iso atom size within group(s) of atoms in self (if specified), treating all non-selected atoms as an additional group.

  • individual (bool) – scaling by individual atom, else by average isotropic B

  • intermediate ((float, float)) – beyond these prolateness limits, the ellipsoid will be considered pure oblate and prolate respectively, transitioning between the two with a linear ramp between the limits.

  • map_to_a (bool) – statistics for structure b will be mapped to the paired atoms of structure a; else will reordered as in structure a, but a contiguous array only for the b atoms that are paired.

  • diagnostics ([int, float]) – print diagnostics for 1st n cases where alignment stats differ by more than threshold.

Returns:

difference magnitudes, then misalignments between diffence vectors and anisotropic Bs for both a and b structures

Return type:

(MaskedArray,) x 3, shapes len(self.a.atoms) (but 3rd shape is count(self.a.paired) if map_to_a=False).

Misalignment is the average (cosine) deviation.

equivs

Array[N, 2] with the paired indices from structures a & b.

info(verbose=False)

Difference statistics on matched atoms: rmsd(xyz), <|O1-O2|>, <|B1-B2|>

Returns:

matched atoms, atoms in structure A, structure B

Return type:

3 int

loquacious = False
objective

Methods for refinement objective function, derivatives.

overlay(selection=None)

Rigidly transform selected atoms of “a” to superimpose on target “b”.

Initial alignment: faster/quicker convergence than superpose for overall superimposition, but less control. Uses Kabsch’s eigenvector method.

Parameters:

selection (boolean Selection or Group) – atoms to be transformed, noting that all paired atoms are used for the alignment irrespective of which atoms are selected to be transformed.

Returns:

reference to the in-place updated Pairing.

Return type:

Pairing

parameters

Last refinement’s parameters, gradients, history etc..

residueTable

Changes, impact per residue.

superpose(continuation=False, refine=None, method='l_bfgs_b', max_cycles=10, min_improvement=0.0, min_grad=-1.0, accuracy=0.0, reference=None, verbosity=0)

Superpose selected atoms of “a” onto target “b” by changing parameters.

With torsion optimization, the tuple phipsi supports definition of a subset of phi, psi angles within a moving atom selection. Within the moving atom selection, the dependence on each torsion angle is determined by a graph of atom connectivity determined automatically, and then optionally edited through the link and unlink parameters.

Parameters:
  • continuation (bool) – resume a prior refinement, ignoring any new model parameterization arguments (individual atoms, groups, overall, phipsi).

  • refine (optimize.AtomicParameterization or subclass) – definition of what is to be refined, how atomic parameters are to be collectivized.

  • method (str) – tested are ‘l_bfgs_b’, ‘bfgs’, but ‘Powell’, ‘CG’, ‘Newton_CG’ & ‘TNC’ are also available (see scipy.optimize.minimize documentation)

Note

l_bfgs is usually recommended as the memory usage of bfgs increases with the square of the number of parameters (atoms). l_bfgs_b also supports bound-constrained refinement.

Note

The convergence criteria below are used by the methods listed in parentheses (see scipy documentation), and are otherwise ignored.

Parameters:
  • min_improvement (float) – refinement (l_bfgs_b, TNC) is stopped when relative change in function < min_improvement, i.e. precision of 1.e-2 stops when change < 1% of current residual value.

  • accuracy (float) – criteria for convergence if estimated fractional error for all parameters is less than accuracy (Powell, Newton_CG).

  • max_cycles (int) – maximum number of iterations (Powell, bfgs, Newton-CG, l_bfgs_b, TNC).

  • min_grad (float) – refinement stopped when the largest derivative magnitude falls below this value (internal parameter units as reported by analyze) (CG, bfgs, l_bfgs_b, TNC).

  • reference (Atoms or NoneType) – if torsion angle changes are to be restrained (option.torsion_weight), an optional reference state of the moving structure (same atoms, order etc.) can be provided (eg. input structure); else any restraint will apply from the start of each refinement batch. This structure is also used if residue tables and plots use overall options.

  • verbosity (int) – -1 for silent, 0 for terse, 1 for verbose, > 1 for (debugging) information on each function or gradient evaluation.

Returns:

new object of moved atoms

Return type:

Atoms

class superpose.Parameters(atoms, parameter_selection={'B': {'group': False, 'indiv': False, 'overall': False}, 'magnification': False, 'occ': {'group': False, 'indiv': False, 'overall': False}, 'position': {'group': True, 'indiv': False, 'overall': True, 'torsion': True}}, defaults=None, link=None, unlink=None)

Bases: Parameters

Maps refining parameters into a linear array.

Saves slices for extraction of updated parameters. Although atoms and groups may contain non-contiguous sequences of atoms, the refinable parameters will be loaded contiguously, so that they can be recovered using a single slice. Saves the atomic coordinates used on instantiation for extraction so that any changes outside of Parameters.array will be ignored.

Parameters:
  • atoms (Atoms) – atomic coordinates etc.

  • refine (AtomicParameterization (or subclass)) – Dict-like object defining parameters to be refined and their dependence on atomic coordinates.

  • link ((Group of) 2-atom atoms.Selection(s)) – Additional pair(s) of atoms to be linked for joint rotations about (other) torsion bonds.

  • unlink ((Group of) 2-atom atoms.Selection(s)) – Disconnect pair(s) of atoms from those automatically linked so that not rotated together about torsion bonds.

grouping = 'overall'
param = 'magnification'
partials = "{\n                 'position':{'indiv':dxyz, 'group':drigid, \n                             'overall':dxyzoverall, 'torsion': dtorsion},\n                 'B':  {'indiv':False, 'group':False, 'overall':False},\n                 'occ':{'indiv':False, 'group':False, 'overall':False},\n                 'magnification': False\n                 }"
supported_modes = "{\n                 'position':{'indiv':False, 'group':True, 'overall':True, \n                         'torsion': True},\n                 'B':  {'indiv':False, 'group':False, 'overall':False},\n                 'occ':{'indiv':False, 'group':False, 'overall':False},\n                 'magnification': False\n                 }"
value = False
class superpose.Tasks

Bases: Tasks, Tasks

Program-specific tasks, supporting just-in-time execution.

Methods with names ending _prereq define tasks whose prerequisites will be met, if possible, prior to execution.

Superclass for atoms-related common tasks.

Warning

If this class defines pre-requisites on which other tasks depend, then this superclass must be instantiated before the other tasks are defined. If this class depends on pre-requisites defined elsewhere, then it must be instantiated afterwards. It may not be possible to satisfy both requirements!

property atoms_being_evaluated
property atoms_refined
backup(jar)

Pickle current refinement state for future restoration.

Saves the current coordinates, ResidueTable and refinement History, but not the parameterization, options etc..

Parameters:

jar (str) – file name

backup_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

bfactors(*args, **kwargs)

Analysis of atomic displacement parameters.

bfactors_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

property default_group
evaluate(quiet=False, verbose=False, color=None, scale=1.0)

Current model statistics.

Parameters:
  • color (str|NoneType) – name of a new PDB file in which B will be replaced by the coordinate difference.

  • scale (float) – for the differences in the PDB file.

evaluate_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

flip(glu=True, gln=True, asp=True, asn=True, his=True, phe=True, tyr=True, arg=True, **kwargs)

Side-chain flipping of moving coordinates, invokes rotamer.flip().

Tests residue type specified as True.

flip_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

overlay(moving=None)

Overalay selected atoms of moving structure onto target.

Parameters:

moving (Selection) – atoms to be transformed, noting that the least-squares transformation is calculated using all paired atoms, not just those selected.

overlay_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

pair(value=None, position=None, moving=None, target=None)

Pair atoms between structure A (moving) & B (target).

Requires self.pairing as a Pairing instance.

Parameters:
  • value (list of strings) – attributes that must match exactly. Synonyms in atoms.Selection._attributes are recognized.

  • position (list of strings) – attributes that will be matched by order, providing that the selections contain the same numbers of each. Synonyms in atoms.Selection._attributes are recognized.

  • moving (atoms.Selection or str criteria) – atoms within A used for this pairing command.

  • target (atoms.Selection or str criteria) – atoms within B used for this pairing command.

Returns:

updated self.pairing

Return type:

atoms.Pairing

Changed in version 02/13: Reimplemented to use Pairing, supporting selections on both structures and matching by flexible criteria.

pair_init(moving=None, target=None)

Prepare to pair atoms between structure A (moving) & B (target).

Parameters:
  • moving (Atoms, Selection or str (criterion for Selection)) – atoms [def. self.atoms] or master selection thereof for subsequent pairing commands. Future selections will be combined with the optional master selection through logical AND.)

  • target (Atoms, Selection or str (criterion for Selection)) – atoms [def. self.target_in] or master selection thereof for subsequent pairing commands. Future selections will be combined with the optional master selection through logical AND.)

Returns:

self.pairing

Return type:

Pairing

pair_init_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

pair_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

parameterization_init()

Initialize parameterization - directives on what/how to refine.

parameterization_init_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

parameterize()

Pass-back after checking prerequisites for parameterize sub-comds.

parameterize_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

phipsi_copy(**arguments)

Copy phi, psi from target into current structure.

Parameters:

sigma (float) – copy only dihedrals whose difference exceeds this sigma-level.

phipsi_copy_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

phipsi_diff(color=None, pseudo=False, normalized=True, **arguments)

Difference in phi, psi between current structure & target.

Parameters:
  • color (str or NoneType) – PDB filename is which Bs will reflect phi-psi differences.

  • pseudo (bool) – φi’ is to be combined with |psgr|:sub:`i-1 in above PDB.

  • normalized (bool) – use relative magnitudes instead of actual torsion angle differences.

phipsi_diff_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

read_coords(*args, **kwargs)
Parameters:

new_file (str) – PDB file to be read.

Warning

Does not automatically recalculate statistics etc..

read_target(new_file=None)

New coordinates for target, but does not recalculate statistics.

Parameters:

new_file (str) – PDB file to be read.

read_target_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

refine(continuation=False, restart=False, method='l_bfgs_b', max_cycles=0, min_improvement=0.0, accuracy=0.0, min_grad=-1.0, verbosity=0)

Superpose wrapper: align moving molecule to target.

Parameters:
  • continuation (bool) – If not restart, treat as a continuation of a prior batch if no change in parameterization and atoms since last refinement. False - force a new batch.

  • restart (bool) – from start of prior refinement.

  • method (str) –

    tested are ‘l_bfgs_b’, ‘bfgs’, but ‘Powell’, ‘CG’, ‘Newton_CG’ & ‘TNC’ are also available (see scipy.optimize.minimize documentation)

Note

l_bfgs is usually recommended as the memory usage of bfgs increases with the square of the number of parameters (atoms). l_bfgs_b also supports bound-constrained refinement.

Note

The convergence criteria below are used by the methods listed in parentheses (see scipy documentation), and are otherwise ignored.

Parameters:
  • min_improvement (float) – refinement (l_bfgs_b, TNC) is stopped when relative change in function < min_improvement, i.e. precision of 1.e-2 stops when change < 1% of current residual value.

  • accuracy (float) – criteria for convergence if estimated fractional error for all parameters is less than accuracy (Powell, Newton_CG).

  • max_cycles (int) – maximum number of iterations (Powell, bfgs, Newton-CG, l_bfgs_b, TNC).

  • min_grad (float) – refinement stopped when the largest derivative magnitude falls below this value (internal parameter units as reported by analyze) (CG, bfgs, l_bfgs_b, TNC).

  • verbosity (int) – -1 for silent, 0 for terse, 1 for verbose, > 1 for (debugging) information on each function or gradient evaluation.

Returns:

new object of moved atoms

Return type:

Atoms

refine_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

restore(jar)

Restores a previously pickled refinement end-point.

Restores the current coordinates, ResidueTable, History and selected refinement and parameter attributes.

Parameters:

jar (str) – file name

Warning

options and parameterization must be made compatible with jar-file before it is loaded.

Warning

FRAGILE - because refinement and parameter instances contain methods, they cannot be pickled. They must exist and have been instantiated with the same parameterization mapping with which the objects in the jar file were created. Then instances with the methods can have selected attributes rebound to jar objects.

See also

restore_prereq for creation of a new refinement instance if needed.

See also

comments in code for backup for explanation.

restore_prereq(*args, **kwargs)

Pass-through, trying to meet the prerequisites.

If refinement has not previously been run, it will be implicitly through the prerequisite defined for self._restore.

Warning

No matter how created, the refinement instance must have been created with the same parameterization (and program options) as when the jar file was saved. There is no error checking, and unpredictable results are expected, because otherwise the mapping of structural parameters to the optimization parameter array will be garbled.

restrain_to_reference = True
run_test(name, arguments=None)

Program development testing.

verbose = False
class superpose.Test(name)

Bases: object

set_options(options)
class superpose.TopCommands(tasks, initial_commands=None, py_locals={}, parser=None)

Bases: Commands, Commands, TopCmd, ProgCmd

Top-level commands for Program Prog.

Parameters:
  • tasks (Control) – class instance that defines methods to be called.

  • initial_commands (str or list of str) – file(s) of commands to run before interactive loop at the top level, and before any command-line commands.

  • py_locals (dict) – objects added to the local namespace in the python interpreter invoked by ‘py’ commands.

  • parser (ArgumentParser (argparse) or OptionParser (optparse)) – to which -t / –test option will be added for cmd2 regression testing. Should only be used once / program.

backup_parser = ArgumentParser(prog='sphinx-build', usage=None, description='Save state: coordinates, history, refinement stats', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
bfactors_parser = ArgumentParser(prog='sphinx-build', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
do_backup(args)
do_bfactors(args)

B-factor statistics comparing current model to target.

do_evaluate(args)

Statistics for current model compared to target.

do_flip(args)

Chi rotation of pseudo-symmetrical side chains to match target.

180 degree rotations about sp3-sp2 bonds.

Warning

exception if PDB contains hydrogens (should not be needed at high resolution anyway).

do_overlay(args)

Apply the rigid transformation that LSQ overlays moving atoms on paired targets.

For a single rigid group, this is prefered over iterative refinement, using the Kabsch method to give the least-squares solution in a single step.

overlay transforms selected coordinates by the rigid group operator

that least-squares aligns previously paired refining and target atoms. (Note that the selection here (default is ‘all’) can be different from the selections used in pairing.) The operator is determined by Kabsch’s eigenvector method [Kabsch-1976], [Kabsch-1978]. This is a direct (linear) method that can circumvent slow and narrow convergence of the non-linear methods in refine. However, it cannot be combined with torsion angle parameterization or external restraints. It is best used as a preliminary such that refine can start well within its convergence radius.

[Kabsch-1976]

Kabsch, W., 1976. A solution for the best rotation to relate two sets of vectors. Acta Crystallographica A32, 922-3.

[Kabsch-1978]

Kabsch, W., 1978. A discussion of the solution for the best rotation to relate two sets of vectors. Acta Crystallographica A34, 827-8.

do_pair(args)

Pair atoms between moving & target structures. Required before flip, refine etc..

Option –moving and –target selections limit the atoms that are available for matching in (just) this pair session (defaults are all atoms). These selections are combined (logical AND) with those of the pair>within subcommand. Limits need only be defined for one structure, but either/both can be specified for convenience.

do_parameterize(args)

For designated parameter type(s) (def. positions), select atoms to be refined & how.

do_phipsi_copy(args)

Copy phi, psi from target to moving structure

do_phipsi_diff(args)

Difference in phi, psi between current structure & target.

do_refine(args)

Refine atomic model.

do_restore(args)
do_test(args)

Run a program developer’s test.

evaluate_parser = ArgumentParser(prog='sphinx-build', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
flip_parser = ArgumentParser(prog='sphinx-build', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
help_test()
overlay_parser = ArgumentParser(prog='sphinx-build', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
pair_parser = ArgumentParser(prog='sphinx-build', usage=None, description='Pair atoms between moving & target structures; pre-requisite of flip, refine.', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
parameterize_parser = ArgumentParser(prog='sphinx-build', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
phipsi_copy_parser = ArgumentParser(prog='sphinx-build', usage=None, description='Copy phi, psi from target to moving structure', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
phipsi_diff_parser = ArgumentParser(prog='sphinx-build', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
refine_convergence = <argparse._ArgumentGroup object>
refine_parser = ArgumentParser(prog='sphinx-build', usage=None, description=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
restore_parser = ArgumentParser(prog='sphinx-build', usage=None, description='Restore state: coordinates, history, refinement stats', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
test_parser = ArgumentParser(prog='sphinx-build', usage=None, description='Run a test (program development only).', formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
superpose.dissect(obj, doc)

Recusrively type the attributes of an object, printing documentation..

A diagnostic used to gopher out forgotten burried ndarrays that hopefully will never be needed again.

Parameters:
  • obj – object (and its attributes) to be typed.

  • doc (str) – printed label, often the attribute name.

superpose.findS0(obj, doc, exception=False, verbose=True)

Recusively gopher out string ndarrays.

Documents string ndarrays which will cause pickle.load() errors. Scans attributes, but not items if object is a sequence.

Parameters:
  • obj – object and its attributes to be analyzed.

  • doc (str) – label to be printed, often attribute name.

  • exception (bool) – raise exception if zero-length numpy.string encountered, noting that ndarray initialization to [‘’, ‘’] gives length-1. It might be only those instantiated to None or numpy.nan that raise exception.

  • verbose (bool) – print (some of) array contents if numpy.string

superpose.main()
superpose.startup()

Program initialization, reading options etc..

Returns:

parser

Return type:

Arguments.ArgumentParser

superpose.std_err_mu(var_a, a_size, var_b, b_size)

Standard error between sample means.

BMJ introduction

This is the same as the standard error between small-sized sample and population mean (unequal variances). (BMJ explanation)

superpose.t1_Welch_gt(data, comparison)

Welch’s unequal variances 1-tailed t-test for mean(data)>mean(comparison)

Parameters:
  • data (ndarray)

  • comparison (ndarray)

(Like a student t-test for unequal variances; Wiki)

superpose.t1_Welch_lt(data, comparison)

Welch’s unequal variances 1-tailed t-test for mean(data)<mean(comparison)

Parameters:
  • data (ndarray)

  • comparison (ndarray)

(Like a student t-test for unequal variances; Wiki)

superpose.z_d(mean_a, var_a, a_size, mean_b, var_b, b_size)

Difference between means in standard error units (z-score).

BMJ introduction

This is the same as Sattherwaite’s approach for an analogous d-score:

BMJ t-test explanation

Also same as Welch’s unequal variances t-test, for calculation of a Student-t like difference in means (t-statistic).

So we also calculate degrees of freedom for a t-test

Deprecated since version use: scipy.stats.ttest_ind(equal_var=False) or scipy.stats.mstats.ttest_ind(equal_var=False)