source: sasmodels/sasmodels/product.py @ 94d13f1

core_shell_microgelscostrafo411magnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 94d13f1 was 9951a86, checked in by Paul Kienzle <pkienzle@…>, 8 years ago

fix product model for structure factors with parameters

  • Property mode set to 100644
File size: 10.4 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
47    assert(s_info.parameters.kernel_parameters[0].id == ER_ID)
48    assert(s_info.parameters.kernel_parameters[1].id == VF_ID)
49    assert(s_info.parameters.magnetism_index == [])
[f619de7]50    p_id, p_name, p_pars = p_info.id, p_info.name, p_info.parameters
51    s_id, s_name, s_pars = s_info.id, s_info.name, s_info.parameters
52    p_set = set(p.id for p in p_pars.call_parameters)
53    s_set = set(p.id for p in s_pars.call_parameters)
[6d6508e]54
55    if p_set & s_set:
56        # there is some overlap between the parameter names; tag the
[6dc78e4]57        # overlapping S parameters with name_S.
58        # Skip the first parameter of s, which is effective radius
59        s_list = [(suffix_parameter(par) if par.id in p_set else par)
60                  for par in s_pars.kernel_parameters[1:]]
[6d6508e]61    else:
[6dc78e4]62        # Skip the first parameter of s, which is effective radius
63        s_list = s_pars.kernel_parameters[1:]
64    translate_name = dict((old.id, new.id) for old, new
65                          in zip(s_pars.kernel_parameters[1:], s_list))
66    demo = {}
67    demo.update((k, v) for k, v in p_info.demo.items()
68                if k not in ("background", "scale"))
69    demo.update((translate_name[k], v) for k, v in s_info.demo.items()
70                if k not in ("background", "scale") and not k.startswith(ER_ID))
71    combined_pars = p_pars.kernel_parameters + s_list
[f619de7]72    parameters = ParameterTable(combined_pars)
[6dc78e4]73    parameters.max_pd = p_pars.max_pd + s_pars.max_pd
[6d6508e]74
75    model_info = ModelInfo()
76    model_info.id = '*'.join((p_id, s_id))
[6dc78e4]77    model_info.name = '*'.join((p_name, s_name))
[6d6508e]78    model_info.filename = None
79    model_info.title = 'Product of %s and %s'%(p_name, s_name)
80    model_info.description = model_info.title
81    model_info.docs = model_info.title
82    model_info.category = "custom"
[f619de7]83    model_info.parameters = parameters
[6d6508e]84    #model_info.single = p_info.single and s_info.single
85    model_info.structure_factor = False
86    model_info.variant_info = None
87    #model_info.tests = []
88    #model_info.source = []
[fcd7bbd]89    # Iq, Iqxy, form_volume, ER, VR and sesans
[6dc78e4]90    # Remember the component info blocks so we can build the model
[6d6508e]91    model_info.composition = ('product', [p_info, s_info])
[6dc78e4]92    model_info.demo = {}
[17bbadd]93    return model_info
94
[6dc78e4]95def suffix_parameter(par, suffix):
96    par = copy(par)
97    par.name = par.name + " S"
98    par.id = par.id + "_S"
99    return par
100
[f619de7]101class ProductModel(KernelModel):
[72a081d]102    def __init__(self, model_info, P, S):
[f619de7]103        # type: (ModelInfo, KernelModel, KernelModel) -> None
[72a081d]104        self.info = model_info
[17bbadd]105        self.P = P
106        self.S = S
107
[6dc78e4]108    def make_kernel(self, q_vectors):
[f619de7]109        # type: (List[np.ndarray]) -> Kernel
[17bbadd]110        # Note: may be sending the q_vectors to the GPU twice even though they
111        # are only needed once.  It would mess up modularity quite a bit to
112        # handle this optimally, especially since there are many cases where
113        # separate q vectors are needed (e.g., form in python and structure
114        # in opencl; or both in opencl, but one in single precision and the
115        # other in double precision).
[f619de7]116        p_kernel = self.P.make_kernel(q_vectors)
117        s_kernel = self.S.make_kernel(q_vectors)
[17bbadd]118        return ProductKernel(self.info, p_kernel, s_kernel)
119
120    def release(self):
[f619de7]121        # type: (None) -> None
[17bbadd]122        """
123        Free resources associated with the model.
124        """
125        self.P.release()
126        self.S.release()
127
128
[f619de7]129class ProductKernel(Kernel):
[17bbadd]130    def __init__(self, model_info, p_kernel, s_kernel):
[f619de7]131        # type: (ModelInfo, Kernel, Kernel) -> None
[17bbadd]132        self.info = model_info
133        self.p_kernel = p_kernel
134        self.s_kernel = s_kernel
[6dc78e4]135        self.dtype = p_kernel.dtype
136        self.results = []  # type: List[np.ndarray]
137
138    def __call__(self, call_details, values, cutoff, magnetic):
139        # type: (CallDetails, np.ndarray, float, bool) -> np.ndarray
140        p_info, s_info = self.info.composition[1]
141
142        # if there are magnetic parameters, they will only be on the
143        # form factor P, not the structure factor S.
144        nmagnetic = len(self.info.parameters.magnetism_index)
145        if nmagnetic:
146            spin_index = self.info.parameters.npars + 2
147            magnetism = values[spin_index: spin_index+3+3*nmagnetic]
148        else:
149            magnetism = []
150        nvalues = self.info.parameters.nvalues
151        nweights = call_details.num_weights
152        weights = values[nvalues:nvalues + 2*nweights]
153
154        # Construct the calling parameters for P.
155        p_npars = p_info.parameters.npars
156        p_length = call_details.length[:p_npars]
157        p_offset = call_details.offset[:p_npars]
158        p_details = make_details(p_info, p_length, p_offset, nweights)
159        # Set p scale to the volume fraction in s, which is the first of the
160        # 'S' parameters in the parameter list, or 2+np in 0-origin.
161        volfrac = values[2+p_npars]
162        p_values = [[volfrac, 0.0], values[2:2+p_npars], magnetism, weights]
163        spacer = (32 - sum(len(v) for v in p_values)%32)%32
164        p_values.append([0.]*spacer)
165        p_values = np.hstack(p_values).astype(self.p_kernel.dtype)
166
167        # Call ER and VR for P since these are needed for S.
168        p_er, p_vr = calc_er_vr(p_info, p_details, p_values)
169        s_vr = (volfrac/p_vr if p_vr != 0. else volfrac)
170        #print("volfrac:%g p_er:%g p_vr:%g s_vr:%g"%(volfrac,p_er,p_vr,s_vr))
171
172        # Construct the calling parameters for S.
173        # The  effective radius is not in the combined parameter list, so
174        # the number of 'S' parameters is one less than expected.  The
175        # computed effective radius needs to be added into the weights
176        # vector, especially since it is a polydisperse parameter in the
177        # stand-alone structure factor models.  We will added it at the
178        # end so the remaining offsets don't need to change.
179        s_npars = s_info.parameters.npars-1
180        s_length = call_details.length[p_npars:p_npars+s_npars]
181        s_offset = call_details.offset[p_npars:p_npars+s_npars]
182        s_length = np.hstack((1, s_length))
183        s_offset = np.hstack((nweights, s_offset))
184        s_details = make_details(s_info, s_length, s_offset, nweights+1)
185        v, w = weights[:nweights], weights[nweights:]
[9951a86]186        s_values = [
187            # scale=1, background=0, radius_effective=p_er, volfraction=s_vr
188            [1., 0., p_er, s_vr],
189            # structure factor parameters start after scale, background and
190            # all the form factor parameters.  Skip the volfraction parameter
191            # as well, since it is computed elsewhere, and go to the end of the
192            # parameter list.
193            values[2+p_npars+1:2+p_npars+s_npars],
194            # no magnetism parameters to include for S
195            # add er into the (value, weights) pairs
196            v, [p_er], w, [1.0]
197        ]
[6dc78e4]198        spacer = (32 - sum(len(v) for v in s_values)%32)%32
199        s_values.append([0.]*spacer)
200        s_values = np.hstack(s_values).astype(self.s_kernel.dtype)
[17bbadd]201
[6dc78e4]202        # Call the kernels
203        p_result = self.p_kernel(p_details, p_values, cutoff, magnetic)
204        s_result = self.s_kernel(s_details, s_values, cutoff, False)
[17bbadd]205
[9951a86]206        #print("p_npars",p_npars,s_npars,p_er,s_vr,values[2+p_npars+1:2+p_npars+s_npars])
[6dc78e4]207        #call_details.show(values)
208        #print("values", values)
209        #p_details.show(p_values)
210        #print("=>", p_result)
211        #s_details.show(s_values)
212        #print("=>", s_result)
[17bbadd]213
[6dc78e4]214        # remember the parts for plotting later
215        self.results = [p_result, s_result]
216
217        #import pylab as plt
218        #plt.subplot(211); plt.loglog(self.p_kernel.q_input.q, p_result, '-')
219        #plt.subplot(212); plt.loglog(self.s_kernel.q_input.q, s_result, '-')
220        #plt.figure()
221
222        return values[0]*(p_result*s_result) + values[1]
[17bbadd]223
224    def release(self):
[f619de7]225        # type: () -> None
[17bbadd]226        self.p_kernel.release()
[f619de7]227        self.s_kernel.release()
[17bbadd]228
[6dc78e4]229
230def calc_er_vr(model_info, call_details, values):
231    # type: (ModelInfo, ParameterSet) -> Tuple[float, float]
232
[f619de7]233    if model_info.ER is None and model_info.VR is None:
234        return 1.0, 1.0
235
[6dc78e4]236    nvalues = model_info.parameters.nvalues
237    value = values[nvalues:nvalues + call_details.num_weights]
238    weight = values[nvalues + call_details.num_weights: nvalues + 2*call_details.num_weights]
239    npars = model_info.parameters.npars
240    pairs = [(value[offset:offset+length], weight[offset:offset+length])
241             for p, offset, length
242             in zip(model_info.parameters.call_parameters[2:2+npars],
243                    call_details.offset,
244                    call_details.length)
245             if p.type == 'volume']
246    value, weight = dispersion_mesh(model_info, pairs)
[6d6508e]247
[f619de7]248    if model_info.ER is not None:
249        individual_radii = model_info.ER(*value)
[6dc78e4]250        radius_effective = np.sum(weight*individual_radii) / np.sum(weight)
[f619de7]251    else:
[6dc78e4]252        radius_effective = 1.0
[f619de7]253
254    if model_info.VR is not None:
255        whole, part = model_info.VR(*value)
256        volume_ratio = np.sum(weight*part)/np.sum(weight*whole)
257    else:
258        volume_ratio = 1.0
[6d6508e]259
[6dc78e4]260    return radius_effective, volume_ratio
Note: See TracBrowser for help on using the repository browser.