source: sasmodels/sasmodels/product.py @ ac60a39

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

Merge branch 'master' into ticket-776-orientation

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