source: sasmodels/sasmodels/product.py @ 39a06c9

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

Remove references to ER and VR from sasmodels. Refs #1202.

  • 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, Union
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
39RADIUS_ID = "radius_effective"
40VOLFRAC_ID = "volfraction"
41def make_extra_pars(p_info):
42    pars = []
43    if p_info.have_Fq:
44        par = parse_parameter(
45                "structure_factor_mode",
46                "",
47                0,
48                [["P*S","P*(1+beta*(S-1))"]],
49                "",
50                "Structure factor calculation")
51        pars.append(par)
52    if p_info.effective_radius_type is not None:
53        par = parse_parameter(
54                "radius_effective_mode",
55                "",
56                0,
57                [["unconstrained"] + p_info.effective_radius_type],
58                "",
59                "Effective radius calculation")
60        pars.append(par)
61    return pars
62
63def make_product_info(p_info, s_info):
64    # type: (ModelInfo, ModelInfo) -> ModelInfo
65    """
66    Create info block for product model.
67    """
68    # Make sure effective radius is the first parameter and
69    # make sure volume fraction is the second parameter of the
70    # structure factor calculator.  Structure factors should not
71    # have any magnetic parameters
72    if not len(s_info.parameters.kernel_parameters) >= 2:
73        raise TypeError("S needs {} and {} as its first parameters".format(RADIUS_ID, VOLFRAC_ID))
74    if not s_info.parameters.kernel_parameters[0].id == RADIUS_ID:
75        raise TypeError("S needs {} as first parameter".format(RADIUS_ID))
76    if not s_info.parameters.kernel_parameters[1].id == VOLFRAC_ID:
77        raise TypeError("S needs {} as second parameter".format(VOLFRAC_ID))
78    if not s_info.parameters.magnetism_index == []:
79        raise TypeError("S should not have SLD parameters")
80    p_id, p_name, p_pars = p_info.id, p_info.name, p_info.parameters
81    s_id, s_name, s_pars = s_info.id, s_info.name, s_info.parameters
82
83    # Create list of parameters for the combined model.  If there
84    # are any names in P that overlap with those in S, modify the name in S
85    # to distinguish it.
86    p_set = set(p.id for p in p_pars.kernel_parameters)
87    s_list = [(_tag_parameter(par) if par.id in p_set else par)
88              for par in s_pars.kernel_parameters]
89    # Check if still a collision after renaming.  This could happen if for
90    # example S has volfrac and P has both volfrac and volfrac_S.
91    if any(p.id in p_set for p in s_list):
92        raise TypeError("name collision: P has P.name and P.name_S while S has S.name")
93
94    # make sure effective radius is not a polydisperse parameter in product
95    s_list[0] = copy(s_list[0])
96    s_list[0].polydisperse = False
97
98    translate_name = dict((old.id, new.id) for old, new
99                          in zip(s_pars.kernel_parameters, s_list))
100    combined_pars = p_pars.kernel_parameters + s_list + make_extra_pars(p_info)
101    parameters = ParameterTable(combined_pars)
102    parameters.max_pd = p_pars.max_pd + s_pars.max_pd
103    def random():
104        combined_pars = p_info.random()
105        s_names = set(par.id for par in s_pars.kernel_parameters)
106        combined_pars.update((translate_name[k], v)
107                             for k, v in s_info.random().items()
108                             if k in s_names)
109        return combined_pars
110
111    model_info = ModelInfo()
112    model_info.id = '@'.join((p_id, s_id))
113    model_info.name = '@'.join((p_name, s_name))
114    model_info.filename = None
115    model_info.title = 'Product of %s and %s'%(p_name, s_name)
116    model_info.description = model_info.title
117    model_info.docs = model_info.title
118    model_info.category = "custom"
119    model_info.parameters = parameters
120    model_info.random = random
121    #model_info.single = p_info.single and s_info.single
122    model_info.structure_factor = False
123    model_info.variant_info = None
124    #model_info.tests = []
125    #model_info.source = []
126    # Remember the component info blocks so we can build the model
127    model_info.composition = ('product', [p_info, s_info])
128    model_info.control = p_info.control
129    model_info.hidden = p_info.hidden
130    if getattr(p_info, 'profile', None) is not None:
131        profile_pars = set(p.id for p in p_info.parameters.kernel_parameters)
132        def profile(**kwargs):
133            # extract the profile args
134            kwargs = dict((k, v) for k, v in kwargs.items() if k in profile_pars)
135            return p_info.profile(**kwargs)
136    else:
137        profile = None
138    model_info.profile = profile
139    model_info.profile_axes = p_info.profile_axes
140
141    # TODO: delegate random to p_info, s_info
142    #model_info.random = lambda: {}
143
144    ## Show the parameter table
145    #from .compare import get_pars, parlist
146    #print("==== %s ====="%model_info.name)
147    #values = get_pars(model_info)
148    #print(parlist(model_info, values, is2d=True))
149    return model_info
150
151def _tag_parameter(par):
152    """
153    Tag the parameter name with _S to indicate that the parameter comes from
154    the structure factor parameter set.  This is only necessary if the
155    form factor model includes a parameter of the same name as a parameter
156    in the structure factor.
157    """
158    par = copy(par)
159    # Protect against a vector parameter in S by appending the vector length
160    # to the renamed parameter.  Note: haven't tested this since no existing
161    # structure factor models contain vector parameters.
162    vector_length = par.name[len(par.id):]
163    par.id = par.id + "_S"
164    par.name = par.id + vector_length
165    return par
166
167def _intermediates(
168        F1,               # type: np.ndarray
169        F2,               # type: np.ndarray
170        S,                # type: np.ndarray
171        scale,            # type: float
172        effective_radius, # type: float
173        beta_mode,        # type: bool
174        ):
175    # type: (...) -> OrderedDict[str, Union[np.ndarray, float]]
176    """
177    Returns intermediate results for beta approximation-enabled product.
178    The result may be an array or a float.
179    """
180    if beta_mode:
181        # TODO: 1. include calculated Q vector
182        # TODO: 2. consider implications if there are intermediate results in P(Q)
183        parts = OrderedDict((
184            ("P(Q)", scale*F2),
185            ("S(Q)", S),
186            ("beta(Q)", F1**2 / F2),
187            ("S_eff(Q)", 1 + (F1**2 / F2)*(S-1)),
188            ("effective_radius", effective_radius),
189            # ("I(Q)", scale*(F2 + (F1**2)*(S-1)) + bg),
190        ))
191    else:
192        parts = OrderedDict((
193            ("P(Q)", scale*F2),
194            ("S(Q)", S),
195            ("effective_radius", effective_radius),
196        ))
197    return parts
198
199class ProductModel(KernelModel):
200    def __init__(self, model_info, P, S):
201        # type: (ModelInfo, KernelModel, KernelModel) -> None
202        #: Combined info plock for the product model
203        self.info = model_info
204        #: Form factor modelling individual particles.
205        self.P = P
206        #: Structure factor modelling interaction between particles.
207        self.S = S
208
209        #: Model precision. This is not really relevant, since it is the
210        #: individual P and S models that control the effective dtype,
211        #: converting the q-vectors to the correct type when the kernels
212        #: for each are created. Ideally this should be set to the more
213        #: precise type to avoid loss of precision, but precision in q is
214        #: not critical (single is good enough for our purposes), so it just
215        #: uses the precision of the form factor.
216        self.dtype = P.dtype  # type: np.dtype
217
218    def make_kernel(self, q_vectors):
219        # type: (List[np.ndarray]) -> Kernel
220        # Note: may be sending the q_vectors to the GPU twice even though they
221        # are only needed once.  It would mess up modularity quite a bit to
222        # handle this optimally, especially since there are many cases where
223        # separate q vectors are needed (e.g., form in python and structure
224        # in opencl; or both in opencl, but one in single precision and the
225        # other in double precision).
226
227        p_kernel = self.P.make_kernel(q_vectors)
228        s_kernel = self.S.make_kernel(q_vectors)
229        return ProductKernel(self.info, p_kernel, s_kernel)
230
231    def release(self):
232        # type: (None) -> None
233        """
234        Free resources associated with the model.
235        """
236        self.P.release()
237        self.S.release()
238
239
240class ProductKernel(Kernel):
241    def __init__(self, model_info, p_kernel, s_kernel):
242        # type: (ModelInfo, Kernel, Kernel) -> None
243        self.info = model_info
244        self.p_kernel = p_kernel
245        self.s_kernel = s_kernel
246        self.dtype = p_kernel.dtype
247        self.results = []  # type: List[np.ndarray]
248
249    def __call__(self, call_details, values, cutoff, magnetic):
250        # type: (CallDetails, np.ndarray, float, bool) -> np.ndarray
251
252        p_info, s_info = self.info.composition[1]
253        p_npars = p_info.parameters.npars
254        p_length = call_details.length[:p_npars]
255        p_offset = call_details.offset[:p_npars]
256        s_npars = s_info.parameters.npars
257        s_length = call_details.length[p_npars:p_npars+s_npars]
258        s_offset = call_details.offset[p_npars:p_npars+s_npars]
259
260        # Beta mode parameter is the first parameter after P and S parameters
261        have_beta_mode = p_info.have_Fq
262        beta_mode_offset = 2+p_npars+s_npars
263        beta_mode = (values[beta_mode_offset] > 0) if have_beta_mode else False
264        if beta_mode and self.p_kernel.dim== '2d':
265            raise NotImplementedError("beta not yet supported for 2D")
266
267        # R_eff type parameter is the second parameter after P and S parameters
268        # unless the model doesn't support beta mode, in which case it is first
269        have_radius_type = p_info.effective_radius_type is not None
270        radius_type_offset = 2+p_npars+s_npars + (1 if have_beta_mode else 0)
271        radius_type = int(values[radius_type_offset]) if have_radius_type else 0
272
273        # Retrieve the volume fraction, which is the second of the
274        # 'S' parameters in the parameter list, or 2+np in 0-origin,
275        # as well as the scale and background.
276        volfrac = values[3+p_npars]
277        scale, background = values[0], values[1]
278
279        # if there are magnetic parameters, they will only be on the
280        # form factor P, not the structure factor S.
281        nmagnetic = len(self.info.parameters.magnetism_index)
282        if nmagnetic:
283            spin_index = self.info.parameters.npars + 2
284            magnetism = values[spin_index: spin_index+3+3*nmagnetic]
285        else:
286            magnetism = []
287        nvalues = self.info.parameters.nvalues
288        nweights = call_details.num_weights
289        weights = values[nvalues:nvalues + 2*nweights]
290
291        # Construct the calling parameters for P.
292        p_details = make_details(p_info, p_length, p_offset, nweights)
293        p_values = [
294            [1., 0.], # scale=1, background=0,
295            values[2:2+p_npars],
296            magnetism,
297            weights]
298        spacer = (32 - sum(len(v) for v in p_values)%32)%32
299        p_values.append([0.]*spacer)
300        p_values = np.hstack(p_values).astype(self.p_kernel.dtype)
301
302        # Construct the calling parameters for S.
303        if radius_type > 0:
304            # If R_eff comes from form factor, make sure it is monodisperse.
305            # weight is set to 1 later, after the value array is created
306            s_length[0] = 1
307        s_details = make_details(s_info, s_length, s_offset, nweights)
308        s_values = [
309            [1., 0.], # scale=1, background=0,
310            values[2+p_npars:2+p_npars+s_npars],
311            weights,
312        ]
313        spacer = (32 - sum(len(v) for v in s_values)%32)%32
314        s_values.append([0.]*spacer)
315        s_values = np.hstack(s_values).astype(self.s_kernel.dtype)
316
317        # Call the form factor kernel to compute <F> and <F^2>.
318        # If the model doesn't support Fq the returned <F> will be None.
319        F1, F2, effective_radius, shell_volume, volume_ratio = self.p_kernel.Fq(
320            p_details, p_values, cutoff, magnetic, radius_type)
321
322        # Call the structure factor kernel to compute S.
323        # Plug R_eff from the form factor into structure factor parameters
324        # and scale volume fraction by form:shell volume ratio. These changes
325        # needs to be both in the initial value slot as well as the
326        # polydispersity distribution slot in the values array due to
327        # implementation details in kernel_iq.c.
328        #print("R_eff=%d:%g, volfrac=%g, volume ratio=%g"%(radius_type, effective_radius, volfrac, volume_ratio))
329        if radius_type > 0:
330            # set the value to the model R_eff and set the weight to 1
331            s_values[2] = s_values[2+s_npars+s_offset[0]] = effective_radius
332            s_values[2+s_npars+s_offset[0]+nweights] = 1.0
333        s_values[3] = s_values[2+s_npars+s_offset[1]] = volfrac*volume_ratio
334        S = self.s_kernel.Iq(s_details, s_values, cutoff, False)
335
336        # Determine overall scale factor. Hollow shapes are weighted by
337        # shell_volume, so that is needed for volume normalization.  For
338        # solid shapes we can use shell_volume as well since it is equal
339        # to form volume.
340        combined_scale = scale*volfrac/shell_volume
341
342        # Combine form factor and structure factor
343        #print("beta", beta_mode, F1, F2, S)
344        PS = F2 + F1**2*(S-1) if beta_mode else F2*S
345        final_result = combined_scale*PS + background
346
347        # Capture intermediate values so user can see them.  These are
348        # returned as a lazy evaluator since they are only needed in the
349        # GUI, and not for each evaluation during a fit.
350        # TODO: return the results structure with the final results
351        # That way the model calcs are idempotent. Further, we can
352        # generalize intermediates to various other model types if we put it
353        # kernel calling interface.  Could do this as an "optional"
354        # return value in the caller, though in that case we could return
355        # the results directly rather than through a lazy evaluator.
356        self.results = lambda: _intermediates(
357            F1, F2, S, combined_scale, effective_radius, beta_mode)
358
359        return final_result
360
361    def release(self):
362        # type: () -> None
363        self.p_kernel.release()
364        self.s_kernel.release()
Note: See TracBrowser for help on using the repository browser.