1 | """ |
---|
2 | SAS distributions for polydispersity. |
---|
3 | """ |
---|
4 | # TODO: include dispersion docs with the disperser models |
---|
5 | from __future__ import division, print_function |
---|
6 | |
---|
7 | from math import sqrt # type: ignore |
---|
8 | from collections import OrderedDict |
---|
9 | |
---|
10 | import numpy as np # type: ignore |
---|
11 | from scipy.special import gammaln # type: ignore |
---|
12 | |
---|
13 | # TODO: include dispersion docs with the disperser models |
---|
14 | |
---|
15 | class Dispersion(object): |
---|
16 | """ |
---|
17 | Base dispersion object. |
---|
18 | |
---|
19 | Subclasses should define *_weights(center, sigma, lb, ub)* |
---|
20 | which returns the x points and their corresponding weights. |
---|
21 | """ |
---|
22 | type = "base disperser" |
---|
23 | default = dict(npts=35, width=0, nsigmas=3) |
---|
24 | def __init__(self, npts=None, width=None, nsigmas=None): |
---|
25 | self.npts = self.default['npts'] if npts is None else npts |
---|
26 | self.width = self.default['width'] if width is None else width |
---|
27 | self.nsigmas = self.default['nsigmas'] if nsigmas is None else nsigmas |
---|
28 | |
---|
29 | def get_pars(self): |
---|
30 | """ |
---|
31 | Return the parameters to the disperser as a dictionary. |
---|
32 | """ |
---|
33 | pars = {'type': self.type} |
---|
34 | pars.update(self.__dict__) |
---|
35 | return pars |
---|
36 | |
---|
37 | # pylint: disable=no-self-use |
---|
38 | def set_weights(self, values, weights): |
---|
39 | """ |
---|
40 | Set the weights on the disperser if it is :class:`ArrayDispersion`. |
---|
41 | """ |
---|
42 | raise RuntimeError("set_weights is only available for ArrayDispersion") |
---|
43 | |
---|
44 | def get_weights(self, center, lb, ub, relative): |
---|
45 | """ |
---|
46 | Return the weights for the distribution. |
---|
47 | |
---|
48 | *center* is the center of the distribution |
---|
49 | |
---|
50 | *lb*, *ub* are the min and max allowed values |
---|
51 | |
---|
52 | *relative* is True if the distribution width is proportional to the |
---|
53 | center value instead of absolute. For polydispersity use relative. |
---|
54 | For orientation parameters use absolute. |
---|
55 | """ |
---|
56 | sigma = self.width * center if relative else self.width |
---|
57 | if not relative: |
---|
58 | # For orientation, the jitter is relative to 0 not the angle |
---|
59 | center = 0 |
---|
60 | pass |
---|
61 | if sigma == 0 or self.npts < 2: |
---|
62 | if lb <= center <= ub: |
---|
63 | return np.array([center], 'd'), np.array([1.], 'd') |
---|
64 | else: |
---|
65 | return np.array([], 'd'), np.array([], 'd') |
---|
66 | x, px = self._weights(center, sigma, lb, ub) |
---|
67 | return x, px |
---|
68 | |
---|
69 | def _weights(self, center, sigma, lb, ub): |
---|
70 | """actual work of computing the weights""" |
---|
71 | raise NotImplementedError |
---|
72 | |
---|
73 | def _linspace(self, center, sigma, lb, ub): |
---|
74 | """helper function to provide linear spaced weight points within range""" |
---|
75 | npts, nsigmas = self.npts, self.nsigmas |
---|
76 | x = center + np.linspace(-nsigmas*sigma, +nsigmas*sigma, npts) |
---|
77 | x = x[(x >= lb) & (x <= ub)] |
---|
78 | return x |
---|
79 | |
---|
80 | |
---|
81 | class GaussianDispersion(Dispersion): |
---|
82 | r""" |
---|
83 | Gaussian dispersion, with 1-$\sigma$ width. |
---|
84 | |
---|
85 | .. math:: |
---|
86 | |
---|
87 | w = \exp\left(-\tfrac12 (x - c)^2/\sigma^2\right) |
---|
88 | """ |
---|
89 | type = "gaussian" |
---|
90 | default = dict(npts=35, width=0, nsigmas=3) |
---|
91 | def _weights(self, center, sigma, lb, ub): |
---|
92 | # TODO: sample high probability regions more densely |
---|
93 | # i.e., step uniformly in cumulative density rather than x value |
---|
94 | # so weight = 1/Npts for all weights, but values are unevenly spaced |
---|
95 | x = self._linspace(center, sigma, lb, ub) |
---|
96 | px = np.exp((x-center)**2 / (-2.0 * sigma * sigma)) |
---|
97 | return x, px |
---|
98 | |
---|
99 | |
---|
100 | class RectangleDispersion(Dispersion): |
---|
101 | r""" |
---|
102 | Uniform dispersion, with width $\sqrt{3}\sigma$. |
---|
103 | |
---|
104 | .. math:: |
---|
105 | |
---|
106 | w = 1 |
---|
107 | """ |
---|
108 | type = "rectangle" |
---|
109 | default = dict(npts=35, width=0, nsigmas=1.70325) |
---|
110 | def _weights(self, center, sigma, lb, ub): |
---|
111 | x = self._linspace(center, sigma, lb, ub) |
---|
112 | x = x[np.fabs(x-center) <= np.fabs(sigma)*sqrt(3.0)] |
---|
113 | return x, np.ones_like(x) |
---|
114 | |
---|
115 | |
---|
116 | class LogNormalDispersion(Dispersion): |
---|
117 | r""" |
---|
118 | log Gaussian dispersion, with 1-$\sigma$ width. |
---|
119 | |
---|
120 | .. math:: |
---|
121 | |
---|
122 | w = \frac{\exp\left(-\tfrac12 (\ln x - c)^2/\sigma^2\right)}{x\sigma} |
---|
123 | """ |
---|
124 | type = "lognormal" |
---|
125 | default = dict(npts=80, width=0, nsigmas=8) |
---|
126 | def _weights(self, center, sigma, lb, ub): |
---|
127 | x = self._linspace(center, sigma, max(lb, 1e-8), max(ub, 1e-8)) |
---|
128 | # sigma in the lognormal function is in ln(R) space, thus needs converting |
---|
129 | sig = np.fabs(sigma/center) |
---|
130 | px = np.exp(-0.5*((np.log(x)-np.log(center))/sig)**2)/(x*sig) |
---|
131 | return x, px |
---|
132 | |
---|
133 | |
---|
134 | class SchulzDispersion(Dispersion): |
---|
135 | r""" |
---|
136 | Schultz dispersion, with 1-$\sigma$ width. |
---|
137 | |
---|
138 | .. math:: |
---|
139 | |
---|
140 | w = \frac{z^z\,R^{z-1}}{e^{Rz}\,c \Gamma(z)} |
---|
141 | |
---|
142 | where $c$ is the center of the distribution, $R = x/c$ and $z=(c/\sigma)^2$. |
---|
143 | |
---|
144 | This is evaluated using logarithms as |
---|
145 | |
---|
146 | .. math:: |
---|
147 | |
---|
148 | w = \exp\left(z \ln z + (z-1)\ln R - Rz - \ln c - \ln \Gamma(z) \right) |
---|
149 | """ |
---|
150 | type = "schulz" |
---|
151 | default = dict(npts=80, width=0, nsigmas=8) |
---|
152 | def _weights(self, center, sigma, lb, ub): |
---|
153 | x = self._linspace(center, sigma, max(lb, 1e-8), max(ub, 1e-8)) |
---|
154 | R = x/center |
---|
155 | z = (center/sigma)**2 |
---|
156 | arg = z*np.log(z) + (z-1)*np.log(R) - R*z - np.log(center) - gammaln(z) |
---|
157 | px = np.exp(arg) |
---|
158 | return x, px |
---|
159 | |
---|
160 | |
---|
161 | class ArrayDispersion(Dispersion): |
---|
162 | r""" |
---|
163 | Empirical dispersion curve. |
---|
164 | |
---|
165 | Use :meth:`set_weights` to set $w = f(x)$. |
---|
166 | """ |
---|
167 | type = "array" |
---|
168 | default = dict(npts=35, width=0, nsigmas=1) |
---|
169 | def __init__(self, npts=None, width=None, nsigmas=None): |
---|
170 | Dispersion.__init__(self, npts, width, nsigmas) |
---|
171 | self.values = np.array([0.], 'd') |
---|
172 | self.weights = np.array([1.], 'd') |
---|
173 | |
---|
174 | def set_weights(self, values, weights): |
---|
175 | """ |
---|
176 | Set the weights for the given x values. |
---|
177 | """ |
---|
178 | self.values = np.ascontiguousarray(values, 'd') |
---|
179 | self.weights = np.ascontiguousarray(weights, 'd') |
---|
180 | self.npts = len(values) |
---|
181 | |
---|
182 | def _weights(self, center, sigma, lb, ub): |
---|
183 | # TODO: rebin the array dispersion using npts |
---|
184 | # TODO: use a distribution that can be recentered and scaled |
---|
185 | x = self.values |
---|
186 | #x = center + self.values*sigma |
---|
187 | idx = (x >= lb) & (x <= ub) |
---|
188 | x = x[idx] |
---|
189 | px = self.weights[idx] |
---|
190 | return x, px |
---|
191 | |
---|
192 | |
---|
193 | # dispersion name -> disperser lookup table. |
---|
194 | # Maintain order since this is used by sasview GUI to order the options in |
---|
195 | # the dispersion type combobox. |
---|
196 | MODELS = OrderedDict((d.type, d) for d in ( |
---|
197 | RectangleDispersion, |
---|
198 | ArrayDispersion, |
---|
199 | LogNormalDispersion, |
---|
200 | GaussianDispersion, |
---|
201 | SchulzDispersion, |
---|
202 | )) |
---|
203 | |
---|
204 | |
---|
205 | def get_weights(disperser, n, width, nsigmas, value, limits, relative): |
---|
206 | """ |
---|
207 | Return the set of values and weights for a polydisperse parameter. |
---|
208 | |
---|
209 | *disperser* is the name of the disperser. |
---|
210 | |
---|
211 | *n* is the number of points in the weight vector. |
---|
212 | |
---|
213 | *width* is the width of the disperser distribution. |
---|
214 | |
---|
215 | *nsigmas* is the number of sigmas to span for the dispersion convolution. |
---|
216 | |
---|
217 | *value* is the value of the parameter in the model. |
---|
218 | |
---|
219 | *limits* is [lb, ub], the lower and upper bound on the possible values. |
---|
220 | |
---|
221 | *relative* is true if *width* is defined in proportion to the value |
---|
222 | of the parameter, and false if it is an absolute width. |
---|
223 | |
---|
224 | Returns *(value, weight)*, where *value* and *weight* are vectors. |
---|
225 | """ |
---|
226 | if disperser == "array": |
---|
227 | raise NotImplementedError("Don't handle arrays through get_weights;" |
---|
228 | " use values and weights directly") |
---|
229 | cls = MODELS[disperser] |
---|
230 | obj = cls(n, width, nsigmas) |
---|
231 | v, w = obj.get_weights(value, limits[0], limits[1], relative) |
---|
232 | return v, w/np.sum(w) |
---|
233 | |
---|
234 | |
---|
235 | def plot_weights(model_info, mesh): |
---|
236 | # type: (ModelInfo, List[Tuple[float, np.ndarray, np.ndarray]]) -> None |
---|
237 | """ |
---|
238 | Plot the weights returned by :func:`get_weights`. |
---|
239 | |
---|
240 | *model_info* defines model parameters, etc. |
---|
241 | |
---|
242 | *mesh* is a list of tuples containing (*value*, *dispersity*, *weights*) |
---|
243 | for each parameter, where (*dispersity*, *weights*) pairs are the |
---|
244 | distributions to be plotted. |
---|
245 | """ |
---|
246 | import pylab |
---|
247 | |
---|
248 | if any(len(dispersity) > 1 for value, dispersity, weights in mesh): |
---|
249 | labels = [p.name for p in model_info.parameters.call_parameters] |
---|
250 | #pylab.interactive(True) |
---|
251 | pylab.figure() |
---|
252 | for (v, x, w), s in zip(mesh, labels): |
---|
253 | if len(x) > 1: |
---|
254 | pylab.plot(x, w, '-o', label=s) |
---|
255 | pylab.grid(True) |
---|
256 | pylab.legend() |
---|
257 | #pylab.show() |
---|