source: sasmodels/sasmodels/mixture.py @ 98c045a

ticket-1257-vesicle-product
Last change on this file since 98c045a was b2f0e5d, checked in by Paul Kienzle <pkienzle@…>, 5 years ago

Fix handling of volfraction in vesicle@hardsphere. Refs 1257.

  • Property mode set to 100644
File size: 13.1 KB
Line 
1"""
2Mixture 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*ProductModel(P, S)*.
12"""
13from __future__ import print_function
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
21
22# pylint: disable=unused-import
23try:
24    from typing import List
25except ImportError:
26    pass
27# pylint: enable=unused-import
28
29def make_mixture_info(parts, operation='+'):
30    # type: (List[ModelInfo]) -> ModelInfo
31    """
32    Create info block for mixture model.
33    """
34    # Build new parameter list
35    combined_pars = []
36
37    all_parts = copy(parts)
38    is_flat = False
39    while not is_flat:
40        is_flat = True
41        for part in all_parts:
42            if part.composition and part.composition[0] == 'mixture' and \
43                len(part.composition[1]) > 1:
44                all_parts += part.composition[1]
45                all_parts.remove(part)
46                is_flat = False
47
48    # When creating a mixture model that is a sum of product models (ie (1*2)+(3*4))
49    # the parameters for models 1 & 2 will be prefixed with A & B respectively,
50    # but so will the parameters for models 3 & 4. We need to rename models 3 & 4
51    # so that they are prefixed with C & D to avoid overlap of parameter names.
52    used_prefixes = []
53    for part in parts:
54        i = 0
55        if part.composition and part.composition[0] == 'mixture':
56            npars_list = [info.parameters.npars for info in part.composition[1]]
57            for npars in npars_list:
58                # List of params of one of the constituent models of part
59                submodel_pars = part.parameters.kernel_parameters[i:i+npars]
60                # Prefix of the constituent model
61                prefix = submodel_pars[0].name[0]
62                if prefix not in used_prefixes: # Haven't seen this prefix so far
63                    used_prefixes.append(prefix)
64                    i += npars
65                    continue
66                while prefix in used_prefixes:
67                    # This prefix has been already used, so change it to the
68                    # next letter that hasn't been used
69                    prefix = chr(ord(prefix) + 1)
70                used_prefixes.append(prefix)
71                prefix += "_"
72                # Update the parameters of this constituent model to use the
73                # new prefix
74                for par in submodel_pars:
75                    par.id = prefix + par.id[2:]
76                    par.name = prefix + par.name[2:]
77                    if par.length_control is not None:
78                        par.length_control = prefix + par.length_control[2:]
79                i += npars
80
81    for part in parts:
82        # Parameter prefix per model, A_, B_, ...
83        # Note that prefix must also be applied to id and length_control
84        # to support vector parameters
85        prefix = ''
86        if not part.composition:
87            # Model isn't a composition model, so it's parameters don't have a
88            # a prefix. Add the next available prefix
89            prefix = chr(ord('A')+len(used_prefixes))
90            used_prefixes.append(prefix)
91            prefix += '_'
92
93        if operation == '+':
94            # If model is a sum model, each constituent model gets its own scale parameter
95            scale_prefix = prefix
96            if prefix == '' and getattr(part, "operation", '') == '*':
97                # `part` is a composition product model. Find the prefixes of
98                # it's parameters to form a new prefix for the scale.
99                # For example, a model with A*B*C will have ABC_scale.
100                sub_prefixes = []
101                for param in part.parameters.kernel_parameters:
102                    # Prefix of constituent model
103                    sub_prefix = param.id.split('_')[0]
104                    if sub_prefix not in sub_prefixes:
105                        sub_prefixes.append(sub_prefix)
106                # Concatenate sub_prefixes to form prefix for the scale
107                scale_prefix = ''.join(sub_prefixes) + '_'
108            scale = Parameter(scale_prefix + 'scale', default=1.0,
109                              description="model intensity for " + part.name)
110            combined_pars.append(scale)
111        for p in part.parameters.kernel_parameters:
112            p = copy(p)
113            p.name = prefix + p.name
114            p.id = prefix + p.id
115            if p.length_control is not None:
116                p.length_control = prefix + p.length_control
117            combined_pars.append(p)
118    parameters = ParameterTable(combined_pars)
119    # Allow for the scenario in which each component has all its PD parameters
120    # active simultaneously.  details.make_details() will throw an error if
121    # too many are used from any one component.
122    parameters.max_pd = sum(part.parameters.max_pd for part in parts)
123
124    def random():
125        """Random set of model parameters for mixture model"""
126        combined_pars = {}
127        for k, part in enumerate(parts):
128            prefix = chr(ord('A')+k) + '_'
129            pars = part.random()
130            combined_pars.update((prefix+k, v) for k, v in pars.items())
131        return combined_pars
132
133    model_info = ModelInfo()
134    model_info.id = operation.join(part.id for part in parts)
135    model_info.operation = operation
136    model_info.name = '(' + operation.join(part.name for part in parts) + ')'
137    model_info.filename = None
138    model_info.title = 'Mixture model with ' + model_info.name
139    model_info.description = model_info.title
140    model_info.docs = model_info.title
141    model_info.category = "custom"
142    model_info.parameters = parameters
143    model_info.random = random
144    #model_info.single = any(part['single'] for part in parts)
145    model_info.structure_factor = False
146    model_info.variant_info = None
147    #model_info.tests = []
148    #model_info.source = []
149    # Remember the component info blocks so we can build the model
150    model_info.composition = ('mixture', parts)
151    return model_info
152
153
154class MixtureModel(KernelModel):
155    """
156    Model definition for mixture of models.
157    """
158    def __init__(self, model_info, parts):
159        # type: (ModelInfo, List[KernelModel]) -> None
160        self.info = model_info
161        self.parts = parts
162        self.dtype = parts[0].dtype
163
164    def make_kernel(self, q_vectors):
165        # type: (List[np.ndarray]) -> MixtureKernel
166        # Note: may be sending the q_vectors to the n times 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        kernels = [part.make_kernel(q_vectors) for part in self.parts]
173        return MixtureKernel(self.info, kernels)
174    make_kernel.__doc__ = KernelModel.make_kernel.__doc__
175
176    def release(self):
177        # type: () -> None
178        """Free resources associated with the model."""
179        for part in self.parts:
180            part.release()
181    release.__doc__ = KernelModel.release.__doc__
182
183
184class MixtureKernel(Kernel):
185    """
186    Instantiated kernel for mixture of models.
187    """
188    def __init__(self, model_info, kernels):
189        # type: (ModelInfo, List[Kernel]) -> None
190        self.dim = kernels[0].dim
191        self.info = model_info
192        self.kernels = kernels
193        self.dtype = self.kernels[0].dtype
194        self.operation = model_info.operation
195        self.results = []  # type: List[np.ndarray]
196
197    def Iq(self, call_details, values, cutoff, magnetic):
198        # type: (CallDetails, np.ndarray, np.ndarry, float, bool) -> np.ndarray
199        scale, background = values[0:2]
200        total = 0.0
201        # remember the parts for plotting later
202        self.results = []  # type: List[np.ndarray]
203        parts = _MixtureParts(self.info, self.kernels, call_details, values)
204        for kernel, kernel_details, kernel_values in parts:
205            #print("calling kernel", kernel.info.name)
206            result = kernel(kernel_details, kernel_values, cutoff, magnetic)
207            result = np.array(result).astype(kernel.dtype)
208            # print(kernel.info.name, result)
209            if self.operation == '+':
210                total += result
211            elif self.operation == '*':
212                if np.all(total) == 0.0:
213                    total = result
214                else:
215                    total *= result
216            self.results.append(result)
217
218        return scale*total + background
219
220    Iq.__doc__ = Kernel.Iq.__doc__
221    __call__ = Iq
222
223    def release(self):
224        # type: () -> None
225        """Free resources associated with the kernel."""
226        for k in self.kernels:
227            k.release()
228
229
230# Note: _MixtureParts doesn't implement iteration correctly, and only allows
231# a single iterator to be active at once.  It doesn't matter in this case
232# since _MixtureParts is only used in one place, but it is not clean style.
233class _MixtureParts(object):
234    """
235    Mixture component iterator.
236    """
237    def __init__(self, model_info, kernels, call_details, values):
238        # type: (ModelInfo, List[Kernel], CallDetails, np.ndarray) -> None
239        self.model_info = model_info
240        self.parts = model_info.composition[1]
241        self.kernels = kernels
242        self.call_details = call_details
243        self.values = values
244        self.spin_index = model_info.parameters.npars + 2
245        # The following are redefined by __iter__, but set them here so that
246        # lint complains a little less.
247        self.part_num = -1
248        self.par_index = -1
249        self.mag_index = -1
250        #call_details.show(values)
251
252    def __iter__(self):
253        # type: () -> PartIterable
254        self.part_num = 0
255        self.par_index = 2
256        self.mag_index = self.spin_index + 3
257        return self
258
259    def __next__(self):
260        # type: () -> Tuple[List[Callable], CallDetails, np.ndarray]
261        if self.part_num >= len(self.parts):
262            raise StopIteration()
263        info = self.parts[self.part_num]
264        kernel = self.kernels[self.part_num]
265        call_details = self._part_details(info, self.par_index)
266        values = self._part_values(info, self.par_index, self.mag_index)
267        values = values.astype(kernel.dtype)
268        #call_details.show(values)
269
270        self.part_num += 1
271        self.par_index += info.parameters.npars
272        if self.model_info.operation == '+':
273            self.par_index += 1 # Account for each constituent model's scale param
274        self.mag_index += 3 * len(info.parameters.magnetism_index)
275
276        return kernel, call_details, values
277
278    # CRUFT: py2 support
279    next = __next__
280
281    def _part_details(self, info, par_index):
282        # type: (ModelInfo, int) -> CallDetails
283        full = self.call_details
284        # par_index is index into values array of the current parameter,
285        # which includes the initial scale and background parameters.
286        # We want the index into the weight length/offset for each parameter.
287        # Exclude the initial scale and background, so subtract two. If we're
288        # building an addition model, each component has its own scale factor
289        # which we need to skip when constructing the details for the kernel, so
290        # add one, giving a net subtract one.
291        diff = 1 if self.model_info.operation == '+' else 2
292        index = slice(par_index - diff, par_index - diff + info.parameters.npars)
293        length = full.length[index]
294        offset = full.offset[index]
295        # The complete weight vector is being sent to each part so that
296        # offsets don't need to be adjusted.
297        part = make_details(info, length, offset, full.num_weights)
298        return part
299
300    def _part_values(self, info, par_index, mag_index):
301        # type: (ModelInfo, int, int) -> np.ndarray
302        # Set each constituent model's scale to 1 if this is a multiplication model
303        scale = self.values[par_index] if self.model_info.operation == '+' else 1.0
304        diff = 1 if self.model_info.operation == '+' else 0 # Skip scale if addition model
305        pars = self.values[par_index + diff:par_index + info.parameters.npars + diff]
306        nmagnetic = len(info.parameters.magnetism_index)
307        if nmagnetic:
308            spin_state = self.values[self.spin_index:self.spin_index + 3]
309            mag_index = self.values[mag_index:mag_index + 3 * nmagnetic]
310        else:
311            spin_state = []
312            mag_index = []
313        nvalues = self.model_info.parameters.nvalues
314        nweights = self.call_details.num_weights
315        weights = self.values[nvalues:nvalues+2*nweights]
316        zero = self.values.dtype.type(0.)
317        values = [[scale, zero], pars, spin_state, mag_index, weights]
318        # Pad value array to a 32 value boundary
319        spacer = (32 - sum(len(v) for v in values)%32)%32
320        values.append([zero]*spacer)
321        values = np.hstack(values).astype(self.kernels[0].dtype)
322        return values
Note: See TracBrowser for help on using the repository browser.