source: sasmodels/sasmodels/product.py @ d32de68

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

put intermediate results into helper functions; tidy up; retain sasview 4.3 support in returning P(Q), S(Q)

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