source: sasmodels/sasmodels/mixture.py @ 2ad5d30

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