source: sasmodels/sasmodels/product.py @ b39bf3b

ticket-1257-vesicle-productticket_1156ticket_822_more_unit_tests
Last change on this file since b39bf3b was b39bf3b, checked in by ajj, 5 years ago

Working on structure factor / beta tests

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