source: sasmodels/sasmodels/product.py @ c0131d44

core_shell_microgelsmagnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since c0131d44 was c0131d44, checked in by Torin Cooper-Bennun <torin.cooper-bennun@…>, 6 years ago

use parse_parameter to include fixed choices properly

  • Property mode set to 100644
File size: 15.0 KB
Line 
1"""
2Product model
3-------------
4
5The product model multiplies the structure factor by the form factor,
6modulated by the effective radius of the form.  The resulting model
7has a attributes of both the model description (with parameters, etc.)
8and the module evaluator (with call, release, etc.).
9
10To use it, first load form factor P and structure factor S, then create
11*make_product_info(P, S)*.
12"""
13from __future__ import print_function, division
14
15from collections import OrderedDict
16
17from copy import copy
18import numpy as np  # type: ignore
19
20from .modelinfo import ParameterTable, ModelInfo, Parameter, parse_parameter
21from .kernel import KernelModel, Kernel
22from .details import make_details, dispersion_mesh
23
24# pylint: disable=unused-import
25try:
26    from typing import Tuple, Callable
27except ImportError:
28    pass
29else:
30    from .modelinfo import ParameterSet
31# pylint: enable=unused-import
32
33# TODO: make estimates available to constraints
34#ESTIMATED_PARAMETERS = [
35#    ["est_radius_effective", "A", 0.0, [0, np.inf], "", "Estimated effective radius"],
36#    ["est_volume_ratio", "", 1.0, [0, np.inf], "", "Estimated volume ratio"],
37#]
38
39ER_ID = "radius_effective"
40VF_ID = "volfraction"
41
42def make_extra_pars(p_info):
43    pars = []
44    if p_info.have_Fq:
45        par = parse_parameter(
46                "structure_factor_mode",
47                "",
48                0,
49                [["P*S","P*(1+beta*(S-1))"]],
50                "",
51                "Structure factor calculation")
52        pars.append(par)
53    return pars
54
55# TODO: core_shell_sphere model has suppressed the volume ratio calculation
56# revert it after making VR and ER available at run time as constraints.
57def make_product_info(p_info, s_info):
58    # type: (ModelInfo, ModelInfo) -> ModelInfo
59    """
60    Create info block for product model.
61    """
62    # Make sure effective radius is the first parameter and
63    # make sure volume fraction is the second parameter of the
64    # structure factor calculator.  Structure factors should not
65    # have any magnetic parameters
66    if not len(s_info.parameters.kernel_parameters) >= 2:
67        raise TypeError("S needs {} and {} as its first parameters".format(ER_ID, VF_ID))
68    if not s_info.parameters.kernel_parameters[0].id == ER_ID:
69        raise TypeError("S needs {} as first parameter".format(ER_ID))
70    if not s_info.parameters.kernel_parameters[1].id == VF_ID:
71        raise TypeError("S needs {} as second parameter".format(VF_ID))
72    if not s_info.parameters.magnetism_index == []:
73        raise TypeError("S should not have SLD parameters")
74    p_id, p_name, p_pars = p_info.id, p_info.name, p_info.parameters
75    s_id, s_name, s_pars = s_info.id, s_info.name, s_info.parameters
76
77    # Create list of parameters for the combined model.  Skip the first
78    # parameter of S, which we verified above is effective radius.  If there
79    # are any names in P that overlap with those in S, modify the name in S
80    # to distinguish it.
81    p_set = set(p.id for p in p_pars.kernel_parameters)
82    s_list = [(_tag_parameter(par) if par.id in p_set else par)
83              for par in s_pars.kernel_parameters[1:]]
84    # Check if still a collision after renaming.  This could happen if for
85    # example S has volfrac and P has both volfrac and volfrac_S.
86    if any(p.id in p_set for p in s_list):
87        raise TypeError("name collision: P has P.name and P.name_S while S has S.name")
88
89    translate_name = dict((old.id, new.id) for old, new
90                          in zip(s_pars.kernel_parameters[1:], s_list))
91    combined_pars = p_pars.kernel_parameters + s_list + make_extra_pars(p_info)
92    parameters = ParameterTable(combined_pars)
93    parameters.max_pd = p_pars.max_pd + s_pars.max_pd
94    def random():
95        combined_pars = p_info.random()
96        s_names = set(par.id for par in s_pars.kernel_parameters[1:])
97        combined_pars.update((translate_name[k], v)
98                             for k, v in s_info.random().items()
99                             if k in s_names)
100        return combined_pars
101
102    model_info = ModelInfo()
103    model_info.id = '@'.join((p_id, s_id))
104    model_info.name = '@'.join((p_name, s_name))
105    model_info.filename = None
106    model_info.title = 'Product of %s and %s'%(p_name, s_name)
107    model_info.description = model_info.title
108    model_info.docs = model_info.title
109    model_info.category = "custom"
110    model_info.parameters = parameters
111    model_info.random = random
112    #model_info.single = p_info.single and s_info.single
113    model_info.structure_factor = False
114    model_info.variant_info = None
115    #model_info.tests = []
116    #model_info.source = []
117    # Iq, Iqxy, form_volume, ER, VR and sesans
118    # Remember the component info blocks so we can build the model
119    model_info.composition = ('product', [p_info, s_info])
120    model_info.control = p_info.control
121    model_info.hidden = p_info.hidden
122    if getattr(p_info, 'profile', None) is not None:
123        profile_pars = set(p.id for p in p_info.parameters.kernel_parameters)
124        def profile(**kwargs):
125            # extract the profile args
126            kwargs = dict((k, v) for k, v in kwargs.items() if k in profile_pars)
127            return p_info.profile(**kwargs)
128    else:
129        profile = None
130    model_info.profile = profile
131    model_info.profile_axes = p_info.profile_axes
132
133    # TODO: delegate random to p_info, s_info
134    #model_info.random = lambda: {}
135
136    ## Show the parameter table
137    #from .compare import get_pars, parlist
138    #print("==== %s ====="%model_info.name)
139    #values = get_pars(model_info)
140    #print(parlist(model_info, values, is2d=True))
141    return model_info
142
143def _tag_parameter(par):
144    """
145    Tag the parameter name with _S to indicate that the parameter comes from
146    the structure factor parameter set.  This is only necessary if the
147    form factor model includes a parameter of the same name as a parameter
148    in the structure factor.
149    """
150    par = copy(par)
151    # Protect against a vector parameter in S by appending the vector length
152    # to the renamed parameter.  Note: haven't tested this since no existing
153    # structure factor models contain vector parameters.
154    vector_length = par.name[len(par.id):]
155    par.id = par.id + "_S"
156    par.name = par.id + vector_length
157    return par
158
159def _intermediates(P, S):
160    # type: (np.ndarray, np.ndarray) -> OrderedDict[str, np.ndarray]
161    """
162    Returns intermediate results for standard product (P(Q)*S(Q))
163    """
164    return OrderedDict((
165        ("P(Q)", P),
166        ("S(Q)", S),
167    ))
168
169def _intermediates_beta(F1, F2, S, scale, bg):
170    # type: (np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray) -> OrderedDict[str, np.ndarray]
171    """
172    Returns intermediate results for beta approximation-enabled product
173    """
174    # TODO: 1. include calculated Q vector
175    # TODO: 2. consider implications if there are intermediate results in P(Q)
176    return OrderedDict((
177        ("P(Q)", scale*F2),
178        ("S(Q)", S),
179        ("beta(Q)", F1**2 / F2),
180        ("S_eff(Q)", 1 + (F1**2 / F2)*(S-1)),
181        # ("I(Q)", scale*(F2 + (F1**2)*(S-1)) + bg),
182    ))
183
184class ProductModel(KernelModel):
185    def __init__(self, model_info, P, S):
186        # type: (ModelInfo, KernelModel, KernelModel) -> None
187        #: Combined info plock for the product model
188        self.info = model_info
189        #: Form factor modelling individual particles.
190        self.P = P
191        #: Structure factor modelling interaction between particles.
192        self.S = S
193
194        #: Model precision. This is not really relevant, since it is the
195        #: individual P and S models that control the effective dtype,
196        #: converting the q-vectors to the correct type when the kernels
197        #: for each are created. Ideally this should be set to the more
198        #: precise type to avoid loss of precision, but precision in q is
199        #: not critical (single is good enough for our purposes), so it just
200        #: uses the precision of the form factor.
201        self.dtype = P.dtype  # type: np.dtype
202
203    def make_kernel(self, q_vectors):
204        # type: (List[np.ndarray]) -> Kernel
205        # Note: may be sending the q_vectors to the GPU twice even though they
206        # are only needed once.  It would mess up modularity quite a bit to
207        # handle this optimally, especially since there are many cases where
208        # separate q vectors are needed (e.g., form in python and structure
209        # in opencl; or both in opencl, but one in single precision and the
210        # other in double precision).
211
212        p_kernel = self.P.make_kernel(q_vectors)
213        s_kernel = self.S.make_kernel(q_vectors)
214        return ProductKernel(self.info, p_kernel, s_kernel)
215
216    def release(self):
217        # type: (None) -> None
218        """
219        Free resources associated with the model.
220        """
221        self.P.release()
222        self.S.release()
223
224
225class ProductKernel(Kernel):
226    def __init__(self, model_info, p_kernel, s_kernel):
227        # type: (ModelInfo, Kernel, Kernel) -> None
228        self.info = model_info
229        self.p_kernel = p_kernel
230        self.s_kernel = s_kernel
231        self.dtype = p_kernel.dtype
232        self.results = []  # type: List[np.ndarray]
233
234    def __call__(self, call_details, values, cutoff, magnetic):
235        # type: (CallDetails, np.ndarray, float, bool) -> np.ndarray
236        p_info, s_info = self.info.composition[1]
237
238        # if there are magnetic parameters, they will only be on the
239        # form factor P, not the structure factor S.
240        nmagnetic = len(self.info.parameters.magnetism_index)
241        if nmagnetic:
242            spin_index = self.info.parameters.npars + 2
243            magnetism = values[spin_index: spin_index+3+3*nmagnetic]
244        else:
245            magnetism = []
246        nvalues = self.info.parameters.nvalues
247        nweights = call_details.num_weights
248        weights = values[nvalues:nvalues + 2*nweights]
249
250        # Construct the calling parameters for P.
251        p_npars = p_info.parameters.npars
252        p_length = call_details.length[:p_npars]
253        p_offset = call_details.offset[:p_npars]
254        p_details = make_details(p_info, p_length, p_offset, nweights)
255
256        # Set p scale to the volume fraction in s, which is the first of the
257        # 'S' parameters in the parameter list, or 2+np in 0-origin.
258        volfrac = values[2+p_npars]
259        p_values = [[volfrac, 0.0], values[2:2+p_npars], magnetism, weights]
260        spacer = (32 - sum(len(v) for v in p_values)%32)%32
261        p_values.append([0.]*spacer)
262        p_values = np.hstack(p_values).astype(self.p_kernel.dtype)
263
264        # Call ER and VR for P since these are needed for S.
265        p_er, p_vr = calc_er_vr(p_info, p_details, p_values)
266        s_vr = (volfrac/p_vr if p_vr != 0. else volfrac)
267        #print("volfrac:%g p_er:%g p_vr:%g s_vr:%g"%(volfrac,p_er,p_vr,s_vr))
268
269        # Construct the calling parameters for S.
270        # The  effective radius is not in the combined parameter list, so
271        # the number of 'S' parameters is one less than expected.  The
272        # computed effective radius needs to be added into the weights
273        # vector, especially since it is a polydisperse parameter in the
274        # stand-alone structure factor models.  We will added it at the
275        # end so the remaining offsets don't need to change.
276        s_npars = s_info.parameters.npars-1
277        s_length = call_details.length[p_npars:p_npars+s_npars]
278        s_offset = call_details.offset[p_npars:p_npars+s_npars]
279        s_length = np.hstack((1, s_length))
280        s_offset = np.hstack((nweights, s_offset))
281        s_details = make_details(s_info, s_length, s_offset, nweights+1)
282        v, w = weights[:nweights], weights[nweights:]
283        s_values = [
284            # scale=1, background=0, radius_effective=p_er, volfraction=s_vr
285            [1., 0., p_er, s_vr],
286            # structure factor parameters start after scale, background and
287            # all the form factor parameters.  Skip the volfraction parameter
288            # as well, since it is computed elsewhere, and go to the end of the
289            # parameter list.
290            values[2+p_npars+1:2+p_npars+s_npars],
291            # no magnetism parameters to include for S
292            # add er into the (value, weights) pairs
293            v, [p_er], w, [1.0]
294        ]
295        spacer = (32 - sum(len(v) for v in s_values)%32)%32
296        s_values.append([0.]*spacer)
297        s_values = np.hstack(s_values).astype(self.s_kernel.dtype)
298
299        # beta mode is the first parameter after the structure factor pars
300        beta_index = 2+p_npars+s_npars
301        beta_mode = values[beta_index]
302
303        # Call the kernels
304        s_result = self.s_kernel.Iq(s_details, s_values, cutoff, False)
305        scale, background = values[0], values[1]
306        if beta_mode:
307            F1, F2, volume_avg = self.p_kernel.beta(p_details, p_values, cutoff, magnetic)
308            combined_scale = scale*volfrac/volume_avg
309
310            self.results = lambda: _intermediates_beta(F1, F2, s_result, volfrac/volume_avg, background)
311            final_result = combined_scale*(F2 + (F1**2)*(s_result - 1)) + background
312
313        else:
314            p_result = self.p_kernel.Iq(p_details, p_values, cutoff, magnetic)
315
316            self.results = lambda: _intermediates(p_result, s_result)
317            final_result = scale*(p_result*s_result) + background
318
319        #call_details.show(values)
320        #print("values", values)
321        #p_details.show(p_values)
322        #print("=>", p_result)
323        #s_details.show(s_values)
324        #print("=>", s_result)
325        #import pylab as plt
326        #plt.subplot(211); plt.loglog(self.p_kernel.q_input.q, p_result, '-')
327        #plt.subplot(212); plt.loglog(self.s_kernel.q_input.q, s_result, '-')
328        #plt.figure()
329        return final_result
330
331    def release(self):
332        # type: () -> None
333        self.p_kernel.release()
334        self.s_kernel.release()
335
336
337def calc_er_vr(model_info, call_details, values):
338    # type: (ModelInfo, ParameterSet) -> Tuple[float, float]
339
340    if model_info.ER is None and model_info.VR is None:
341        return 1.0, 1.0
342
343    nvalues = model_info.parameters.nvalues
344    value = values[nvalues:nvalues + call_details.num_weights]
345    weight = values[nvalues + call_details.num_weights: nvalues + 2*call_details.num_weights]
346    npars = model_info.parameters.npars
347    # Note: changed from pairs ([v], [w]) to triples (p, [v], [w]), but the
348    # dispersion mesh code doesn't actually care about the nominal parameter
349    # value, p, so set it to None.
350    pairs = [(None, value[offset:offset+length], weight[offset:offset+length])
351             for p, offset, length
352             in zip(model_info.parameters.call_parameters[2:2+npars],
353                    call_details.offset,
354                    call_details.length)
355             if p.type == 'volume']
356    value, weight = dispersion_mesh(model_info, pairs)
357
358    if model_info.ER is not None:
359        individual_radii = model_info.ER(*value)
360        radius_effective = np.sum(weight*individual_radii) / np.sum(weight)
361    else:
362        radius_effective = 1.0
363
364    if model_info.VR is not None:
365        whole, part = model_info.VR(*value)
366        volume_ratio = np.sum(weight*part)/np.sum(weight*whole)
367    else:
368        volume_ratio = 1.0
369
370    return radius_effective, volume_ratio
Note: See TracBrowser for help on using the repository browser.