source: sasmodels/explore/realspace.py @ cfa28d3

core_shell_microgelsmagnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since cfa28d3 was cfa28d3, checked in by Paul Kienzle <pkienzle@…>, 6 years ago

add monte carlo calculator as explore/realspace.py

  • Property mode set to 100644
File size: 15.5 KB
Line 
1from __future__ import division, print_function
2
3import time
4from copy import copy
5
6import numpy as np
7from numpy import pi, radians, sin, cos, sqrt
8from numpy.random import poisson, uniform
9from scipy.integrate import simps
10from scipy.special import j1 as J1
11
12# Definition of rotation matrices comes from wikipedia:
13#    https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations
14def Rx(angle):
15    """Construct a matrix to rotate points about *x* by *angle* degrees."""
16    a = radians(angle)
17    R = [[1, 0, 0],
18         [0, +cos(a), -sin(a)],
19         [0, +sin(a), +cos(a)]]
20    return np.matrix(R)
21
22def Ry(angle):
23    """Construct a matrix to rotate points about *y* by *angle* degrees."""
24    a = radians(angle)
25    R = [[+cos(a), 0, +sin(a)],
26         [0, 1, 0],
27         [-sin(a), 0, +cos(a)]]
28    return np.matrix(R)
29
30def Rz(angle):
31    """Construct a matrix to rotate points about *z* by *angle* degrees."""
32    a = radians(angle)
33    R = [[+cos(a), -sin(a), 0],
34         [+sin(a), +cos(a), 0],
35         [0, 0, 1]]
36    return np.matrix(R)
37
38def rotation(theta, phi, psi):
39    """
40    Apply the jitter transform to a set of points.
41
42    Points are stored in a 3 x n numpy matrix, not a numpy array or tuple.
43    """
44    return Rx(phi)*Ry(theta)*Rz(psi)
45
46class Shape:
47    rotation = np.matrix([[1., 0, 0], [0, 1, 0], [0, 0, 1]])
48    center = np.array([0., 0., 0.])[:, None]
49    r_max = None
50
51    def volume(self):
52        # type: () -> float
53        raise NotImplementedError()
54
55    def sample(self, density):
56        # type: (float) -> np.ndarray[N], np.ndarray[N, 3]
57        raise NotImplementedError()
58
59    def rotate(self, theta, phi, psi):
60        self.rotation = rotation(theta, phi, psi) * self.rotation
61        return self
62
63    def shift(self, x, y, z):
64        self.center = self.center + np.array([x, y, z])[:, None]
65        return self
66
67    def _adjust(self, points):
68        points = np.asarray(self.rotation * np.matrix(points.T)) + self.center
69        return points.T
70
71    def r_bins(self, q, over_sampling=1, r_step=0.):
72        r_max = min(2 * pi / q[0], self.r_max)
73        if r_step == 0.:
74            r_step = 2 * pi / q[-1] / over_sampling
75        #r_step = 0.01
76        return np.arange(r_step, r_max, r_step)
77
78class Composite(Shape):
79    def __init__(self, shapes, center=(0, 0, 0), orientation=(0, 0, 0)):
80        self.shapes = shapes
81        self.rotate(*orientation)
82        self.shift(*center)
83
84        # Find the worst case distance between any two points amongst a set
85        # of shapes independent of orientation.  This could easily be a
86        # factor of two worse than necessary, e.g., a pair of thin rods
87        # end-to-end vs the same pair side-by-side.
88        distances = [((s1.r_max + s2.r_max)/2
89                      + sqrt(np.sum((s1.center - s2.center)**2)))
90                     for s1 in shapes
91                     for s2 in shapes]
92        self.r_max = max(distances + [s.r_max for s in shapes])
93
94    def volume(self):
95        return sum(shape.volume() for shape in self.shapes)
96
97    def sample(self, density):
98        values, points = zip(*(shape.sample(density) for shape in self.shapes))
99        return np.hstack(values), self._adjust(np.vstack(points))
100
101class Box(Shape):
102    def __init__(self, a, b, c,
103                 value, center=(0, 0, 0), orientation=(0, 0, 0)):
104        self.value = np.asarray(value)
105        self.rotate(*orientation)
106        self.shift(*center)
107        self.a, self.b, self.c = a, b, c
108        self._scale = np.array([a/2, b/2, c/2])[None, :]
109        self.r_max = sqrt(a**2 + b**2 + c**2)
110
111    def volume(self):
112        return self.a*self.b*self.c
113
114    def sample(self, density):
115        num_points = poisson(density*self.a*self.b*self.c)
116        points = self._scale*uniform(-1, 1, size=(num_points, 3))
117        values = self.value.repeat(points.shape[0])
118        return values, self._adjust(points)
119
120class EllipticalCylinder(Shape):
121    def __init__(self, ra, rb, length,
122                 value, center=(0, 0, 0), orientation=(0, 0, 0)):
123        self.value = np.asarray(value)
124        self.rotate(*orientation)
125        self.shift(*center)
126        self.ra, self.rb, self.length = ra, rb, length
127        self._scale = np.array([ra, rb, length/2])[None, :]
128        self.r_max = sqrt(4*max(ra, rb)**2 + length**2)
129
130    def volume(self):
131        return pi*self.ra*self.rb*self.length
132
133    def sample(self, density):
134        # density of the bounding box
135        num_points = poisson(density*4*self.ra*self.rb*self.length)
136        points = uniform(-1, 1, size=(num_points, 3))
137        radius = points[:, 0]**2 + points[:, 1]**2
138        points = self._scale*points[radius <= 1]
139        values = self.value.repeat(points.shape[0])
140        return values, self._adjust(points)
141
142class TriaxialEllipsoid(Shape):
143    def __init__(self, ra, rb, rc,
144                 value, center=(0, 0, 0), orientation=(0, 0, 0)):
145        self.value = np.asarray(value)
146        self.rotate(*orientation)
147        self.shift(*center)
148        self.ra, self.rb, self.rc = ra, rb, rc
149        self._scale = np.array([ra, rb, rc])[None, :]
150        self.r_max = 2*max(ra, rb, rc)
151
152    def volume(self):
153        return 4*pi/3 * self.ra * self.rb * self.rc
154
155    def sample(self, density):
156        # randomly sample from a box of side length 2*r, excluding anything
157        # not in the ellipsoid
158        num_points = poisson(density*8*self.ra*self.rb*self.rc)
159        points = uniform(-1, 1, size=(num_points, 3))
160        radius = np.sum(points**2, axis=1)
161        points = self._scale*points[radius <= 1]
162        values = self.value.repeat(points.shape[0])
163        return values, self._adjust(points)
164
165class Helix(Shape):
166    def __init__(self, helix_radius, helix_pitch, tube_radius, tube_length,
167                 value, center=(0, 0, 0), orientation=(0, 0, 0)):
168        self.value = np.asarray(value)
169        self.rotate(*orientation)
170        self.shift(*center)
171        self.helix_radius, self.helix_pitch = helix_radius, helix_pitch
172        self.tube_radius, self.tube_length = tube_radius, tube_length
173        helix_length = helix_pitch * tube_length/sqrt(helix_radius**2 + helix_pitch**2)
174        self.r_max = sqrt((2*helix_radius + 2*tube_radius)*2
175                          + (helix_length + 2*tube_radius)**2)
176
177    def volume(self):
178        # small tube radius approximation; for larger tubes need to account
179        # for the fact that the inner length is much shorter than the outer
180        # length
181        return pi*self.tube_radius**2*self.tube_length
182
183    def points(self, density):
184        num_points = poisson(density*4*self.tube_radius**2*self.tube_length)
185        points = uniform(-1, 1, size=(num_points, 3))
186        radius = points[:, 0]**2 + points[:, 1]**2
187        points = points[radius <= 1]
188
189        # Based on math stackexchange answer by Jyrki Lahtonen
190        #     https://math.stackexchange.com/a/461637
191        # with helix along z rather than x [so tuples in answer are (z, x, y)]
192        # and with random points in the cross section (p1, p2) rather than
193        # uniform points on the surface (cos u, sin u).
194        a, R = self.tube_radius, self.helix_radius
195        h = self.helix_pitch
196        scale = 1/sqrt(R**2 + h**2)
197        t = points[:, 3] * (self.tube_length * scale/2)
198        cos_t, sin_t = cos(t), sin(t)
199
200        # rx = R*cos_t
201        # ry = R*sin_t
202        # rz = h*t
203        # nx = -a * cos_t * points[:, 1]
204        # ny = -a * sin_t * points[:, 1]
205        # nz = 0
206        # bx = (a * h/scale) * sin_t * points[:, 2]
207        # by = (-a * h/scale) * cos_t * points[:, 2]
208        # bz = a*R/scale
209        # x = rx + nx + bx
210        # y = ry + ny + by
211        # z = rz + nz + bz
212        u, v = (R - a*points[:, 1]), (a * h/scale)*points[:, 2]
213        x = u * cos_t + v * sin_t
214        y = u * sin_t - v * cos_t
215        z = a*R/scale + h * t
216
217        points = np.hstack((x, y, z))
218        values = self.value.repeat(points.shape[0])
219        return values, self._adjust(points)
220
221def _calc_Pr_nonuniform(r, rho, points):
222    # Make Pr a little be bigger than necessary so that only distances
223    # min < d < max end up in Pr
224    n_max = len(r)+1
225    extended_Pr = np.zeros(n_max+1, 'd')
226    # r refers to bin centers; find corresponding bin edges
227    bins = bin_edges(r)
228    t_next = time.clock() + 3
229    for k, rho_k in enumerate(rho[:-1]):
230        distance = sqrt(np.sum((points[k] - points[k+1:])**2, axis=1))
231        weights = rho_k * rho[k+1:]
232        index = np.searchsorted(bins, distance)
233        # Note: indices may be duplicated, so "Pr[index] += w" will not work!!
234        extended_Pr += np.bincount(index, weights, n_max+1)
235        t = time.clock()
236        if t > t_next:
237            t_next = t + 3
238            print("processing %d of %d"%(k, len(rho)-1))
239    Pr = extended_Pr[1:-1]
240    return Pr / Pr.max()
241
242def calc_Pr(r, rho, points):
243    # P(r) with uniform steps in r is 3x faster; check if we are uniform
244    # before continuing
245    if np.max(np.abs(np.diff(r) - r[0])) > r[0]*0.01:
246        return _calc_Pr_nonuniform(r, rho, points)
247
248    # Make Pr a little be bigger than necessary so that only distances
249    # min < d < max end up in Pr
250    n_max = len(r)
251    extended_Pr = np.zeros(n_max+1, 'd')
252    t0 = time.clock()
253    t_next = t0 + 3
254    row_zero = np.zeros(len(rho), 'i')
255    for k, rho_k in enumerate(rho[:-1]):
256        distances = sqrt(np.sum((points[k] - points[k+1:])**2, axis=1))
257        weights = rho_k * rho[k+1:]
258        index = np.minimum(np.asarray(distances/r[0], 'i'), n_max)
259        # Note: indices may be duplicated, so "Pr[index] += w" will not work!!
260        extended_Pr += np.bincount(index, weights, n_max+1)
261        t = time.clock()
262        if t > t_next:
263            t_next = t + 3
264            print("processing %d of %d"%(k, len(rho)-1))
265    #print("time py:", time.clock() - t0)
266    Pr = extended_Pr[:-1]
267    # Make Pr independent of sampling density.  The factor of 2 comes because
268    # we are only accumulating the upper triangular distances.
269    #Pr = Pr * 2 / len(rho)**2
270    return Pr / Pr.max()
271
272    # Can get an additional 2x by going to C.  Cuda/OpenCL will allow even
273    # more speedup, though still bounded by the n^2 cose.
274    """
275void pdfcalc(int n, const double *pts, const double *rho,
276             int nPr, double *Pr, double rstep)
277{
278  int i,j;
279
280  for (i=0; i<n-2; i++) {
281    for (j=i+1; j<=n-1; j++) {
282      const double dxx=pts[3*i]-pts[3*j];
283      const double dyy=pts[3*i+1]-pts[3*j+1];
284      const double dzz=pts[3*i+2]-pts[3*j+2];
285      const double d=sqrt(dxx*dxx+dyy*dyy+dzz*dzz);
286      const int k=rint(d/rstep);
287      if (k < nPr) Pr[k]+=rho[i]*rho[j];
288    }
289  }
290}
291"""
292
293def j0(x):
294    return np.sinc(x/np.pi)
295
296def calc_Iq(q, r, Pr):
297    Iq = np.array([simps(Pr * j0(qk*r), r) for qk in q])
298    #Iq = np.array([np.trapz(Pr * j0(qk*r), r) for qk in q])
299    Iq /= Iq[0]
300    return Iq
301
302# NOTE: copied from sasmodels/resolution.py
303def bin_edges(x):
304    """
305    Determine bin edges from bin centers, assuming that edges are centered
306    between the bins.
307
308    Note: this uses the arithmetic mean, which may not be appropriate for
309    log-scaled data.
310    """
311    if len(x) < 2 or (np.diff(x) < 0).any():
312        raise ValueError("Expected bins to be an increasing set")
313    edges = np.hstack([
314        x[0]  - 0.5*(x[1]  - x[0]),  # first point minus half first interval
315        0.5*(x[1:] + x[:-1]),        # mid points of all central intervals
316        x[-1] + 0.5*(x[-1] - x[-2]), # last point plus half last interval
317        ])
318    return edges
319
320def plot_calc(r, Pr, q, Iq, theory=None):
321    import matplotlib.pyplot as plt
322    plt.subplot(211)
323    plt.plot(r, Pr, '-', label="Pr")
324    plt.xlabel('r (A)')
325    plt.ylabel('Pr (1/A^2)')
326    plt.subplot(212)
327    plt.loglog(q, Iq, '-', label='from Pr')
328    plt.xlabel('q (1/A')
329    plt.ylabel('Iq')
330    if theory is not None:
331        plt.loglog(theory[0], theory[1], '-', label='analytic')
332        plt.legend()
333
334def plot_points(rho, points):
335    import mpl_toolkits.mplot3d
336    import matplotlib.pyplot as plt
337
338    ax = plt.axes(projection='3d')
339    try:
340        ax.axis('square')
341    except Exception:
342        pass
343    n = len(points)
344    index = np.random.choice(n, size=1000) if n > 1000 else slice(None, None)
345    ax.scatter(points[index, 0], points[index, 1], points[index, 2], c=rho[index])
346    #low, high = points.min(axis=0), points.max(axis=0)
347    #ax.axis([low[0], high[0], low[1], high[1], low[2], high[2]])
348    ax.autoscale(True)
349
350def sas_2J1x_x(x):
351    with np.errstate(all='ignore'):
352        retvalue = 2*J1(x)/x
353    retvalue[x == 0] = 1.
354    return retvalue
355
356def sas_3j1x_x(x):
357    """return 3*j1(x)/x"""
358    with np.errstate(all='ignore'):
359        retvalue = 3*(sin(x) - x*cos(x))/x**3
360    retvalue[x == 0.] = 1.
361    return retvalue
362
363def cylinder_Iq(q, radius, length):
364    height = length/2
365    Iq = np.empty_like(q)
366    theta = np.linspace(0.0, pi/2, 500)
367    for k, qk in enumerate(q):
368        qab, qc = qk*sin(theta), qk*cos(theta)
369        Iq[k] = simps((j0(qc*height)*sas_2J1x_x(qab*radius))**2 * sin(theta))
370    Iq = Iq/Iq[0]
371    return Iq
372
373def sphere_Iq(q, radius):
374    Iq = sas_3j1x_x(q*radius)**2
375    return Iq/Iq[0]
376
377def csbox_Iq(q, a, b, c, da, db, dc, slda, sldb, sldc, sld_core):
378    sld_solvent = 0
379    overlapping = False
380    dr0 = sld_core - sld_solvent
381    drA, drB, drC = slda-sld_solvent, sldb-sld_solvent, sldc-sld_solvent
382    tA, tB, tC = a + 2*da, b + 2*db, c + 2*dc
383
384    Iq = np.zeros_like(q)
385    for cos_alpha in np.linspace(0.0, 1.0, 100):
386        sin_alpha = sqrt(1.0-cos_alpha*cos_alpha)
387        qc = q*cos_alpha
388        siC = c*j0(c*qc/2)
389        siCt = tC*j0(tC*qc/2)
390        for beta in np.linspace(0.0, pi/2, 100):
391            qa, qb = q*sin_alpha*sin(beta), q*sin_alpha*cos(beta)
392            siA = a*j0(a*qa/2)
393            siB = b*j0(b*qb/2)
394            siAt = tA*j0(tA*qa/2)
395            siBt = tB*j0(tB*qb/2)
396            if overlapping:
397                Iq += (dr0*siA*siB*siC
398                       + drA*(siAt-siA)*siB*siC
399                       + drB*siAt*(siBt-siB)*siC
400                       + drC*siAt*siBt*(siCt-siC))**2
401            else:
402                Iq += (dr0*siA*siB*siC
403                       + drA*(siAt-siA)*siB*siC
404                       + drB*siA*(siBt-siB)*siC
405                       + drC*siA*siB*(siCt-siC))**2
406    return Iq/Iq[0]
407
408def check_shape(shape, fn=None):
409    rho_solvent = 0
410    q = np.logspace(-3, 0, 200)
411    r = shape.r_bins(q, r_step=0.01)
412    sampling_density = 15000 / shape.volume()
413    rho, points = shape.sample(sampling_density)
414    Pr = calc_Pr(r, rho-rho_solvent, points)
415    Iq = calc_Iq(q, r, Pr)
416    theory = (q, fn(q)) if fn is not None else None
417
418    import pylab
419    #plot_points(rho, points); pylab.figure()
420    plot_calc(r, Pr, q, Iq, theory=theory)
421    pylab.show()
422
423def check_cylinder(radius=25, length=125, rho=2.):
424    shape = EllipticalCylinder(radius, radius, length, rho)
425    fn = lambda q: cylinder_Iq(q, radius, length)
426    check_shape(shape, fn)
427
428def check_sphere(radius=125, rho=2):
429    shape = TriaxialEllipsoid(radius, radius, radius, rho)
430    fn = lambda q: sphere_Iq(q, radius)
431    check_shape(shape, fn)
432
433def check_csbox(a=10, b=20, c=30, da=1, db=2, dc=3, slda=1, sldb=2, sldc=3, sld_core=4):
434    core = Box(a, b, c, sld_core)
435    side_a = Box(da, b, c, slda, center=((a+da)/2, 0, 0))
436    side_b = Box(a, db, c, sldb, center=(0, (b+db)/2, 0))
437    side_c = Box(a, b, dc, sldc, center=(0, 0, (c+dc)/2))
438    side_a2 = copy(side_a).shift(-a-da, 0, 0)
439    side_b2 = copy(side_b).shift(0, -b-db, 0)
440    side_c2 = copy(side_c).shift(0, 0, -c-dc)
441    shape = Composite((core, side_a, side_b, side_c, side_a2, side_b2, side_c2))
442    fn = lambda q: csbox_Iq(q, a, b, c, da, db, dc, slda, sldb, sldc, sld_core)
443    check_shape(shape, fn)
444
445if __name__ == "__main__":
446    check_cylinder(radius=10, length=40)
447    #check_sphere()
448    #check_csbox()
449    #check_csbox(da=100, db=200, dc=300)
Note: See TracBrowser for help on using the repository browser.