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