source: sasmodels/sasmodels/mixture.py @ ac98886

core_shell_microgelscostrafo411magnetic_modelrelease_v0.94release_v0.95ticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since ac98886 was ac98886, checked in by Paul Kienzle <pkienzle@…>, 6 years ago

restore support for mixture models

  • Property mode set to 100644
File size: 8.0 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):
28    # type: (List[ModelInfo]) -> ModelInfo
29    """
30    Create info block for product model.
31    """
32    flatten = []
33    for part in parts:
34        if part.composition and part.composition[0] == 'mixture':
35            flatten.extend(part.composition[1])
36        else:
37            flatten.append(part)
38    parts = flatten
39
40    # Build new parameter list
41    combined_pars = []
42    for k, part in enumerate(parts):
43        # Parameter prefix per model, A_, B_, ...
44        # Note that prefix must also be applied to id and length_control
45        # to support vector parameters
46        prefix = chr(ord('A')+k) + '_'
47        scale =  Parameter(prefix+'scale', default=1.0,
48                           description="model intensity for " + part.name)
49        combined_pars.append(scale)
50        for p in part.parameters.kernel_parameters:
51            p = copy(p)
52            p.name = prefix + p.name
53            p.id = prefix + p.id
54            if p.length_control is not None:
55                p.length_control = prefix + p.length_control
56            combined_pars.append(p)
57    #print("pars",combined_pars)
58    parameters = ParameterTable(combined_pars)
59    parameters.max_pd = sum(part.parameters.max_pd for part in parts)
60
61    model_info = ModelInfo()
62    model_info.id = '+'.join(part.id for part in parts)
63    model_info.name = ' + '.join(part.name for part in parts)
64    model_info.filename = None
65    model_info.title = 'Mixture model with ' + model_info.name
66    model_info.description = model_info.title
67    model_info.docs = model_info.title
68    model_info.category = "custom"
69    model_info.parameters = parameters
70    #model_info.single = any(part['single'] for part in parts)
71    model_info.structure_factor = False
72    model_info.variant_info = None
73    #model_info.tests = []
74    #model_info.source = []
75    # Iq, Iqxy, form_volume, ER, VR and sesans
76    # Remember the component info blocks so we can build the model
77    model_info.composition = ('mixture', parts)
78    model_info.demo = {}
79    return model_info
80
81
82class MixtureModel(KernelModel):
83    def __init__(self, model_info, parts):
84        # type: (ModelInfo, List[KernelModel]) -> None
85        self.info = model_info
86        self.parts = parts
87
88    def make_kernel(self, q_vectors):
89        # type: (List[np.ndarray]) -> MixtureKernel
90        # Note: may be sending the q_vectors to the n times even though they
91        # are only needed once.  It would mess up modularity quite a bit to
92        # handle this optimally, especially since there are many cases where
93        # separate q vectors are needed (e.g., form in python and structure
94        # in opencl; or both in opencl, but one in single precision and the
95        # other in double precision).
96        kernels = [part.make_kernel(q_vectors) for part in self.parts]
97        return MixtureKernel(self.info, kernels)
98
99    def release(self):
100        # type: () -> None
101        """
102        Free resources associated with the model.
103        """
104        for part in self.parts:
105            part.release()
106
107
108class MixtureKernel(Kernel):
109    def __init__(self, model_info, kernels):
110        # type: (ModelInfo, List[Kernel]) -> None
111        self.dim = kernels[0].dim
112        self.info =  model_info
113        self.kernels = kernels
114        self.dtype = self.kernels[0].dtype
115
116    def __call__(self, call_details, values, cutoff, magnetic):
117        # type: (CallDetails, np.ndarray, np.ndarry, float) -> np.ndarray
118        scale, background = values[0:2]
119        total = 0.0
120        # remember the parts for plotting later
121        self.results = []
122        offset = 2 # skip scale & background
123        parts = MixtureParts(self.info, self.kernels, call_details, values)
124        for kernel, kernel_details, kernel_values in parts:
125            #print("calling kernel", kernel.info.name)
126            result = kernel(kernel_details, kernel_values, cutoff, magnetic)
127            #print(kernel.info.name, result)
128            total += result
129            self.results.append(result)
130
131        return scale*total + background
132
133    def release(self):
134        # type: () -> None
135        for k in self.kernels:
136            k.release()
137
138
139class MixtureParts(object):
140    def __init__(self, model_info, kernels, call_details, values):
141        self.model_info = model_info
142        self.parts = model_info.composition[1]
143        self.kernels = kernels
144        self.call_details = call_details
145        self.values = values
146        self.spin_index = model_info.parameters.npars + 2
147        #call_details.show(values)
148
149    def __iter__(self):
150        # type: () -> PartIterable
151        self.part_num = 0
152        self.par_index = 2
153        self.mag_index = self.spin_index + 3
154        return self
155
156    def next(self):
157        # type: () -> Tuple[List[Callable], CallDetails, np.ndarray]
158        if self.part_num >= len(self.parts):
159            raise StopIteration()
160        info = self.parts[self.part_num]
161        kernel = self.kernels[self.part_num]
162        call_details = self._part_details(info, self.par_index)
163        values = self._part_values(info, self.par_index, self.mag_index)
164        values = values.astype(kernel.dtype)
165        #call_details.show(values)
166
167        self.part_num += 1
168        self.par_index += info.parameters.npars + 1
169        self.mag_index += 3 * len(info.parameters.magnetism_index)
170
171        return kernel, call_details, values
172
173    def _part_details(self, info, par_index):
174        # type: (ModelInfo, int) -> CallDetails
175        full = self.call_details
176        # par_index is index into values array of the current parameter,
177        # which includes the initial scale and background parameters.
178        # We want the index into the weight length/offset for each parameter.
179        # Exclude the initial scale and background, so subtract two, but each
180        # component has its own scale factor which we need to skip when
181        # constructing the details for the kernel, so add one, giving a
182        # net subtract one.
183        index = slice(par_index - 1, par_index - 1 + info.parameters.npars)
184        length = full.length[index]
185        offset = full.offset[index]
186        # The complete weight vector is being sent to each part so that
187        # offsets don't need to be adjusted.
188        part = make_details(info, length, offset, full.num_weights)
189        return part
190
191    def _part_values(self, info, par_index, mag_index):
192        # type: (ModelInfo, int, int) -> np.ndarray
193        #print(info.name, par_index, self.values[par_index:par_index + info.parameters.npars + 1])
194        scale = self.values[par_index]
195        pars = self.values[par_index + 1:par_index + info.parameters.npars + 1]
196        nmagnetic = len(info.parameters.magnetism_index)
197        if nmagnetic:
198            spin_state = self.values[self.spin_index:self.spin_index + 3]
199            mag_index = self.values[mag_index:mag_index + 3 * nmagnetic]
200        else:
201            spin_state = []
202            mag_index = []
203        nvalues = self.model_info.parameters.nvalues
204        nweights = self.call_details.num_weights
205        weights = self.values[nvalues:nvalues+2*nweights]
206        zero = self.values.dtype.type(0.)
207        values = [[scale, zero], pars, spin_state, mag_index, weights]
208        # Pad value array to a 32 value boundary
209        spacer = (32 - sum(len(v) for v in values)%32)%32
210        values.append([zero]*spacer)
211        values = np.hstack(values).astype(self.kernels[0].dtype)
212        return values
Note: See TracBrowser for help on using the repository browser.