polyphys.probe.pairs#
polyphys.probe.pairs#
The polyphys.probe.pairs module measures, in every frame of a
trajectory, the distances between the particles of one species, the pairs
in direct contact, and the bonds and clusters those contacts form: the
foci of the TransFoci studies, the large monomers of a ring among small
ones. PairDistances is an MDAnalysis
AnalysisBase, so it runs over a slice of
frames in serial or, split across workers, in parallel, and stores one
array per quantity in its results.
The research code measured the same four quantities in one loop over the
frames of each TransFoci study’s probe function, without the minimum
image, and wrote the LAMMPS atom IDs of the foci on the diagonal of the
distance matrix. Here the diagonal carries the foci’s 0-based backbone
indices (see PairDistances, “Notes”), and the minimum image along
the periodic directions is optional.
Contents#
PairDistances, the per-frame pair analysis.
Dependencies#
Python standard library: math, pathlib, typing.
MDAnalysis 2.8 or later, through the
mdaextra:AnalysisBaseandResultsGroup.polyphys.analyze.clusters:pair_distances(),find_direct_contacts(),count_bonds(), andcount_clusters().polyphys.probe.core:_ProbeAnalysis, the base whoseruncloses the pool of themultiprocessingbackend, and_compute_part, which computes each part of a split run on its own copy of the analysis.
Notation#
- \(n\), \(F\)
The number of particles of the species and the frames of a run.
- \(d_{ij}\), \(r_c\)
The distance between particles \(i < j\) in a frame, in the dump’s length unit, and the contact cutoff: \(i\) and \(j\) are in direct contact when \(d_{ij} \le r_c\).
- \(g_i\)
The backbone index of particle \(i\), 0-based, from which the pipeline’s
FociPairDistancestakes the genomic distance of each pair.
Examples
Three foci at the corners of a 3-4-5 triangle, one frame, with a cutoff of 3.5: the first two are in contact, the third is alone.
>>> import MDAnalysis as mda
>>> import numpy as np
>>> universe = mda.Universe.empty(3, trajectory=True)
>>> universe.atoms.positions = np.array(
... [[0.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 4.0, 0.0]])
>>> analysis = PairDistances(universe.atoms, 3.5, [2, 5, 8]).run()
>>> analysis.results['distMatTFoci'][0]
array([[2., 3., 5.],
[0., 5., 4.],
[0., 0., 8.]])
>>> analysis.results['bondsHistTFoci'], analysis.results['clustersHistTFoci']
(array([[1, 2, 0]]), array([[0, 1, 1, 0]]))
Added in version 0.7.0.
Classes
|
The pair distances, direct contacts, bonds, and clusters of one species, measured in every frame. |
- class polyphys.probe.pairs.PairDistances(atomgroup, cutoff, genomic_positions, *, species='Foci', periodic=None, inclusive=True, verbose=False)[source]#
Bases:
polyphys.probe.core._ProbeAnalysisThe pair distances, direct contacts, bonds, and clusters of one species, measured in every frame.
Added in version 0.7.0.
- Parameters:
atomgroup (
MDAnalysis.core.groups.AtomGroup) – The particles, at least two, in atom-ID order, whichUniverse.select_atomsgives; they index the matrices.cutoff (
float) – The contact cutoff \(r_c\), finite and positive, in the dump’s length unit.genomic_positions (
typing.Union[typing.Sequence[int],numpy.ndarray]) – The backbone index \(g_i\) of each particle, 0-based, non-negative, and distinct, one per particle in the group’s order; written on the diagonal of every frame’s distance matrix.species (
str) – The species label, which namesresultsand the filessave()writes,<name>-<quantity><species>.npy.periodic (
tuple[bool,bool,bool] |None) – The directions along which the distances use the minimum image, one flag each forx,y, andz, with the frame’s box lengths;Nonefor none, as the research code measured.inclusive (
bool) – Whether a pair at exactly the cutoff is in contact, \(d_{ij} \le r_c\), as the research code counted, rather than \(d_{ij} < r_c\).verbose (
bool) – Whether to show a progress bar duringrun().
- Variables:
atomgroup (
AtomGroup) – The particles.cutoff (
float) – The contact cutoff.genomic_positions (
numpy.ndarray) – The backbone indices, int64, shape(n,).species (
EntityT) – The species label.periodic (
tupleofboolorNone) – The minimum-image directions.inclusive (
bool) – Whether the cutoff itself counts as contact.results (
Results) – Afterrun(), withSthe species label:distMatTS, float64(n_frames, n, n), each frame’s \(d_{ij}\) for \(i < j\) above the diagonal, \(g_i\) on it, and zeros below;directContactsMatTS, bool(n_frames, n, n), the symmetric contact matrix withTrueon the diagonal, asfind_direct_contacts()returns it;bondsHistTS, int64(n_frames, n),[t, d]the number of particles withdcontacts in framet;clustersHistTS, int64(n_frames, n + 1),[t, s]the number of clusters of sizesin framet, with[t, 0]always 0.n_frames (
int) – Afterrun(), the number of frames analyzed, fromAnalysisBase.frames (
numpy.ndarray) – Afterrun(), the indices of the frames analyzed, shape(n_frames,).times (
numpy.ndarray) – Afterrun(), the times of the frames analyzed, shape(n_frames,), in the trajectory’s time unit.
- Raises:
ValueError – If atomgroup has fewer than two particles; if cutoff is not a finite positive number; if genomic_positions has not one non-negative integer per particle or repeats one; if species is empty; or if periodic is neither
Nonenor three booleans, Python or NumPy. Duringrun(), if a periodic direction is asked for and the frame carries no box.
Notes
Per frame,
pair_distances()gives the full distance matrix, with the minimum image along each direction of periodic using that frame’s box length;find_direct_contacts()the contacts at the cutoff;count_bonds()the bonds histogram; andcount_clusters()the clusters histogram, from the connected components of the contact matrix. The distance matrix is stored as the research code wrote it: its upper triangle, with the diagonal replaced.Indexing. LAMMPS numbers atoms from 1 (
read_data: “a unique value from 1 to Natoms for each atom”), and MDAnalysis keeps those numbers asAtomGroup.idswhile numbering its own atoms from 0 asAtomGroup.indices. The research code wrotefoci.atoms.idson the diagonal, so the pair tags of its analysis,loc<i>loc<j>, carry 1-based IDs. Here the diagonal carries the 0-based position of each particle along its chain, whichgenomic_distance()requires andfrom_spec()computes; a tag of this package is therefore one less than the research tag of the same pair. The genomic distance itself is the same under either convention.The MDAnalysis contract:
_prepareallocates one array per quantity for the frames of the run,_single_framewrites the current frame’s entry, and_concludedoes nothing. The class is marked parallelizable, withserial,multiprocessing, anddaskbackends; each worker fills the arrays of its own frames, which_get_aggregatorconcatenates along the frame axis (ResultsGroup.ndarray_vstack).Cost per frame: \(O(n^2)\) time and space for the distance and contact matrices and the connected components. Over a run, \(8 F n^2\) bytes for the distance matrices, \(F n^2\) for the contact matrices, and \(8 F (2 n + 1)\) for the two histograms: for the five foci of the TransFoci studies, \(8 \cdot 25 + 25 + 8 \cdot 11 = 313\) bytes per frame. Positions come from MDAnalysis as float32, so each distance carries a relative round-off of about \(10^{-7}\).
Examples
Two particles across the periodic boundary of a box of length 20 along z, at z = 0.5 and 19.5, are 1 apart with the minimum image and 19 without:
>>> import MDAnalysis as mda >>> import numpy as np >>> universe = mda.Universe.empty(2, trajectory=True) >>> universe.load_new( ... np.array([[[0.0, 0.0, 0.5], [0.0, 0.0, 19.5]]]), format='MEMORY', ... dimensions=np.array([[20.0, 20.0, 20.0, 90.0, 90.0, 90.0]])) <Universe with 2 atoms> >>> wrapped = PairDistances(universe.atoms, 1.5, [0, 9], ... periodic=(False, False, True)).run() >>> wrapped.results['distMatTFoci'][0, 0, 1] np.float64(1.0) >>> wrapped.results['directContactsMatTFoci'][0] array([[ True, True], [ True, True]]) >>> PairDistances(universe.atoms, 1.5, [0, 9]).run().results[ ... 'distMatTFoci'][0, 0, 1] np.float64(19.0)
- classmethod from_spec(universe, spec, parser, *, verbose=False)[source]#
Build the analysis of a whole’s pair species from its study’s probe spec.
The particles are
spec.pair_speciesselected with its string inspec.selections; the cutoff isspec.contact_cutoffresolved for this whole; the backbone indices are the particles’ positions among the atoms ofspec.chain, in atom-ID order; and the minimum image follows the geometry whenspec.minimum_imageis set.Added in version 0.7.0.
- Parameters:
universe (
MDAnalysis.core.universe.Universe) – The trajectory, asmake_universe()opens it.spec (
polyphys.spec.ProbeSpec) – The study’s probe spec, withpair_speciesandcontact_cutoffset.parser (
polyphys.manage.parser.ParserBase) – The whole’s parser, for the cutoff.verbose (
bool) – Whether to show a progress bar duringrun().
- Returns:
The analysis, not yet run.
- Return type:
- Raises:
ValueError – If the spec names no pair species, or if a selected particle is not among the chain’s atoms.
Examples
A ring of six monomers whose atoms 2, 4, and 6 (LAMMPS IDs) are the large ones: their backbone indices are 1, 3, and 5.
>>> import MDAnalysis as mda >>> import numpy as np >>> from polyphys.tests.synthetic import RingCub >>> from polyphys.spec import ProbeSpec, ProjectSpec >>> project = ProjectSpec( ... parser=RingCub, group='bug', divisor=0.025, ... crowder_attr='phi_bulk_c', ... physical_attrs=('space', 'nmon_small', 'nmon_large'), ... species_sizes={'Mon': 'dmon_small', 'Foci': 'dmon_large', ... 'Crd': 'dcrowd'}, ... tseries_properties=('gyrTMon',)) >>> spec = ProbeSpec( ... project, {'Mon': 'resid 1', 'Foci': 'type 2'}, 'Mon', ... ('gyrT',), unwrap=False, pair_species='Foci', ... contact_cutoff=lambda info: info.dmon_large + info.dcrowd) >>> whole = RingCub( ... 'al2nl3ml8ns3ac1nc0l5dt0.005bdump1adump1ens1', ... 'whole', 'bug') >>> universe = mda.Universe.empty( ... 6, n_residues=1, atom_resindex=[0] * 6, trajectory=True) >>> universe.add_TopologyAttr('resid', [1]) >>> universe.add_TopologyAttr('ids', [1, 2, 3, 4, 5, 6]) >>> universe.add_TopologyAttr('types', ['1', '2'] * 3) >>> universe.load_new(np.array([[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], ... [2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 1.0, 0.0], ... [3.0, 2.0, 0.0]]]), format='MEMORY', dimensions=np.array( ... [[10.0, 10.0, 20.0, 90.0, 90.0, 90.0]])) <Universe with 6 atoms> >>> analysis = PairDistances.from_spec(universe, spec, whole) >>> analysis.genomic_positions, analysis.cutoff, analysis.periodic (array([1, 3, 5]), 3.0, (True, True, True)) >>> analysis.run().results['distMatTFoci'][0] array([[1. , 2. , 2.82842712], [0. , 3. , 2. ], [0. , 0. , 5. ]])
- classmethod get_supported_backends()[source]#
The backends
run()accepts:'serial','multiprocessing', and'dask'.Examples
>>> PairDistances.get_supported_backends() ('serial', 'multiprocessing', 'dask')
- save(save_to, name)[source]#
Save each quantity’s array as
<name>-<quantity><species>.npy.Added in version 0.7.0.
- Parameters:
save_to (
str|os.PathLike[str]) – An existing directory.name (
str) – The artifact’s name,<parser.name>-<parser.group>in the studies, such as'epss5...ens1-bug'.
- Returns:
The files written: the distance matrices, the contact matrices, the bonds histograms, and the clusters histograms.
- Return type:
- Raises:
RuntimeError – If
run()has not been called.
Examples
>>> import tempfile >>> import MDAnalysis as mda >>> import numpy as np >>> universe = mda.Universe.empty(2, trajectory=True) >>> universe.atoms.positions = np.array([[0.0, 0.0, 0.0], ... [0.0, 0.0, 3.0]]) >>> analysis = PairDistances(universe.atoms, 1.0, [0, 4]).run() >>> with tempfile.TemporaryDirectory() as tmp: ... paths = analysis.save(tmp, 'N2ens1-bug') ... len(paths), paths[0].name, np.load(paths[2]).tolist() (4, 'N2ens1-bug-distMatTFoci.npy', [[2, 0]])