source: sasmodels/sasmodels/product.py @ 765eb0e

core_shell_microgelscostrafo411magnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 765eb0e was 765eb0e, checked in by Paul Kienzle <pkienzle@…>, 7 years ago

allow random generation of parameters for product and mixture models

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