source: sasmodels/sasmodels/product.py @ 99658f6

core_shell_microgelsmagnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 99658f6 was 99658f6, checked in by grethevj, 5 years ago

updated ER functions including cylinder excluded volume, to match 4.x

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