source: sasmodels/sasmodels/product.py @ 01c8d9e

core_shell_microgelsmagnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 01c8d9e was 01c8d9e, checked in by Suczewski <ges3@…>, 11 months ago

beta approximation, first pass

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