[803f835] | 1 | """ |
---|
| 2 | Class interface to the model calculator. |
---|
| 3 | |
---|
| 4 | Calling a model is somewhat non-trivial since the functions called depend |
---|
| 5 | on the data type. For 1D data the *Iq* kernel needs to be called, for |
---|
| 6 | 2D data the *Iqxy* kernel needs to be called, and for SESANS data the |
---|
| 7 | *Iq* kernel needs to be called followed by a Hankel transform. Before |
---|
| 8 | the kernel is called an appropriate *q* calculation vector needs to be |
---|
| 9 | constructed. This is not the simple *q* vector where you have measured |
---|
| 10 | the data since the resolution calculation will require values beyond the |
---|
| 11 | range of the measured data. After the calculation the resolution calculator |
---|
| 12 | must be called to return the predicted value for each measured data point. |
---|
| 13 | |
---|
| 14 | :class:`DirectModel` is a callable object that takes *parameter=value* |
---|
| 15 | keyword arguments and returns the appropriate theory values for the data. |
---|
| 16 | |
---|
| 17 | :class:`DataMixin` does the real work of interpreting the data and calling |
---|
| 18 | the model calculator. This is used by :class:`DirectModel`, which uses |
---|
| 19 | direct parameter values and by :class:`bumps_model.Experiment` which wraps |
---|
| 20 | the parameter values in boxes so that the user can set fitting ranges, etc. |
---|
| 21 | on the individual parameters and send the model to the Bumps optimizers. |
---|
| 22 | """ |
---|
| 23 | from __future__ import print_function |
---|
[ae7b97b] | 24 | |
---|
[7ae2b7f] | 25 | import numpy as np # type: ignore |
---|
[ae7b97b] | 26 | |
---|
[7ae2b7f] | 27 | # TODO: fix sesans module |
---|
| 28 | from . import sesans # type: ignore |
---|
[6d6508e] | 29 | from . import weights |
---|
[7cf2cfd] | 30 | from . import resolution |
---|
| 31 | from . import resolution2d |
---|
[9eb3632] | 32 | from .details import build_details |
---|
[6d6508e] | 33 | |
---|
[a5b8477] | 34 | try: |
---|
| 35 | from typing import Optional, Dict, Tuple |
---|
| 36 | except ImportError: |
---|
| 37 | pass |
---|
| 38 | else: |
---|
| 39 | from .data import Data |
---|
| 40 | from .kernel import Kernel, KernelModel |
---|
| 41 | from .modelinfo import Parameter, ParameterSet |
---|
| 42 | |
---|
[0ff62d4] | 43 | def call_kernel(calculator, pars, cutoff=0., mono=False): |
---|
[a5b8477] | 44 | # type: (Kernel, ParameterSet, float, bool) -> np.ndarray |
---|
[6d6508e] | 45 | """ |
---|
| 46 | Call *kernel* returned from *model.make_kernel* with parameters *pars*. |
---|
| 47 | |
---|
| 48 | *cutoff* is the limiting value for the product of dispersion weights used |
---|
| 49 | to perform the multidimensional dispersion calculation more quickly at a |
---|
| 50 | slight cost to accuracy. The default value of *cutoff=0* integrates over |
---|
| 51 | the entire dispersion cube. Using *cutoff=1e-5* can be 50% faster, but |
---|
| 52 | with an error of about 1%, which is usually less than the measurement |
---|
| 53 | uncertainty. |
---|
| 54 | |
---|
| 55 | *mono* is True if polydispersity should be set to none on all parameters. |
---|
| 56 | """ |
---|
[0ff62d4] | 57 | parameters = calculator.info.parameters |
---|
[6d6508e] | 58 | if mono: |
---|
| 59 | active = lambda name: False |
---|
[0ff62d4] | 60 | elif calculator.dim == '1d': |
---|
[6d6508e] | 61 | active = lambda name: name in parameters.pd_1d |
---|
[0ff62d4] | 62 | elif calculator.dim == '2d': |
---|
[6d6508e] | 63 | active = lambda name: name in parameters.pd_2d |
---|
| 64 | else: |
---|
| 65 | active = lambda name: True |
---|
| 66 | |
---|
[9eb3632] | 67 | #print("pars",[p.id for p in parameters.call_parameters]) |
---|
[6d6508e] | 68 | vw_pairs = [(get_weights(p, pars) if active(p.name) |
---|
[a738209] | 69 | else ([pars.get(p.name, p.default)], [1.0])) |
---|
[6d6508e] | 70 | for p in parameters.call_parameters] |
---|
| 71 | |
---|
[9eb3632] | 72 | call_details, values, is_magnetic = build_details(calculator, vw_pairs) |
---|
[32e3c9b] | 73 | #print("values:", values) |
---|
[9eb3632] | 74 | return calculator(call_details, values, cutoff, is_magnetic) |
---|
[6d6508e] | 75 | |
---|
| 76 | def get_weights(parameter, values): |
---|
[a5b8477] | 77 | # type: (Parameter, Dict[str, float]) -> Tuple[np.ndarray, np.ndarray] |
---|
[6d6508e] | 78 | """ |
---|
| 79 | Generate the distribution for parameter *name* given the parameter values |
---|
| 80 | in *pars*. |
---|
| 81 | |
---|
| 82 | Uses "name", "name_pd", "name_pd_type", "name_pd_n", "name_pd_sigma" |
---|
| 83 | from the *pars* dictionary for parameter value and parameter dispersion. |
---|
| 84 | """ |
---|
| 85 | value = float(values.get(parameter.name, parameter.default)) |
---|
| 86 | relative = parameter.relative_pd |
---|
| 87 | limits = parameter.limits |
---|
| 88 | disperser = values.get(parameter.name+'_pd_type', 'gaussian') |
---|
| 89 | npts = values.get(parameter.name+'_pd_n', 0) |
---|
| 90 | width = values.get(parameter.name+'_pd', 0.0) |
---|
| 91 | nsigma = values.get(parameter.name+'_pd_nsigma', 3.0) |
---|
| 92 | if npts == 0 or width == 0: |
---|
[a738209] | 93 | return [value], [1.0] |
---|
[6d6508e] | 94 | value, weight = weights.get_weights( |
---|
| 95 | disperser, npts, width, nsigma, value, limits, relative) |
---|
| 96 | return value, weight / np.sum(weight) |
---|
[ae7b97b] | 97 | |
---|
[7cf2cfd] | 98 | class DataMixin(object): |
---|
| 99 | """ |
---|
| 100 | DataMixin captures the common aspects of evaluating a SAS model for a |
---|
| 101 | particular data set, including calculating Iq and evaluating the |
---|
| 102 | resolution function. It is used in particular by :class:`DirectModel`, |
---|
| 103 | which evaluates a SAS model parameters as key word arguments to the |
---|
| 104 | calculator method, and by :class:`bumps_model.Experiment`, which wraps the |
---|
| 105 | model and data for use with the Bumps fitting engine. It is not |
---|
| 106 | currently used by :class:`sasview_model.SasviewModel` since this will |
---|
| 107 | require a number of changes to SasView before we can do it. |
---|
[803f835] | 108 | |
---|
| 109 | :meth:`_interpret_data` initializes the data structures necessary |
---|
| 110 | to manage the calculations. This sets attributes in the child class |
---|
| 111 | such as *data_type* and *resolution*. |
---|
| 112 | |
---|
| 113 | :meth:`_calc_theory` evaluates the model at the given control values. |
---|
| 114 | |
---|
| 115 | :meth:`_set_data` sets the intensity data in the data object, |
---|
| 116 | possibly with random noise added. This is useful for simulating a |
---|
| 117 | dataset with the results from :meth:`_calc_theory`. |
---|
[7cf2cfd] | 118 | """ |
---|
| 119 | def _interpret_data(self, data, model): |
---|
[a5b8477] | 120 | # type: (Data, KernelModel) -> None |
---|
[803f835] | 121 | # pylint: disable=attribute-defined-outside-init |
---|
| 122 | |
---|
[7cf2cfd] | 123 | self._data = data |
---|
| 124 | self._model = model |
---|
| 125 | |
---|
| 126 | # interpret data |
---|
| 127 | if hasattr(data, 'lam'): |
---|
| 128 | self.data_type = 'sesans' |
---|
| 129 | elif hasattr(data, 'qx_data'): |
---|
| 130 | self.data_type = 'Iqxy' |
---|
[ea75043] | 131 | elif getattr(data, 'oriented', False): |
---|
| 132 | self.data_type = 'Iq-oriented' |
---|
[7cf2cfd] | 133 | else: |
---|
| 134 | self.data_type = 'Iq' |
---|
| 135 | |
---|
| 136 | if self.data_type == 'sesans': |
---|
| 137 | q = sesans.make_q(data.sample.zacceptance, data.Rmax) |
---|
[803f835] | 138 | index = slice(None, None) |
---|
| 139 | res = None |
---|
[7cf2cfd] | 140 | if data.y is not None: |
---|
[803f835] | 141 | Iq, dIq = data.y, data.dy |
---|
| 142 | else: |
---|
| 143 | Iq, dIq = None, None |
---|
[7cf2cfd] | 144 | #self._theory = np.zeros_like(q) |
---|
[02e70ff] | 145 | q_vectors = [q] |
---|
| 146 | q_mono = sesans.make_all_q(data) |
---|
[7cf2cfd] | 147 | elif self.data_type == 'Iqxy': |
---|
[6d6508e] | 148 | #if not model.info.parameters.has_2d: |
---|
[60eab2a] | 149 | # raise ValueError("not 2D without orientation or magnetic parameters") |
---|
[7cf2cfd] | 150 | q = np.sqrt(data.qx_data**2 + data.qy_data**2) |
---|
| 151 | qmin = getattr(data, 'qmin', 1e-16) |
---|
| 152 | qmax = getattr(data, 'qmax', np.inf) |
---|
| 153 | accuracy = getattr(data, 'accuracy', 'Low') |
---|
[803f835] | 154 | index = ~data.mask & (q >= qmin) & (q <= qmax) |
---|
[7cf2cfd] | 155 | if data.data is not None: |
---|
[803f835] | 156 | index &= ~np.isnan(data.data) |
---|
| 157 | Iq = data.data[index] |
---|
| 158 | dIq = data.err_data[index] |
---|
| 159 | else: |
---|
| 160 | Iq, dIq = None, None |
---|
| 161 | res = resolution2d.Pinhole2D(data=data, index=index, |
---|
| 162 | nsigma=3.0, accuracy=accuracy) |
---|
[7cf2cfd] | 163 | #self._theory = np.zeros_like(self.Iq) |
---|
[803f835] | 164 | q_vectors = res.q_calc |
---|
[02e70ff] | 165 | q_mono = [] |
---|
[7cf2cfd] | 166 | elif self.data_type == 'Iq': |
---|
[803f835] | 167 | index = (data.x >= data.qmin) & (data.x <= data.qmax) |
---|
[7cf2cfd] | 168 | if data.y is not None: |
---|
[803f835] | 169 | index &= ~np.isnan(data.y) |
---|
| 170 | Iq = data.y[index] |
---|
| 171 | dIq = data.dy[index] |
---|
| 172 | else: |
---|
| 173 | Iq, dIq = None, None |
---|
[7cf2cfd] | 174 | if getattr(data, 'dx', None) is not None: |
---|
[803f835] | 175 | q, dq = data.x[index], data.dx[index] |
---|
| 176 | if (dq > 0).any(): |
---|
| 177 | res = resolution.Pinhole1D(q, dq) |
---|
[7cf2cfd] | 178 | else: |
---|
[803f835] | 179 | res = resolution.Perfect1D(q) |
---|
| 180 | elif (getattr(data, 'dxl', None) is not None |
---|
| 181 | and getattr(data, 'dxw', None) is not None): |
---|
| 182 | res = resolution.Slit1D(data.x[index], |
---|
[4d8e0bb] | 183 | qx_width=data.dxl[index], |
---|
| 184 | qy_width=data.dxw[index]) |
---|
[7cf2cfd] | 185 | else: |
---|
[803f835] | 186 | res = resolution.Perfect1D(data.x[index]) |
---|
[7cf2cfd] | 187 | |
---|
| 188 | #self._theory = np.zeros_like(self.Iq) |
---|
[803f835] | 189 | q_vectors = [res.q_calc] |
---|
[02e70ff] | 190 | q_mono = [] |
---|
[ea75043] | 191 | elif self.data_type == 'Iq-oriented': |
---|
| 192 | index = (data.x >= data.qmin) & (data.x <= data.qmax) |
---|
| 193 | if data.y is not None: |
---|
| 194 | index &= ~np.isnan(data.y) |
---|
| 195 | Iq = data.y[index] |
---|
| 196 | dIq = data.dy[index] |
---|
| 197 | else: |
---|
| 198 | Iq, dIq = None, None |
---|
| 199 | if (getattr(data, 'dxl', None) is None |
---|
| 200 | or getattr(data, 'dxw', None) is None): |
---|
| 201 | raise ValueError("oriented sample with 1D data needs slit resolution") |
---|
| 202 | |
---|
| 203 | res = resolution2d.Slit2D(data.x[index], |
---|
| 204 | qx_width=data.dxw[index], |
---|
| 205 | qy_width=data.dxl[index]) |
---|
| 206 | q_vectors = res.q_calc |
---|
| 207 | q_mono = [] |
---|
[7cf2cfd] | 208 | else: |
---|
| 209 | raise ValueError("Unknown data type") # never gets here |
---|
| 210 | |
---|
| 211 | # Remember function inputs so we can delay loading the function and |
---|
| 212 | # so we can save/restore state |
---|
[02e70ff] | 213 | self._kernel_inputs = q_vectors |
---|
| 214 | self._kernel_mono_inputs = q_mono |
---|
[7cf2cfd] | 215 | self._kernel = None |
---|
[803f835] | 216 | self.Iq, self.dIq, self.index = Iq, dIq, index |
---|
| 217 | self.resolution = res |
---|
[7cf2cfd] | 218 | |
---|
| 219 | def _set_data(self, Iq, noise=None): |
---|
[a5b8477] | 220 | # type: (np.ndarray, Optional[float]) -> None |
---|
[803f835] | 221 | # pylint: disable=attribute-defined-outside-init |
---|
[7cf2cfd] | 222 | if noise is not None: |
---|
| 223 | self.dIq = Iq*noise*0.01 |
---|
| 224 | dy = self.dIq |
---|
| 225 | y = Iq + np.random.randn(*dy.shape) * dy |
---|
| 226 | self.Iq = y |
---|
[ea75043] | 227 | if self.data_type in ('Iq', 'Iq-oriented'): |
---|
[7cf2cfd] | 228 | self._data.dy[self.index] = dy |
---|
| 229 | self._data.y[self.index] = y |
---|
| 230 | elif self.data_type == 'Iqxy': |
---|
| 231 | self._data.data[self.index] = y |
---|
| 232 | elif self.data_type == 'sesans': |
---|
| 233 | self._data.y[self.index] = y |
---|
| 234 | else: |
---|
| 235 | raise ValueError("Unknown model") |
---|
| 236 | |
---|
| 237 | def _calc_theory(self, pars, cutoff=0.0): |
---|
[a5b8477] | 238 | # type: (ParameterSet, float) -> np.ndarray |
---|
[7cf2cfd] | 239 | if self._kernel is None: |
---|
[68e7f9d] | 240 | self._kernel = self._model.make_kernel(self._kernel_inputs) |
---|
| 241 | self._kernel_mono = (self._model.make_kernel(self._kernel_mono_inputs) |
---|
[ea75043] | 242 | if self._kernel_mono_inputs else None) |
---|
[7cf2cfd] | 243 | |
---|
| 244 | Iq_calc = call_kernel(self._kernel, pars, cutoff=cutoff) |
---|
[ea75043] | 245 | # TODO: may want to plot the raw Iq for other than oriented usans |
---|
| 246 | self.Iq_calc = None |
---|
[7cf2cfd] | 247 | if self.data_type == 'sesans': |
---|
[ea75043] | 248 | Iq_mono = (call_kernel(self._kernel_mono, pars, mono=True) |
---|
| 249 | if self._kernel_mono_inputs else None) |
---|
[02e70ff] | 250 | result = sesans.transform(self._data, |
---|
| 251 | self._kernel_inputs[0], Iq_calc, |
---|
| 252 | self._kernel_mono_inputs, Iq_mono) |
---|
[7cf2cfd] | 253 | else: |
---|
| 254 | result = self.resolution.apply(Iq_calc) |
---|
[ea75043] | 255 | if hasattr(self.resolution, 'nx'): |
---|
| 256 | self.Iq_calc = ( |
---|
| 257 | self.resolution.qx_calc, self.resolution.qy_calc, |
---|
| 258 | np.reshape(Iq_calc, (self.resolution.ny, self.resolution.nx)) |
---|
| 259 | ) |
---|
[02e70ff] | 260 | return result |
---|
[7cf2cfd] | 261 | |
---|
| 262 | |
---|
| 263 | class DirectModel(DataMixin): |
---|
[803f835] | 264 | """ |
---|
| 265 | Create a calculator object for a model. |
---|
| 266 | |
---|
| 267 | *data* is 1D SAS, 2D SAS or SESANS data |
---|
| 268 | |
---|
| 269 | *model* is a model calculator return from :func:`generate.load_model` |
---|
| 270 | |
---|
| 271 | *cutoff* is the polydispersity weight cutoff. |
---|
| 272 | """ |
---|
[7cf2cfd] | 273 | def __init__(self, data, model, cutoff=1e-5): |
---|
[a5b8477] | 274 | # type: (Data, KernelModel, float) -> None |
---|
[7cf2cfd] | 275 | self.model = model |
---|
| 276 | self.cutoff = cutoff |
---|
[803f835] | 277 | # Note: _interpret_data defines the model attributes |
---|
[7cf2cfd] | 278 | self._interpret_data(data, model) |
---|
[803f835] | 279 | |
---|
[16bc3fc] | 280 | def __call__(self, **pars): |
---|
[a5b8477] | 281 | # type: (**float) -> np.ndarray |
---|
[7cf2cfd] | 282 | return self._calc_theory(pars, cutoff=self.cutoff) |
---|
[803f835] | 283 | |
---|
[7cf2cfd] | 284 | def simulate_data(self, noise=None, **pars): |
---|
[a5b8477] | 285 | # type: (Optional[float], **float) -> None |
---|
[803f835] | 286 | """ |
---|
| 287 | Generate simulated data for the model. |
---|
| 288 | """ |
---|
[7cf2cfd] | 289 | Iq = self.__call__(**pars) |
---|
| 290 | self._set_data(Iq, noise=noise) |
---|
[ae7b97b] | 291 | |
---|
[803f835] | 292 | def main(): |
---|
[a5b8477] | 293 | # type: () -> None |
---|
[803f835] | 294 | """ |
---|
| 295 | Program to evaluate a particular model at a set of q values. |
---|
| 296 | """ |
---|
[ae7b97b] | 297 | import sys |
---|
[7cf2cfd] | 298 | from .data import empty_data1D, empty_data2D |
---|
[17bbadd] | 299 | from .core import load_model_info, build_model |
---|
[7cf2cfd] | 300 | |
---|
[ae7b97b] | 301 | if len(sys.argv) < 3: |
---|
[9404dd3] | 302 | print("usage: python -m sasmodels.direct_model modelname (q|qx,qy) par=val ...") |
---|
[ae7b97b] | 303 | sys.exit(1) |
---|
| 304 | model_name = sys.argv[1] |
---|
[aa4946b] | 305 | call = sys.argv[2].upper() |
---|
[17bbadd] | 306 | if call != "ER_VR": |
---|
[7cf2cfd] | 307 | try: |
---|
| 308 | values = [float(v) for v in call.split(',')] |
---|
[ee8f734] | 309 | except Exception: |
---|
[7cf2cfd] | 310 | values = [] |
---|
[aa4946b] | 311 | if len(values) == 1: |
---|
[7cf2cfd] | 312 | q, = values |
---|
| 313 | data = empty_data1D([q]) |
---|
[aa4946b] | 314 | elif len(values) == 2: |
---|
[803f835] | 315 | qx, qy = values |
---|
| 316 | data = empty_data2D([qx], [qy]) |
---|
[aa4946b] | 317 | else: |
---|
[9404dd3] | 318 | print("use q or qx,qy or ER or VR") |
---|
[aa4946b] | 319 | sys.exit(1) |
---|
[7cf2cfd] | 320 | else: |
---|
| 321 | data = empty_data1D([0.001]) # Data not used in ER/VR |
---|
| 322 | |
---|
[17bbadd] | 323 | model_info = load_model_info(model_name) |
---|
| 324 | model = build_model(model_info) |
---|
[7cf2cfd] | 325 | calculator = DirectModel(data, model) |
---|
[803f835] | 326 | pars = dict((k, float(v)) |
---|
[ae7b97b] | 327 | for pair in sys.argv[3:] |
---|
[803f835] | 328 | for k, v in [pair.split('=')]) |
---|
[17bbadd] | 329 | if call == "ER_VR": |
---|
| 330 | print(calculator.ER_VR(**pars)) |
---|
[aa4946b] | 331 | else: |
---|
[7cf2cfd] | 332 | Iq = calculator(**pars) |
---|
[9404dd3] | 333 | print(Iq[0]) |
---|
[ae7b97b] | 334 | |
---|
| 335 | if __name__ == "__main__": |
---|
[803f835] | 336 | main() |
---|