source: sasmodels/sasmodels/mixture.py @ 61a4bd4

core_shell_microgelscostrafo411magnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 61a4bd4 was 61a4bd4, checked in by lewis, 7 years ago

Refactor load_model_info to parse more complex model strings

  • Property mode set to 100644
File size: 11.9 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
22try:
23    from typing import List
24except ImportError:
25    pass
26
27def make_mixture_info(parts, operation='+'):
28    # type: (List[ModelInfo]) -> ModelInfo
29    """
30    Create info block for mixture model.
31    """
32    # Build new parameter list
33    combined_pars = []
34    demo = {}
35
36    model_num = 0
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    model_num = len(all_parts) - len(parts)
82    if model_num != 0:
83        model_num += 1
84
85    for k, part in enumerate(parts):
86        # Parameter prefix per model, A_, B_, ...
87        # Note that prefix must also be applied to id and length_control
88        # to support vector parameters
89        prefix = chr(ord('A')+k+model_num) + '_'
90        if part.composition and part.composition[0] == 'mixture':
91            # Parameter already has a prefix as it's part of a composition model
92            prefix = ''
93            model_num -= 1
94           
95        if operation == '+':
96            # If model is a sum model, each constituent model gets its own scale parameter
97            scale_prefix = prefix
98            if prefix == '' and part.operation == '*':
99                # `part` is a composition product model. Find the prefixes of
100                # it's parameters to form a new prefix for the scale, eg:
101                # a model with A*B*C will have ABC_scale
102                sub_prefixes = []
103                for param in part.parameters.kernel_parameters:
104                    # Prefix of constituent model
105                    sub_prefix = param.id.split('_')[0]
106                    if sub_prefix not in sub_prefixes:
107                        sub_prefixes.append(sub_prefix)
108                # Concatenate sub_prefixes to form prefix for the scale
109                scale_prefix = ''.join(sub_prefixes) + '_'
110            scale =  Parameter(scale_prefix + 'scale', default=1.0,
111                            description="model intensity for " + part.name)
112            combined_pars.append(scale)
113        for p in part.parameters.kernel_parameters:
114            p = copy(p)
115            p.name = prefix + p.name
116            p.id = prefix + p.id
117            if p.length_control is not None:
118                p.length_control = prefix + p.length_control
119            combined_pars.append(p)
120        demo.update((prefix+k, v) for k, v in part.demo.items()
121                    if k != "background")
122    #print("pars",combined_pars)
123    parameters = ParameterTable(combined_pars)
124    parameters.max_pd = sum(part.parameters.max_pd for part in parts)
125
126    model_info = ModelInfo()
127    model_info.id = operation.join(part.id for part in parts)
128    model_info.operation = operation
129    model_info.name = '(' + operation.join(part.name for part in parts) + ')'
130    model_info.filename = None
131    model_info.title = 'Mixture model with ' + model_info.name
132    model_info.description = model_info.title
133    model_info.docs = model_info.title
134    model_info.category = "custom"
135    model_info.parameters = parameters
136    #model_info.single = any(part['single'] for part in parts)
137    model_info.structure_factor = False
138    model_info.variant_info = None
139    #model_info.tests = []
140    #model_info.source = []
141    # Iq, Iqxy, form_volume, ER, VR and sesans
142    # Remember the component info blocks so we can build the model
143    model_info.composition = ('mixture', parts)
144    model_info.demo = demo
145    return model_info
146
147
148class MixtureModel(KernelModel):
149    def __init__(self, model_info, parts):
150        # type: (ModelInfo, List[KernelModel]) -> None
151        self.info = model_info
152        self.parts = parts
153
154    def make_kernel(self, q_vectors):
155        # type: (List[np.ndarray]) -> MixtureKernel
156        # Note: may be sending the q_vectors to the n times even though they
157        # are only needed once.  It would mess up modularity quite a bit to
158        # handle this optimally, especially since there are many cases where
159        # separate q vectors are needed (e.g., form in python and structure
160        # in opencl; or both in opencl, but one in single precision and the
161        # other in double precision).
162        kernels = [part.make_kernel(q_vectors) for part in self.parts]
163        return MixtureKernel(self.info, kernels)
164
165    def release(self):
166        # type: () -> None
167        """
168        Free resources associated with the model.
169        """
170        for part in self.parts:
171            part.release()
172
173
174class MixtureKernel(Kernel):
175    def __init__(self, model_info, kernels):
176        # type: (ModelInfo, List[Kernel]) -> None
177        self.dim = kernels[0].dim
178        self.info =  model_info
179        self.kernels = kernels
180        self.dtype = self.kernels[0].dtype
181        self.operation = model_info.operation
182        self.results = []  # type: List[np.ndarray]
183
184    def __call__(self, call_details, values, cutoff, magnetic):
185        # type: (CallDetails, np.ndarray, np.ndarry, float, bool) -> np.ndarray
186        scale, background = values[0:2]
187        total = 0.0
188        # remember the parts for plotting later
189        self.results = []  # type: List[np.ndarray]
190        parts = MixtureParts(self.info, self.kernels, call_details, values)
191        for kernel, kernel_details, kernel_values in parts:
192            #print("calling kernel", kernel.info.name)
193            result = kernel(kernel_details, kernel_values, cutoff, magnetic)
194            result = np.array(result).astype(kernel.dtype)
195            # print(kernel.info.name, result)
196            if self.operation == '+':
197                total += result
198            elif self.operation == '*':
199                if np.all(total) == 0.0:
200                    total = result
201                else:
202                    total *= result
203            self.results.append(result)
204
205        return scale*total + background
206
207    def release(self):
208        # type: () -> None
209        for k in self.kernels:
210            k.release()
211
212
213class MixtureParts(object):
214    def __init__(self, model_info, kernels, call_details, values):
215        # type: (ModelInfo, List[Kernel], CallDetails, np.ndarray) -> None
216        self.model_info = model_info
217        self.parts = model_info.composition[1]
218        self.kernels = kernels
219        self.call_details = call_details
220        self.values = values
221        self.spin_index = model_info.parameters.npars + 2
222        #call_details.show(values)
223
224    def __iter__(self):
225        # type: () -> PartIterable
226        self.part_num = 0
227        self.par_index = 2
228        self.mag_index = self.spin_index + 3
229        return self
230
231    def next(self):
232        # type: () -> Tuple[List[Callable], CallDetails, np.ndarray]
233        if self.part_num >= len(self.parts):
234            raise StopIteration()
235        info = self.parts[self.part_num]
236        kernel = self.kernels[self.part_num]
237        call_details = self._part_details(info, self.par_index)
238        values = self._part_values(info, self.par_index, self.mag_index)
239        values = values.astype(kernel.dtype)
240        #call_details.show(values)
241
242        self.part_num += 1
243        self.par_index += info.parameters.npars
244        if self.model_info.operation == '+':
245            self.par_index += 1 # Account for each constituent model's scale param
246        self.mag_index += 3 * len(info.parameters.magnetism_index)
247
248        return kernel, call_details, values
249
250    def _part_details(self, info, par_index):
251        # type: (ModelInfo, int) -> CallDetails
252        full = self.call_details
253        # par_index is index into values array of the current parameter,
254        # which includes the initial scale and background parameters.
255        # We want the index into the weight length/offset for each parameter.
256        # Exclude the initial scale and background, so subtract two. If we're
257        # building an addition model, each component has its own scale factor
258        # which we need to skip when constructing the details for the kernel, so
259        # add one, giving a net subtract one.
260        diff = 1 if self.model_info.operation == '+' else 2
261        index = slice(par_index - diff, par_index - diff + info.parameters.npars)
262        length = full.length[index]
263        offset = full.offset[index]
264        # The complete weight vector is being sent to each part so that
265        # offsets don't need to be adjusted.
266        part = make_details(info, length, offset, full.num_weights)
267        return part
268
269    def _part_values(self, info, par_index, mag_index):
270        # type: (ModelInfo, int, int) -> np.ndarray
271        # Set each constituent model's scale to 1 if this is a multiplication model
272        scale = self.values[par_index] if self.model_info.operation == '+' else 1.0
273        diff = 1 if self.model_info.operation == '+' else 0 # Skip scale if addition model
274        pars = self.values[par_index + diff:par_index + info.parameters.npars + diff]
275        nmagnetic = len(info.parameters.magnetism_index)
276        if nmagnetic:
277            spin_state = self.values[self.spin_index:self.spin_index + 3]
278            mag_index = self.values[mag_index:mag_index + 3 * nmagnetic]
279        else:
280            spin_state = []
281            mag_index = []
282        nvalues = self.model_info.parameters.nvalues
283        nweights = self.call_details.num_weights
284        weights = self.values[nvalues:nvalues+2*nweights]
285        zero = self.values.dtype.type(0.)
286        values = [[scale, zero], pars, spin_state, mag_index, weights]
287        # Pad value array to a 32 value boundary
288        spacer = (32 - sum(len(v) for v in values)%32)%32
289        values.append([zero]*spacer)
290        values = np.hstack(values).astype(self.kernels[0].dtype)
291        return values
Note: See TracBrowser for help on using the repository browser.