source: sasmodels/sasmodels/product.py @ c952e59

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

Merge branch 'beta_approx' into beta_approx_new_R_eff

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