source: sasmodels/sasmodels/details.py @ 110f69c

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

lint

  • Property mode set to 100644
File size: 13.2 KB
Line 
1"""
2Kernel Call Details
3===================
4
5When calling sas computational kernels with polydispersity there are a
6number of details that need to be sent to the caller.  This includes the
7list of polydisperse parameters, the number of points in the polydispersity
8weight distribution, and which parameter is the "theta" parameter for
9polar coordinate integration.  The :class:`CallDetails` object maintains
10this data.  Use :func:`build_details` to build a *details* object which
11can be passed to one of the computational kernels.
12"""
13
14from __future__ import print_function
15
16import numpy as np  # type: ignore
17from numpy import pi, cos, sin, radians
18
19try:
20    np.meshgrid([])
21    meshgrid = np.meshgrid
22except Exception:
23    # CRUFT: np.meshgrid requires multiple vectors
24    def meshgrid(*args):
25        """See docs from a recent version of numpy"""
26        if len(args) > 1:
27            return np.meshgrid(*args)
28        else:
29            return [np.asarray(v) for v in args]
30
31try:
32    from typing import List, Tuple, Sequence
33except ImportError:
34    pass
35else:
36    from .modelinfo import ModelInfo
37    from .modelinfo import ParameterTable
38
39
40class CallDetails(object):
41    """
42    Manage the polydispersity information for the kernel call.
43
44    Conceptually, a polydispersity calculation is an integral over a mesh
45    in n-D space where n is the number of polydisperse parameters.  In order
46    to keep the program responsive, and not crash the GPU, only a portion
47    of the mesh is computed at a time.  Meshes with a large number of points
48    will therefore require many calls to the polydispersity loop.  Restarting
49    a nested loop in the middle requires that the indices of the individual
50    mesh dimensions can be computed for the current loop location.  This
51    is handled by the *pd_stride* vector, with n//stride giving the loop
52    index and n%stride giving the position in the sub loops.
53
54    One of the parameters may be the latitude.  When integrating in polar
55    coordinates, the total circumference decreases as latitude varies from
56    pi r^2 at the equator to 0 at the pole, and the weight associated
57    with a range of latitude values needs to be scaled by this circumference.
58    This scale factor needs to be updated each time the theta value
59    changes.  *theta_par* indicates which of the values in the parameter
60    vector is the latitude parameter, or -1 if there is no latitude
61    parameter in the model.  In practice, the normalization term cancels
62    if the latitude is not a polydisperse parameter.
63    """
64    parts = None  # type: List["CallDetails"]
65    def __init__(self, model_info):
66        # type: (ModelInfo) -> None
67        parameters = model_info.parameters
68        max_pd = parameters.max_pd
69
70        # Structure of the call details buffer:
71        #   pd_par[max_pd]     pd params in order of length
72        #   pd_length[max_pd]  length of each pd param
73        #   pd_offset[max_pd]  offset of pd values in parameter array
74        #   pd_stride[max_pd]  index of pd value in loop = n//stride[k]
75        #   num_eval           total length of pd loop
76        #   num_weights        total length of the weight vector
77        #   num_active         number of pd params
78        #   theta_par          parameter number for theta parameter
79        self.buffer = np.empty(4*max_pd + 4, 'i4')
80
81        # generate views on different parts of the array
82        self._pd_par = self.buffer[0 * max_pd:1 * max_pd]
83        self._pd_length = self.buffer[1 * max_pd:2 * max_pd]
84        self._pd_offset = self.buffer[2 * max_pd:3 * max_pd]
85        self._pd_stride = self.buffer[3 * max_pd:4 * max_pd]
86
87        # theta_par is fixed
88        self.theta_par = parameters.theta_offset
89
90        # offset and length are for all parameters, not just pd parameters
91        # They are not sent to the kernel function, though they could be.
92        # They are used by the composite models (sum and product) to
93        # figure out offsets into the combined value list.
94        self.offset = None  # type: np.ndarray
95        self.length = None  # type: np.ndarray
96
97        # keep hold of ifno show() so we can break a values vector
98        # into the individual components
99        self.info = model_info
100
101    @property
102    def pd_par(self):
103        """List of polydisperse parameters"""
104        return self._pd_par
105
106    @property
107    def pd_length(self):
108        """Number of weights for each polydisperse parameter"""
109        return self._pd_length
110
111    @property
112    def pd_offset(self):
113        """Offsets for the individual weight vectors in the set of weights"""
114        return self._pd_offset
115
116    @property
117    def pd_stride(self):
118        """Stride in the pd mesh for each pd dimension"""
119        return self._pd_stride
120
121    @property
122    def num_eval(self):
123        """Total size of the pd mesh"""
124        return self.buffer[-4]
125
126    @num_eval.setter
127    def num_eval(self, v):
128        """Total size of the pd mesh"""
129        self.buffer[-4] = v
130
131    @property
132    def num_weights(self):
133        """Total length of all the weight vectors"""
134        return self.buffer[-3]
135
136    @num_weights.setter
137    def num_weights(self, v):
138        """Total length of all the weight vectors"""
139        self.buffer[-3] = v
140
141    @property
142    def num_active(self):
143        """Number of active polydispersity loops"""
144        return self.buffer[-2]
145
146    @num_active.setter
147    def num_active(self, v):
148        """Number of active polydispersity loops"""
149        self.buffer[-2] = v
150
151    @property
152    def theta_par(self):
153        """Location of the theta parameter in the parameter vector"""
154        return self.buffer[-1]
155
156    @theta_par.setter
157    def theta_par(self, v):
158        """Location of the theta parameter in the parameter vector"""
159        self.buffer[-1] = v
160
161    def show(self, values=None):
162        """Print the polydispersity call details to the console"""
163        print("===== %s details ===="%self.info.name)
164        print("num_active:%d  num_eval:%d  num_weights:%d  theta=%d"
165              % (self.num_active, self.num_eval, self.num_weights, self.theta_par))
166        if self.pd_par.size:
167            print("pd_par", self.pd_par)
168            print("pd_length", self.pd_length)
169            print("pd_offset", self.pd_offset)
170            print("pd_stride", self.pd_stride)
171        if values is not None:
172            nvalues = self.info.parameters.nvalues
173            print("scale, background", values[:2])
174            print("val", values[2:nvalues])
175            print("pd", values[nvalues:nvalues+self.num_weights])
176            print("wt", values[nvalues+self.num_weights:nvalues+2*self.num_weights])
177            print("offsets", self.offset)
178
179
180def make_details(model_info, length, offset, num_weights):
181    # type: (ModelInfo, np.ndarray, np.ndarray, int) -> CallDetails
182    """
183    Return a :class:`CallDetails` object for a polydisperse calculation
184    of the model defined by *model_info*.  Polydispersity is defined by
185    the *length* of the polydispersity distribution for each parameter
186    and the *offset* of the distribution in the polydispersity array.
187    Monodisperse parameters should use a polydispersity length of one
188    with weight 1.0. *num_weights* is the total length of the polydispersity
189    array.
190    """
191    #pars = model_info.parameters.call_parameters[2:model_info.parameters.npars+2]
192    #print(", ".join(str(i)+"-"+p.id for i,p in enumerate(pars)))
193    #print("len:",length)
194    #print("off:",offset)
195
196    # Check that we aren't using too many polydispersity loops
197    num_active = np.sum(length > 1)
198    max_pd = model_info.parameters.max_pd
199    if num_active > max_pd:
200        raise ValueError("Too many polydisperse parameters")
201
202    # Decreasing list of polydpersity lengths
203    # Note: the reversing view, x[::-1], does not require a copy
204    idx = np.argsort(length)[::-1][:max_pd]
205    pd_stride = np.cumprod(np.hstack((1, length[idx])))
206
207    call_details = CallDetails(model_info)
208    call_details.pd_par[:max_pd] = idx
209    call_details.pd_length[:max_pd] = length[idx]
210    call_details.pd_offset[:max_pd] = offset[idx]
211    call_details.pd_stride[:max_pd] = pd_stride[:-1]
212    call_details.num_eval = pd_stride[-1]
213    call_details.num_weights = num_weights
214    call_details.num_active = num_active
215    call_details.length = length
216    call_details.offset = offset
217    #call_details.show()
218    return call_details
219
220
221ZEROS = tuple([0.]*31)
222def make_kernel_args(kernel, mesh):
223    # type: (Kernel, Tuple[List[np.ndarray], List[np.ndarray]]) -> Tuple[CallDetails, np.ndarray, bool]
224    """
225    Converts (value, dispersity, weight) for each parameter into kernel pars.
226
227    Returns a CallDetails object indicating the polydispersity, a data object
228    containing the different values, and the magnetic flag indicating whether
229    any magnetic magnitudes are non-zero. Magnetic vectors (M0, phi, theta) are
230    converted to rectangular coordinates (mx, my, mz).
231    """
232    npars = kernel.info.parameters.npars
233    nvalues = kernel.info.parameters.nvalues
234    scalars = [value for value, _dispersity, _weight in mesh]
235    # skipping scale and background when building values and weights
236    _values, dispersity, weights = zip(*mesh[2:npars+2]) if npars else ((), (), ())
237    #weights = correct_theta_weights(kernel.info.parameters, dispersity, weights)
238    length = np.array([len(w) for w in weights])
239    offset = np.cumsum(np.hstack((0, length)))
240    call_details = make_details(kernel.info, length, offset[:-1], offset[-1])
241    # Pad value array to a 32 value boundaryd
242    data_len = nvalues + 2*sum(len(v) for v in dispersity)
243    extra = (32 - data_len%32)%32
244    data = np.hstack((scalars,) + dispersity + weights + ZEROS[:extra])
245    data = data.astype(kernel.dtype)
246    is_magnetic = convert_magnetism(kernel.info.parameters, data)
247    #call_details.show()
248    return call_details, data, is_magnetic
249
250def correct_theta_weights(parameters, dispersity, weights):
251    # type: (ParameterTable, Sequence[np.ndarray], Sequence[np.ndarray]) -> Sequence[np.ndarray]
252    """
253    If there is a theta parameter, update the weights of that parameter so that
254    the cosine weighting required for polar integration is preserved.
255
256    Avoid evaluation strictly at the pole, which would otherwise send the
257    weight to zero.  This is probably not a problem in practice (if dispersity
258    is +/- 90, then you probably should be using a 1-D model of the circular
259    average).
260
261    Note: scale and background parameters are not include in the tuples for
262    dispersity and weights, so index is parameters.theta_offset, not
263    parameters.theta_offset+2
264
265    Returns updated weights vectors
266    """
267    # TODO: explain in a comment why scale and background are missing
268    # Apparently the parameters.theta_offset similarly skips scale and
269    # and background, so the indexing works out, but they are still shipped
270    # to the kernel, so we need to add two there.
271    if parameters.theta_offset >= 0:
272        index = parameters.theta_offset
273        theta = dispersity[index]
274        # TODO: modify the dispersity vector to avoid the theta=-90,90,270,...
275        theta_weight = abs(cos(radians(theta)))
276        weights = tuple(theta_weight*w if k == index else w
277                        for k, w in enumerate(weights))
278    return weights
279
280
281def convert_magnetism(parameters, values):
282    # type: (ParameterTable, Sequence[np.ndarray]) -> bool
283    """
284    Convert magnetism values from polar to rectangular coordinates.
285
286    Returns True if any magnetism is present.
287    """
288    mag = values[parameters.nvalues-3*parameters.nmagnetic:parameters.nvalues]
289    mag = mag.reshape(-1, 3)
290    scale = mag[:, 0]
291    if np.any(scale):
292        theta, phi = radians(mag[:, 1]), radians(mag[:, 2])
293        cos_theta = cos(theta)
294        mag[:, 0] = scale*cos_theta*cos(phi)  # mx
295        mag[:, 1] = scale*sin(theta)  # my
296        mag[:, 2] = -scale*cos_theta*sin(phi)  # mz
297        return True
298    else:
299        return False
300
301
302def dispersion_mesh(model_info, mesh):
303    # type: (ModelInfo) -> Tuple[List[np.ndarray], List[np.ndarray]]
304    """
305    Create a mesh grid of dispersion parameters and weights.
306
307    *mesh* is a list of (value, dispersity, weights), where the values
308    are the individual parameter values, and (dispersity, weights) is
309    the distribution of parameter values.
310
311    Only the volume parameters should be included in this list.  Orientation
312    parameters do not affect the calculation of effective radius or volume
313    ratio.  This is convenient since it avoids the distinction between
314    value and dispersity that is present in orientation parameters but not
315    shape parameters.
316
317    Returns [p1,p2,...],w where pj is a vector of values for parameter j
318    and w is a vector containing the products for weights for each
319    parameter set in the vector.
320    """
321    _, dispersity, weight = zip(*mesh)
322    #weight = [w if len(w)>0 else [1.] for w in weight]
323    weight = np.vstack([v.flatten() for v in meshgrid(*weight)])
324    weight = np.prod(weight, axis=0)
325    dispersity = [v.flatten() for v in meshgrid(*dispersity)]
326    lengths = [par.length for par in model_info.parameters.kernel_parameters
327               if par.type == 'volume']
328    if any(n > 1 for n in lengths):
329        pars = []
330        offset = 0
331        for n in lengths:
332            pars.append(np.vstack(dispersity[offset:offset+n])
333                        if n > 1 else dispersity[offset])
334            offset += n
335        dispersity = pars
336    return dispersity, weight
Note: See TracBrowser for help on using the repository browser.