[87985ca] | 1 | """ |
---|
| 2 | Sasview model constructor. |
---|
| 3 | |
---|
| 4 | Given a module defining an OpenCL kernel such as sasmodels.models.cylinder, |
---|
| 5 | create a sasview model class to run that kernel as follows:: |
---|
| 6 | |
---|
| 7 | from sasmodels.sasview_model import make_class |
---|
| 8 | from sasmodels.models import cylinder |
---|
| 9 | CylinderModel = make_class(cylinder, dtype='single') |
---|
| 10 | |
---|
| 11 | The model parameters for sasmodels are different from those in sasview. |
---|
| 12 | When reloading previously saved models, the parameters should be converted |
---|
| 13 | using :func:`sasmodels.convert.convert`. |
---|
| 14 | """ |
---|
| 15 | |
---|
| 16 | # TODO: add a sasview=>sasmodels parameter translation layer |
---|
| 17 | # this will allow us to use the new sasmodels as drop in replacements, and |
---|
| 18 | # delay renaming parameters until all models have been converted. |
---|
| 19 | |
---|
[ce27e21] | 20 | import math |
---|
| 21 | from copy import deepcopy |
---|
[ff7119b] | 22 | import warnings |
---|
[ce27e21] | 23 | |
---|
| 24 | import numpy as np |
---|
| 25 | |
---|
[ff7119b] | 26 | try: |
---|
[f786ff3] | 27 | from .kernelcl import load_model |
---|
[de0c4ba] | 28 | except ImportError, exc: |
---|
[5d4777d] | 29 | warnings.warn(str(exc)) |
---|
[250fa25] | 30 | warnings.warn("using ctypes instead") |
---|
[f786ff3] | 31 | from .kerneldll import load_model |
---|
[ff7119b] | 32 | |
---|
| 33 | |
---|
[0a82216] | 34 | def make_class(kernel_module, dtype='single', namestyle='name'): |
---|
[ff7119b] | 35 | """ |
---|
| 36 | Load the sasview model defined in *kernel_module*. |
---|
[87985ca] | 37 | |
---|
| 38 | Returns a class that can be used directly as a sasview model. |
---|
[0a82216] | 39 | |
---|
| 40 | Defaults to using the new name for a model. Setting namestyle='name' |
---|
| 41 | will produce a class with a name compatible with SasView |
---|
[ff7119b] | 42 | """ |
---|
[de0c4ba] | 43 | model = load_model(kernel_module, dtype=dtype) |
---|
[32c160a] | 44 | def __init__(self, multfactor=1): |
---|
[a7684e5] | 45 | SasviewModel.__init__(self, model) |
---|
| 46 | attrs = dict(__init__=__init__) |
---|
[de0c4ba] | 47 | ConstructedModel = type(model.info[namestyle], (SasviewModel,), attrs) |
---|
[ce27e21] | 48 | return ConstructedModel |
---|
| 49 | |
---|
| 50 | class SasviewModel(object): |
---|
| 51 | """ |
---|
| 52 | Sasview wrapper for opencl/ctypes model. |
---|
| 53 | """ |
---|
| 54 | def __init__(self, model): |
---|
| 55 | """Initialization""" |
---|
| 56 | self._model = model |
---|
| 57 | |
---|
| 58 | self.name = model.info['name'] |
---|
[3271e20] | 59 | self.oldname = model.info['oldname'] |
---|
[ce27e21] | 60 | self.description = model.info['description'] |
---|
| 61 | self.category = None |
---|
| 62 | self.multiplicity_info = None |
---|
| 63 | self.is_multifunc = False |
---|
| 64 | |
---|
| 65 | ## interpret the parameters |
---|
| 66 | ## TODO: reorganize parameter handling |
---|
| 67 | self.details = dict() |
---|
| 68 | self.params = dict() |
---|
| 69 | self.dispersion = dict() |
---|
| 70 | partype = model.info['partype'] |
---|
[de0c4ba] | 71 | for name, units, default, limits, ptype, description in model.info['parameters']: |
---|
[ce27e21] | 72 | self.params[name] = default |
---|
[de0c4ba] | 73 | self.details[name] = [units] + limits |
---|
[ce27e21] | 74 | |
---|
| 75 | for name in partype['pd-2d']: |
---|
| 76 | self.dispersion[name] = { |
---|
| 77 | 'width': 0, |
---|
| 78 | 'npts': 35, |
---|
[1780d59] | 79 | 'nsigmas': 3, |
---|
[ce27e21] | 80 | 'type': 'gaussian', |
---|
| 81 | } |
---|
| 82 | |
---|
| 83 | self.orientation_params = ( |
---|
| 84 | partype['orientation'] |
---|
[de0c4ba] | 85 | + [n + '.width' for n in partype['orientation']] |
---|
[ce27e21] | 86 | + partype['magnetic']) |
---|
| 87 | self.magnetic_params = partype['magnetic'] |
---|
[de0c4ba] | 88 | self.fixed = [n + '.width' for n in partype['pd-2d']] |
---|
[ce27e21] | 89 | self.non_fittable = [] |
---|
| 90 | |
---|
| 91 | ## independent parameter name and unit [string] |
---|
[de0c4ba] | 92 | self.input_name = model.info.get("input_name", "Q") |
---|
| 93 | self.input_unit = model.info.get("input_unit", "A^{-1}") |
---|
| 94 | self.output_name = model.info.get("output_name", "Intensity") |
---|
| 95 | self.output_unit = model.info.get("output_unit", "cm^{-1}") |
---|
[ce27e21] | 96 | |
---|
[87c722e] | 97 | ## _persistency_dict is used by sas.perspectives.fitting.basepage |
---|
[ce27e21] | 98 | ## to store dispersity reference. |
---|
| 99 | ## TODO: _persistency_dict to persistency_dict throughout sasview |
---|
| 100 | self._persistency_dict = {} |
---|
| 101 | |
---|
| 102 | ## New fields introduced for opencl rewrite |
---|
| 103 | self.cutoff = 1e-5 |
---|
| 104 | |
---|
| 105 | def __str__(self): |
---|
| 106 | """ |
---|
| 107 | :return: string representation |
---|
| 108 | """ |
---|
| 109 | return self.name |
---|
| 110 | |
---|
| 111 | def is_fittable(self, par_name): |
---|
| 112 | """ |
---|
| 113 | Check if a given parameter is fittable or not |
---|
| 114 | |
---|
| 115 | :param par_name: the parameter name to check |
---|
| 116 | """ |
---|
| 117 | return par_name.lower() in self.fixed |
---|
| 118 | #For the future |
---|
| 119 | #return self.params[str(par_name)].is_fittable() |
---|
| 120 | |
---|
| 121 | |
---|
| 122 | def getProfile(self): |
---|
| 123 | """ |
---|
| 124 | Get SLD profile |
---|
| 125 | |
---|
| 126 | : return: (z, beta) where z is a list of depth of the transition points |
---|
| 127 | beta is a list of the corresponding SLD values |
---|
| 128 | """ |
---|
| 129 | return None, None |
---|
| 130 | |
---|
| 131 | def setParam(self, name, value): |
---|
| 132 | """ |
---|
| 133 | Set the value of a model parameter |
---|
| 134 | |
---|
| 135 | :param name: name of the parameter |
---|
| 136 | :param value: value of the parameter |
---|
| 137 | |
---|
| 138 | """ |
---|
| 139 | # Look for dispersion parameters |
---|
| 140 | toks = name.split('.') |
---|
[de0c4ba] | 141 | if len(toks) == 2: |
---|
[ce27e21] | 142 | for item in self.dispersion.keys(): |
---|
[de0c4ba] | 143 | if item.lower() == toks[0].lower(): |
---|
[ce27e21] | 144 | for par in self.dispersion[item]: |
---|
| 145 | if par.lower() == toks[1].lower(): |
---|
| 146 | self.dispersion[item][par] = value |
---|
| 147 | return |
---|
| 148 | else: |
---|
| 149 | # Look for standard parameter |
---|
| 150 | for item in self.params.keys(): |
---|
[de0c4ba] | 151 | if item.lower() == name.lower(): |
---|
[ce27e21] | 152 | self.params[item] = value |
---|
| 153 | return |
---|
| 154 | |
---|
| 155 | raise ValueError, "Model does not contain parameter %s" % name |
---|
| 156 | |
---|
| 157 | def getParam(self, name): |
---|
| 158 | """ |
---|
| 159 | Set the value of a model parameter |
---|
| 160 | |
---|
| 161 | :param name: name of the parameter |
---|
| 162 | |
---|
| 163 | """ |
---|
| 164 | # Look for dispersion parameters |
---|
| 165 | toks = name.split('.') |
---|
[de0c4ba] | 166 | if len(toks) == 2: |
---|
[ce27e21] | 167 | for item in self.dispersion.keys(): |
---|
[de0c4ba] | 168 | if item.lower() == toks[0].lower(): |
---|
[ce27e21] | 169 | for par in self.dispersion[item]: |
---|
| 170 | if par.lower() == toks[1].lower(): |
---|
| 171 | return self.dispersion[item][par] |
---|
| 172 | else: |
---|
| 173 | # Look for standard parameter |
---|
| 174 | for item in self.params.keys(): |
---|
[de0c4ba] | 175 | if item.lower() == name.lower(): |
---|
[ce27e21] | 176 | return self.params[item] |
---|
| 177 | |
---|
| 178 | raise ValueError, "Model does not contain parameter %s" % name |
---|
| 179 | |
---|
| 180 | def getParamList(self): |
---|
| 181 | """ |
---|
| 182 | Return a list of all available parameters for the model |
---|
| 183 | """ |
---|
[de0c4ba] | 184 | param_list = self.params.keys() |
---|
[ce27e21] | 185 | # WARNING: Extending the list with the dispersion parameters |
---|
[de0c4ba] | 186 | param_list.extend(self.getDispParamList()) |
---|
| 187 | return param_list |
---|
[ce27e21] | 188 | |
---|
| 189 | def getDispParamList(self): |
---|
| 190 | """ |
---|
| 191 | Return a list of all available parameters for the model |
---|
| 192 | """ |
---|
[1780d59] | 193 | # TODO: fix test so that parameter order doesn't matter |
---|
[de0c4ba] | 194 | ret = ['%s.%s' % (d.lower(), p) |
---|
[1780d59] | 195 | for d in self._model.info['partype']['pd-2d'] |
---|
| 196 | for p in ('npts', 'nsigmas', 'width')] |
---|
| 197 | #print ret |
---|
| 198 | return ret |
---|
[ce27e21] | 199 | |
---|
| 200 | def clone(self): |
---|
| 201 | """ Return a identical copy of self """ |
---|
| 202 | return deepcopy(self) |
---|
| 203 | |
---|
| 204 | def run(self, x=0.0): |
---|
| 205 | """ |
---|
| 206 | Evaluate the model |
---|
| 207 | |
---|
| 208 | :param x: input q, or [q,phi] |
---|
| 209 | |
---|
| 210 | :return: scattering function P(q) |
---|
| 211 | |
---|
| 212 | **DEPRECATED**: use calculate_Iq instead |
---|
| 213 | """ |
---|
[de0c4ba] | 214 | if isinstance(x, (list, tuple)): |
---|
[ce27e21] | 215 | q, phi = x |
---|
| 216 | return self.calculate_Iq([q * math.cos(phi)], |
---|
| 217 | [q * math.sin(phi)])[0] |
---|
| 218 | else: |
---|
| 219 | return self.calculate_Iq([float(x)])[0] |
---|
| 220 | |
---|
| 221 | |
---|
| 222 | def runXY(self, x=0.0): |
---|
| 223 | """ |
---|
| 224 | Evaluate the model in cartesian coordinates |
---|
| 225 | |
---|
| 226 | :param x: input q, or [qx, qy] |
---|
| 227 | |
---|
| 228 | :return: scattering function P(q) |
---|
| 229 | |
---|
| 230 | **DEPRECATED**: use calculate_Iq instead |
---|
| 231 | """ |
---|
[de0c4ba] | 232 | if isinstance(x, (list, tuple)): |
---|
| 233 | return self.calculate_Iq([float(x[0])], [float(x[1])])[0] |
---|
[ce27e21] | 234 | else: |
---|
| 235 | return self.calculate_Iq([float(x)])[0] |
---|
| 236 | |
---|
| 237 | def evalDistribution(self, qdist): |
---|
| 238 | """ |
---|
| 239 | Evaluate a distribution of q-values. |
---|
| 240 | |
---|
| 241 | * For 1D, a numpy array is expected as input: :: |
---|
| 242 | |
---|
| 243 | evalDistribution(q) |
---|
| 244 | |
---|
| 245 | where q is a numpy array. |
---|
| 246 | |
---|
| 247 | * For 2D, a list of numpy arrays are expected: [qx,qy], |
---|
| 248 | with 1D arrays:: |
---|
| 249 | |
---|
| 250 | qx = [ qx[0], qx[1], qx[2], ....] |
---|
| 251 | |
---|
| 252 | and:: |
---|
| 253 | |
---|
| 254 | qy = [ qy[0], qy[1], qy[2], ....] |
---|
| 255 | |
---|
| 256 | Then get :: |
---|
| 257 | |
---|
| 258 | q = numpy.sqrt(qx^2+qy^2) |
---|
| 259 | |
---|
| 260 | that is a qr in 1D array:: |
---|
| 261 | |
---|
| 262 | q = [q[0], q[1], q[2], ....] |
---|
| 263 | |
---|
| 264 | |
---|
| 265 | :param qdist: ndarray of scalar q-values or list [qx,qy] where qx,qy are 1D ndarrays |
---|
| 266 | """ |
---|
[de0c4ba] | 267 | if isinstance(qdist, (list, tuple)): |
---|
[ce27e21] | 268 | # Check whether we have a list of ndarrays [qx,qy] |
---|
| 269 | qx, qy = qdist |
---|
[5d4777d] | 270 | partype = self._model.info['partype'] |
---|
| 271 | if not partype['orientation'] and not partype['magnetic']: |
---|
[de0c4ba] | 272 | return self.calculate_Iq(np.sqrt(qx ** 2 + qy ** 2)) |
---|
[5d4777d] | 273 | else: |
---|
| 274 | return self.calculate_Iq(qx, qy) |
---|
[ce27e21] | 275 | |
---|
| 276 | elif isinstance(qdist, np.ndarray): |
---|
| 277 | # We have a simple 1D distribution of q-values |
---|
| 278 | return self.calculate_Iq(qdist) |
---|
| 279 | |
---|
| 280 | else: |
---|
[de0c4ba] | 281 | raise TypeError("evalDistribution expects q or [qx, qy], not %r" % type(qdist)) |
---|
[ce27e21] | 282 | |
---|
| 283 | def calculate_Iq(self, *args): |
---|
[ff7119b] | 284 | """ |
---|
| 285 | Calculate Iq for one set of q with the current parameters. |
---|
| 286 | |
---|
| 287 | If the model is 1D, use *q*. If 2D, use *qx*, *qy*. |
---|
| 288 | |
---|
| 289 | This should NOT be used for fitting since it copies the *q* vectors |
---|
| 290 | to the card for each evaluation. |
---|
| 291 | """ |
---|
[ce27e21] | 292 | q_vectors = [np.asarray(q) for q in args] |
---|
| 293 | fn = self._model(self._model.make_input(q_vectors)) |
---|
| 294 | pars = [self.params[v] for v in fn.fixed_pars] |
---|
| 295 | pd_pars = [self._get_weights(p) for p in fn.pd_pars] |
---|
| 296 | result = fn(pars, pd_pars, self.cutoff) |
---|
| 297 | fn.input.release() |
---|
| 298 | fn.release() |
---|
| 299 | return result |
---|
| 300 | |
---|
| 301 | def calculate_ER(self): |
---|
| 302 | """ |
---|
| 303 | Calculate the effective radius for P(q)*S(q) |
---|
| 304 | |
---|
| 305 | :return: the value of the effective radius |
---|
| 306 | """ |
---|
| 307 | ER = self._model.info.get('ER', None) |
---|
| 308 | if ER is None: |
---|
| 309 | return 1.0 |
---|
| 310 | else: |
---|
| 311 | vol_pars = self._model.info['partype']['volume'] |
---|
| 312 | values, weights = self._dispersion_mesh(vol_pars) |
---|
| 313 | fv = ER(*values) |
---|
[32c160a] | 314 | #print values[0].shape, weights.shape, fv.shape |
---|
[de0c4ba] | 315 | return np.sum(weights * fv) / np.sum(weights) |
---|
[ce27e21] | 316 | |
---|
| 317 | def calculate_VR(self): |
---|
| 318 | """ |
---|
| 319 | Calculate the volf ratio for P(q)*S(q) |
---|
| 320 | |
---|
| 321 | :return: the value of the volf ratio |
---|
| 322 | """ |
---|
[32c160a] | 323 | VR = self._model.info.get('VR', None) |
---|
[ce27e21] | 324 | if VR is None: |
---|
| 325 | return 1.0 |
---|
| 326 | else: |
---|
| 327 | vol_pars = self._model.info['partype']['volume'] |
---|
| 328 | values, weights = self._dispersion_mesh(vol_pars) |
---|
[de0c4ba] | 329 | whole, part = VR(*values) |
---|
| 330 | return np.sum(weights * part) / np.sum(weights * whole) |
---|
[ce27e21] | 331 | |
---|
| 332 | def set_dispersion(self, parameter, dispersion): |
---|
| 333 | """ |
---|
| 334 | Set the dispersion object for a model parameter |
---|
| 335 | |
---|
| 336 | :param parameter: name of the parameter [string] |
---|
| 337 | :param dispersion: dispersion object of type Dispersion |
---|
| 338 | """ |
---|
[1780d59] | 339 | if parameter.lower() in (s.lower() for s in self.params.keys()): |
---|
| 340 | # TODO: Store the disperser object directly in the model. |
---|
| 341 | # The current method of creating one on the fly whenever it is |
---|
| 342 | # needed is kind of funky. |
---|
| 343 | # Note: can't seem to get disperser parameters from sasview |
---|
| 344 | # (1) Could create a sasview model that has not yet # been |
---|
| 345 | # converted, assign the disperser to one of its polydisperse |
---|
| 346 | # parameters, then retrieve the disperser parameters from the |
---|
| 347 | # sasview model. (2) Could write a disperser parameter retriever |
---|
| 348 | # in sasview. (3) Could modify sasview to use sasmodels.weights |
---|
| 349 | # dispersers. |
---|
| 350 | # For now, rely on the fact that the sasview only ever uses |
---|
| 351 | # new dispersers in the set_dispersion call and create a new |
---|
| 352 | # one instead of trying to assign parameters. |
---|
| 353 | from . import weights |
---|
| 354 | disperser = weights.dispersers[dispersion.__class__.__name__] |
---|
| 355 | dispersion = weights.models[disperser]() |
---|
[ce27e21] | 356 | self.dispersion[parameter] = dispersion.get_pars() |
---|
| 357 | else: |
---|
| 358 | raise ValueError("%r is not a dispersity or orientation parameter") |
---|
| 359 | |
---|
| 360 | def _dispersion_mesh(self, pars): |
---|
| 361 | """ |
---|
| 362 | Create a mesh grid of dispersion parameters and weights. |
---|
| 363 | |
---|
| 364 | Returns [p1,p2,...],w where pj is a vector of values for parameter j |
---|
| 365 | and w is a vector containing the products for weights for each |
---|
| 366 | parameter set in the vector. |
---|
| 367 | """ |
---|
| 368 | values, weights = zip(*[self._get_weights(p) for p in pars]) |
---|
| 369 | values = [v.flatten() for v in np.meshgrid(*values)] |
---|
| 370 | weights = np.vstack([v.flatten() for v in np.meshgrid(*weights)]) |
---|
[32c160a] | 371 | weights = np.prod(weights, axis=0) |
---|
[ce27e21] | 372 | return values, weights |
---|
| 373 | |
---|
| 374 | def _get_weights(self, par): |
---|
[de0c4ba] | 375 | """ |
---|
| 376 | Return dispersion weights |
---|
| 377 | :param par parameter name |
---|
| 378 | """ |
---|
[ce27e21] | 379 | from . import weights |
---|
| 380 | |
---|
| 381 | relative = self._model.info['partype']['pd-rel'] |
---|
| 382 | limits = self._model.info['limits'] |
---|
| 383 | dis = self.dispersion[par] |
---|
[de0c4ba] | 384 | v, w = weights.get_weights( |
---|
[1780d59] | 385 | dis['type'], dis['npts'], dis['width'], dis['nsigmas'], |
---|
[ce27e21] | 386 | self.params[par], limits[par], par in relative) |
---|
[de0c4ba] | 387 | return v, w / w.max() |
---|
[1780d59] | 388 | |
---|