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
RevLine 
[baa79c2]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
[a738209]14from __future__ import print_function
15
[7ae2b7f]16import numpy as np  # type: ignore
[d4c33d6]17from numpy import pi, cos, sin, radians
[9eb3632]18
19try:
20    np.meshgrid([])
21    meshgrid = np.meshgrid
[725ee36]22except Exception:
[9eb3632]23    # CRUFT: np.meshgrid requires multiple vectors
24    def meshgrid(*args):
[110f69c]25        """See docs from a recent version of numpy"""
[9eb3632]26        if len(args) > 1:
27            return np.meshgrid(*args)
28        else:
29            return [np.asarray(v) for v in args]
[7ae2b7f]30
31try:
[d4c33d6]32    from typing import List, Tuple, Sequence
[7ae2b7f]33except ImportError:
34    pass
[8d62008]35else:
36    from .modelinfo import ModelInfo
[d4c33d6]37    from .modelinfo import ParameterTable
[7ae2b7f]38
[d2fc9a4]39
40class CallDetails(object):
[baa79c2]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
[d4c33d6]57    with a range of latitude values needs to be scaled by this circumference.
[baa79c2]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    """
[7ae2b7f]64    parts = None  # type: List["CallDetails"]
[d2fc9a4]65    def __init__(self, model_info):
[8d62008]66        # type: (ModelInfo) -> None
[d2fc9a4]67        parameters = model_info.parameters
68        max_pd = parameters.max_pd
[a738209]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]
[bde38b5]75        #   num_eval           total length of pd loop
76        #   num_weights        total length of the weight vector
[a738209]77        #   num_active         number of pd params
78        #   theta_par          parameter number for theta parameter
[bde38b5]79        self.buffer = np.empty(4*max_pd + 4, 'i4')
[d2fc9a4]80
81        # generate views on different parts of the array
[baa79c2]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]
[d2fc9a4]86
87        # theta_par is fixed
[a738209]88        self.theta_par = parameters.theta_offset
[d2fc9a4]89
[bde38b5]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
[d2fc9a4]101    @property
[baa79c2]102    def pd_par(self):
103        """List of polydisperse parameters"""
104        return self._pd_par
[d2fc9a4]105
106    @property
[baa79c2]107    def pd_length(self):
108        """Number of weights for each polydisperse parameter"""
109        return self._pd_length
[d2fc9a4]110
111    @property
[baa79c2]112    def pd_offset(self):
113        """Offsets for the individual weight vectors in the set of weights"""
114        return self._pd_offset
[d2fc9a4]115
116    @property
[baa79c2]117    def pd_stride(self):
118        """Stride in the pd mesh for each pd dimension"""
119        return self._pd_stride
[d2fc9a4]120
121    @property
[bde38b5]122    def num_eval(self):
[baa79c2]123        """Total size of the pd mesh"""
124        return self.buffer[-4]
125
[bde38b5]126    @num_eval.setter
127    def num_eval(self, v):
[40a87fa]128        """Total size of the pd mesh"""
[baa79c2]129        self.buffer[-4] = v
[d2fc9a4]130
131    @property
[bde38b5]132    def num_weights(self):
[baa79c2]133        """Total length of all the weight vectors"""
134        return self.buffer[-3]
135
[bde38b5]136    @num_weights.setter
137    def num_weights(self, v):
[40a87fa]138        """Total length of all the weight vectors"""
[baa79c2]139        self.buffer[-3] = v
[d2fc9a4]140
141    @property
[baa79c2]142    def num_active(self):
143        """Number of active polydispersity loops"""
144        return self.buffer[-2]
145
[d2fc9a4]146    @num_active.setter
[baa79c2]147    def num_active(self, v):
[40a87fa]148        """Number of active polydispersity loops"""
[baa79c2]149        self.buffer[-2] = v
[d2fc9a4]150
151    @property
[baa79c2]152    def theta_par(self):
153        """Location of the theta parameter in the parameter vector"""
154        return self.buffer[-1]
155
[a738209]156    @theta_par.setter
[baa79c2]157    def theta_par(self, v):
[40a87fa]158        """Location of the theta parameter in the parameter vector"""
[baa79c2]159        self.buffer[-1] = v
[d2fc9a4]160
[bde38b5]161    def show(self, values=None):
[baa79c2]162        """Print the polydispersity call details to the console"""
[bde38b5]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):
[6dc78e4]181    # type: (ModelInfo, np.ndarray, np.ndarray, int) -> CallDetails
[baa79c2]182    """
183    Return a :class:`CallDetails` object for a polydisperse calculation
[bde38b5]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.
[baa79c2]190    """
[bde38b5]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
[6aee3ab]196    # Check that we aren't using too many polydispersity loops
[bde38b5]197    num_active = np.sum(length > 1)
[9eb3632]198    max_pd = model_info.parameters.max_pd
199    if num_active > max_pd:
[d2fc9a4]200        raise ValueError("Too many polydisperse parameters")
201
[bde38b5]202    # Decreasing list of polydpersity lengths
[a738209]203    # Note: the reversing view, x[::-1], does not require a copy
[bde38b5]204    idx = np.argsort(length)[::-1][:max_pd]
205    pd_stride = np.cumprod(np.hstack((1, length[idx])))
[d2fc9a4]206
207    call_details = CallDetails(model_info)
[9eb3632]208    call_details.pd_par[:max_pd] = idx
[bde38b5]209    call_details.pd_length[:max_pd] = length[idx]
210    call_details.pd_offset[:max_pd] = offset[idx]
[9eb3632]211    call_details.pd_stride[:max_pd] = pd_stride[:-1]
[bde38b5]212    call_details.num_eval = pd_stride[-1]
213    call_details.num_weights = num_weights
[d2fc9a4]214    call_details.num_active = num_active
[bde38b5]215    call_details.length = length
216    call_details.offset = offset
[d2fc9a4]217    #call_details.show()
218    return call_details
[9eb3632]219
220
[bde38b5]221ZEROS = tuple([0.]*31)
[8698a0d]222def make_kernel_args(kernel, mesh):
[9eb3632]223    # type: (Kernel, Tuple[List[np.ndarray], List[np.ndarray]]) -> Tuple[CallDetails, np.ndarray, bool]
224    """
[8698a0d]225    Converts (value, dispersity, weight) for each parameter into kernel pars.
[9eb3632]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    """
[bde38b5]232    npars = kernel.info.parameters.npars
233    nvalues = kernel.info.parameters.nvalues
[110f69c]234    scalars = [value for value, _dispersity, _weight in mesh]
[77bfb5f]235    # skipping scale and background when building values and weights
[110f69c]236    _values, dispersity, weights = zip(*mesh[2:npars+2]) if npars else ((), (), ())
[767dca8]237    #weights = correct_theta_weights(kernel.info.parameters, dispersity, weights)
[bde38b5]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
[8698a0d]242    data_len = nvalues + 2*sum(len(v) for v in dispersity)
[bde38b5]243    extra = (32 - data_len%32)%32
[8698a0d]244    data = np.hstack((scalars,) + dispersity + weights + ZEROS[:extra])
[bde38b5]245    data = data.astype(kernel.dtype)
[9eb3632]246    is_magnetic = convert_magnetism(kernel.info.parameters, data)
247    #call_details.show()
248    return call_details, data, is_magnetic
249
[9e771a3]250def correct_theta_weights(parameters, dispersity, weights):
[d4c33d6]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
[9e771a3]254    the cosine weighting required for polar integration is preserved.
[77bfb5f]255
[9e771a3]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
[d4c33d6]266    """
[9e771a3]267    # TODO: explain in a comment why scale and background are missing
[77bfb5f]268    # Apparently the parameters.theta_offset similarly skips scale and
[9e771a3]269    # and background, so the indexing works out, but they are still shipped
270    # to the kernel, so we need to add two there.
[d4c33d6]271    if parameters.theta_offset >= 0:
[77bfb5f]272        index = parameters.theta_offset
[9e771a3]273        theta = dispersity[index]
274        # TODO: modify the dispersity vector to avoid the theta=-90,90,270,...
275        theta_weight = abs(cos(radians(theta)))
[2bccb5a]276        weights = tuple(theta_weight*w if k == index else w
277                        for k, w in enumerate(weights))
[d4c33d6]278    return weights
279
[bde38b5]280
[9eb3632]281def convert_magnetism(parameters, values):
[d4c33d6]282    # type: (ParameterTable, Sequence[np.ndarray]) -> bool
[9eb3632]283    """
[baa79c2]284    Convert magnetism values from polar to rectangular coordinates.
[9eb3632]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)
[110f69c]290    scale = mag[:, 0]
[40a87fa]291    if np.any(scale):
[d4c33d6]292        theta, phi = radians(mag[:, 1]), radians(mag[:, 2])
[9eb3632]293        cos_theta = cos(theta)
[40a87fa]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
[9eb3632]297        return True
298    else:
299        return False
[bde38b5]300
301
[8698a0d]302def dispersion_mesh(model_info, mesh):
[bde38b5]303    # type: (ModelInfo) -> Tuple[List[np.ndarray], List[np.ndarray]]
304    """
305    Create a mesh grid of dispersion parameters and weights.
306
[8698a0d]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.
[d4c33d6]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
[8698a0d]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.
[d4c33d6]316
[bde38b5]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    """
[ce99754]321    _, dispersity, weight = zip(*mesh)
[6dc78e4]322    #weight = [w if len(w)>0 else [1.] for w in weight]
[bde38b5]323    weight = np.vstack([v.flatten() for v in meshgrid(*weight)])
324    weight = np.prod(weight, axis=0)
[8698a0d]325    dispersity = [v.flatten() for v in meshgrid(*dispersity)]
[bde38b5]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:
[8698a0d]332            pars.append(np.vstack(dispersity[offset:offset+n])
333                        if n > 1 else dispersity[offset])
[bde38b5]334            offset += n
[8698a0d]335        dispersity = pars
336    return dispersity, weight
Note: See TracBrowser for help on using the repository browser.