IMP logo
IMP Reference Guide  develop.7482b7c7af, 2026/12/05
The Integrative Modeling Platform
model_numpy.py
1## \example core/model_numpy.py
2# Demonstration using NumPy to manipulate IMP data.
3#
4
5import IMP.container
6import sys
7
8IMP.setup_from_argv(sys.argv, "model numpy")
9
10if not IMP.IMP_KERNEL_HAS_NUMPY:
11 print("IMP was not built with NumPy support.")
12 sys.exit(0)
13
14# Make 100 xyz particles randomly distributed in a cubic box
15m = IMP.Model()
18 IMP.algebra.Vector3D(10,10,10))
19for i in range(100):
20 p = m.add_particle("p")
21 sc.add(p)
24 d.set_coordinates_are_optimized(True)
25
26# Get all pairs of particles that are close to each other
28m.update()
29
30# contents is a NumPy 2xN array of the indices of each close particle pair
31contents = nbl.get_contents()
32
33# Get direct access to the coordinates and radii of all particles in the Model.
34# These are NumPy views, not copies; they share memory with the Model. This
35# allows us very efficient read-write access to the data, with a caveat: if
36# the Model memory is reallocated (typically when particles or attributes are
37# added) any views become invalid, so we should not keep them around long-term.
38# These arrays are indexed by particle indices.
39xyz, r = m.get_spheres_numpy()
40
41import numpy
42
43# Once we have coordinates and particle indices, we can use any NumPy
44# function on them. Here we calculate the Cartesian distance between each
45# pair of particles in the close pair container.
46dists = numpy.linalg.norm(numpy.diff(xyz[contents], axis=1), axis=2).flatten()
47
48print("Distribution of center-center particle distances:")
49print("Min %.2f Max %.2f Mean %.2f" % (dists.min(), dists.max(), dists.mean()))
Class for storing model, its restraints, constraints, and particles.
Definition Model.h:111
Return all close unordered pairs of particles taken from the SingletonContainer.
static XYZR setup_particle(Model *m, ParticleIndex pi)
Definition XYZR.h:48
VectorD< 3 > Vector3D
Definition VectorD.h:407
VectorD< D > get_random_vector_in(const BoundingBoxD< D > &bb)
Generate a random vector in a box with uniform density.
Various classes to hold sets of particles.
void setup_from_argv(int argc, char **argv, std::string description)
Parse the command line flags and return the positional arguments.