PageRenderTime 67ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/astropy/modeling/parameters.py

https://github.com/eteq/astropy
Python | 954 lines | 878 code | 41 blank | 35 comment | 48 complexity | dc76c575a33ce3274d200c8299f5a166 MD5 | raw file
  1. # Licensed under a 3-clause BSD style license - see LICENSE.rst
  2. """
  3. This module defines two classes that deal with parameters.
  4. It is unlikely users will need to work with these classes directly, unless they
  5. define their own models.
  6. """
  7. import functools
  8. import numbers
  9. import types
  10. import operator
  11. import numpy as np
  12. from .. import units as u
  13. from ..units import Quantity, UnitsError
  14. from ..utils import isiterable, OrderedDescriptor
  15. from .utils import array_repr_oneline
  16. from .utils import get_inputs_and_params
  17. __all__ = ['Parameter', 'InputParameterError', 'ParameterError']
  18. class ParameterError(Exception):
  19. """Generic exception class for all exceptions pertaining to Parameters."""
  20. class InputParameterError(ValueError, ParameterError):
  21. """Used for incorrect input parameter values and definitions."""
  22. class ParameterDefinitionError(ParameterError):
  23. """Exception in declaration of class-level Parameters."""
  24. def _tofloat(value):
  25. """Convert a parameter to float or float array"""
  26. if isiterable(value):
  27. try:
  28. value = np.asanyarray(value, dtype=float)
  29. except (TypeError, ValueError):
  30. # catch arrays with strings or user errors like different
  31. # types of parameters in a parameter set
  32. raise InputParameterError(
  33. "Parameter of {0} could not be converted to "
  34. "float".format(type(value)))
  35. elif isinstance(value, Quantity):
  36. # Quantities are fine as is
  37. pass
  38. elif isinstance(value, np.ndarray):
  39. # A scalar/dimensionless array
  40. value = float(value.item())
  41. elif isinstance(value, (numbers.Number, np.number)):
  42. value = float(value)
  43. elif isinstance(value, bool):
  44. raise InputParameterError(
  45. "Expected parameter to be of numerical type, not boolean")
  46. else:
  47. raise InputParameterError(
  48. "Don't know how to convert parameter of {0} to "
  49. "float".format(type(value)))
  50. return value
  51. # Helpers for implementing operator overloading on Parameter
  52. def _binary_arithmetic_operation(op, reflected=False):
  53. @functools.wraps(op)
  54. def wrapper(self, val):
  55. if self._model is None:
  56. return NotImplemented
  57. if self.unit is not None:
  58. self_value = Quantity(self.value, self.unit)
  59. else:
  60. self_value = self.value
  61. if reflected:
  62. return op(val, self_value)
  63. else:
  64. return op(self_value, val)
  65. return wrapper
  66. def _binary_comparison_operation(op):
  67. @functools.wraps(op)
  68. def wrapper(self, val):
  69. if self._model is None:
  70. if op is operator.lt:
  71. # Because OrderedDescriptor uses __lt__ to work, we need to
  72. # call the super method, but only when not bound to an instance
  73. # anyways
  74. return super(self.__class__, self).__lt__(val)
  75. else:
  76. return NotImplemented
  77. if self.unit is not None:
  78. self_value = Quantity(self.value, self.unit)
  79. else:
  80. self_value = self.value
  81. return op(self_value, val)
  82. return wrapper
  83. def _unary_arithmetic_operation(op):
  84. @functools.wraps(op)
  85. def wrapper(self):
  86. if self._model is None:
  87. return NotImplemented
  88. if self.unit is not None:
  89. self_value = Quantity(self.value, self.unit)
  90. else:
  91. self_value = self.value
  92. return op(self_value)
  93. return wrapper
  94. class Parameter(OrderedDescriptor):
  95. """
  96. Wraps individual parameters.
  97. This class represents a model's parameter (in a somewhat broad sense). It
  98. acts as both a descriptor that can be assigned to a class attribute to
  99. describe the parameters accepted by an individual model (this is called an
  100. "unbound parameter"), or it can act as a proxy for the parameter values on
  101. an individual model instance (called a "bound parameter").
  102. Parameter instances never store the actual value of the parameter directly.
  103. Rather, each instance of a model stores its own parameters parameter values
  104. in an array. A *bound* Parameter simply wraps the value in a Parameter
  105. proxy which provides some additional information about the parameter such
  106. as its constraints. In other words, this is a high-level interface to a
  107. model's adjustable parameter values.
  108. *Unbound* Parameters are not associated with any specific model instance,
  109. and are merely used by model classes to determine the names of their
  110. parameters and other information about each parameter such as their default
  111. values and default constraints.
  112. See :ref:`modeling-parameters` for more details.
  113. Parameters
  114. ----------
  115. name : str
  116. parameter name
  117. .. warning::
  118. The fact that `Parameter` accepts ``name`` as an argument is an
  119. implementation detail, and should not be used directly. When
  120. defining a new `Model` class, parameter names are always
  121. automatically defined by the class attribute they're assigned to.
  122. description : str
  123. parameter description
  124. default : float or array
  125. default value to use for this parameter
  126. unit : `~astropy.units.Unit`
  127. if specified, the parameter will be in these units, and when the
  128. parameter is updated in future, it should be set to a
  129. :class:`~astropy.units.Quantity` that has equivalent units.
  130. getter : callable
  131. a function that wraps the raw (internal) value of the parameter
  132. when returning the value through the parameter proxy (eg. a
  133. parameter may be stored internally as radians but returned to the
  134. user as degrees)
  135. setter : callable
  136. a function that wraps any values assigned to this parameter; should
  137. be the inverse of getter
  138. fixed : bool
  139. if True the parameter is not varied during fitting
  140. tied : callable or False
  141. if callable is supplied it provides a way to link the value of this
  142. parameter to another parameter (or some other arbitrary function)
  143. min : float
  144. the lower bound of a parameter
  145. max : float
  146. the upper bound of a parameter
  147. bounds : tuple
  148. specify min and max as a single tuple--bounds may not be specified
  149. simultaneously with min or max
  150. model : `Model` instance
  151. binds the the `Parameter` instance to a specific model upon
  152. instantiation; this should only be used internally for creating bound
  153. Parameters, and should not be used for `Parameter` descriptors defined
  154. as class attributes
  155. """
  156. constraints = ('fixed', 'tied', 'bounds', 'prior', 'posterior')
  157. """
  158. Types of constraints a parameter can have. Excludes 'min' and 'max'
  159. which are just aliases for the first and second elements of the 'bounds'
  160. constraint (which is represented as a 2-tuple). 'prior' and 'posterior'
  161. are available for use by user fitters but are not used by any built-in
  162. fitters as of this writing.
  163. """
  164. # Settings for OrderedDescriptor
  165. _class_attribute_ = '_parameters_'
  166. _name_attribute_ = '_name'
  167. def __init__(self, name='', description='', default=None, unit=None,
  168. getter=None, setter=None, fixed=False, tied=False, min=None,
  169. max=None, bounds=None, prior=None, posterior=None, model=None):
  170. super().__init__()
  171. self._name = name
  172. self.__doc__ = self._description = description.strip()
  173. # We only need to perform this check on unbound parameters
  174. if model is None and isinstance(default, Quantity):
  175. if unit is not None and not unit.is_equivalent(default.unit):
  176. raise ParameterDefinitionError(
  177. "parameter default {0} does not have units equivalent to "
  178. "the required unit {1}".format(default, unit))
  179. unit = default.unit
  180. default = default.value
  181. self._default = default
  182. self._unit = unit
  183. # NOTE: These are *default* constraints--on model instances constraints
  184. # are taken from the model if set, otherwise the defaults set here are
  185. # used
  186. if bounds is not None:
  187. if min is not None or max is not None:
  188. raise ValueError(
  189. 'bounds may not be specified simultaneously with min or '
  190. 'or max when instantiating Parameter {0}'.format(name))
  191. else:
  192. bounds = (min, max)
  193. self._fixed = fixed
  194. self._tied = tied
  195. self._bounds = bounds
  196. self._posterior = posterior
  197. self._prior = prior
  198. self._order = None
  199. self._model = None
  200. # The getter/setter functions take one or two arguments: The first
  201. # argument is always the value itself (either the value returned or the
  202. # value being set). The second argument is optional, but if present
  203. # will contain a reference to the model object tied to a parameter (if
  204. # it exists)
  205. self._getter = self._create_value_wrapper(getter, None)
  206. self._setter = self._create_value_wrapper(setter, None)
  207. self._validator = None
  208. # Only Parameters declared as class-level descriptors require
  209. # and ordering ID
  210. if model is not None:
  211. self._bind(model)
  212. def __get__(self, obj, objtype):
  213. if obj is None:
  214. return self
  215. # All of the Parameter.__init__ work should already have been done for
  216. # the class-level descriptor; we can skip that stuff and just copy the
  217. # existing __dict__ and then bind to the model instance
  218. parameter = self.__class__.__new__(self.__class__)
  219. parameter.__dict__.update(self.__dict__)
  220. parameter._bind(obj)
  221. return parameter
  222. def __set__(self, obj, value):
  223. value = _tofloat(value)
  224. # Check that units are compatible with default or units already set
  225. param_unit = obj._param_metrics[self.name]['orig_unit']
  226. if param_unit is None:
  227. if isinstance(value, Quantity):
  228. obj._param_metrics[self.name]['orig_unit'] = value.unit
  229. else:
  230. if not isinstance(value, Quantity):
  231. raise UnitsError("The '{0}' parameter should be given as a "
  232. "Quantity because it was originally initialized "
  233. "as a Quantity".format(self._name))
  234. else:
  235. # We need to make sure we update the unit because the units are
  236. # then dropped from the value below.
  237. obj._param_metrics[self.name]['orig_unit'] = value.unit
  238. # Call the validator before the setter
  239. if self._validator is not None:
  240. self._validator(obj, value)
  241. if self._setter is not None:
  242. setter = self._create_value_wrapper(self._setter, obj)
  243. if self.unit is not None:
  244. value = setter(value * self.unit).value
  245. else:
  246. value = setter(value)
  247. self._set_model_value(obj, value)
  248. def __len__(self):
  249. if self._model is None:
  250. raise TypeError('Parameter definitions do not have a length.')
  251. return len(self._model)
  252. def __getitem__(self, key):
  253. value = self.value
  254. if len(self._model) == 1:
  255. # Wrap the value in a list so that getitem can work for sensible
  256. # indices like [0] and [-1]
  257. value = [value]
  258. return value[key]
  259. def __setitem__(self, key, value):
  260. # Get the existing value and check whether it even makes sense to
  261. # apply this index
  262. oldvalue = self.value
  263. n_models = len(self._model)
  264. # if n_models == 1:
  265. # # Convert the single-dimension value to a list to allow some slices
  266. # # that would be compatible with a length-1 array like [:] and [0:]
  267. # oldvalue = [oldvalue]
  268. if isinstance(key, slice):
  269. if len(oldvalue[key]) == 0:
  270. raise InputParameterError(
  271. "Slice assignment outside the parameter dimensions for "
  272. "'{0}'".format(self.name))
  273. for idx, val in zip(range(*key.indices(len(self))), value):
  274. self.__setitem__(idx, val)
  275. else:
  276. try:
  277. oldvalue[key] = value
  278. except IndexError:
  279. raise InputParameterError(
  280. "Input dimension {0} invalid for {1!r} parameter with "
  281. "dimension {2}".format(key, self.name, n_models))
  282. def __repr__(self):
  283. args = "'{0}'".format(self._name)
  284. if self._model is None:
  285. if self._default is not None:
  286. args += ', default={0}'.format(self._default)
  287. else:
  288. args += ', value={0}'.format(self.value)
  289. if self.unit is not None:
  290. args += ', unit={0}'.format(self.unit)
  291. for cons in self.constraints:
  292. val = getattr(self, cons)
  293. if val not in (None, False, (None, None)):
  294. # Maybe non-obvious, but False is the default for the fixed and
  295. # tied constraints
  296. args += ', {0}={1}'.format(cons, val)
  297. return "{0}({1})".format(self.__class__.__name__, args)
  298. @property
  299. def name(self):
  300. """Parameter name"""
  301. return self._name
  302. @property
  303. def default(self):
  304. """Parameter default value"""
  305. if (self._model is None or self._default is None or
  306. len(self._model) == 1):
  307. return self._default
  308. # Otherwise the model we are providing for has more than one parameter
  309. # sets, so ensure that the default is repeated the correct number of
  310. # times along the model_set_axis if necessary
  311. n_models = len(self._model)
  312. model_set_axis = self._model._model_set_axis
  313. default = self._default
  314. new_shape = (np.shape(default) +
  315. (1,) * (model_set_axis + 1 - np.ndim(default)))
  316. default = np.reshape(default, new_shape)
  317. # Now roll the new axis into its correct position if necessary
  318. default = np.rollaxis(default, -1, model_set_axis)
  319. # Finally repeat the last newly-added axis to match n_models
  320. default = np.repeat(default, n_models, axis=-1)
  321. # NOTE: Regardless of what order the last two steps are performed in,
  322. # the resulting array will *look* the same, but only if the repeat is
  323. # performed last will it result in a *contiguous* array
  324. return default
  325. @property
  326. def value(self):
  327. """The unadorned value proxied by this parameter."""
  328. if self._model is None:
  329. raise AttributeError('Parameter definition does not have a value')
  330. value = self._get_model_value(self._model)
  331. if self._getter is None:
  332. return value
  333. else:
  334. raw_unit = self._model._param_metrics[self.name]['raw_unit']
  335. orig_unit = self._model._param_metrics[self.name]['orig_unit']
  336. if raw_unit is not None:
  337. return np.float64(self._getter(value, raw_unit, orig_unit).value)
  338. else:
  339. return self._getter(value)
  340. @value.setter
  341. def value(self, value):
  342. if self._model is None:
  343. raise AttributeError('Cannot set a value on a parameter '
  344. 'definition')
  345. if self._setter is not None:
  346. val = self._setter(value)
  347. if isinstance(value, Quantity):
  348. raise TypeError("The .value property on parameters should be set to "
  349. "unitless values, not Quantity objects. To set a "
  350. "parameter to a quantity simply set the parameter "
  351. "directly without using .value")
  352. self._set_model_value(self._model, value)
  353. @property
  354. def unit(self):
  355. """
  356. The unit attached to this parameter, if any.
  357. On unbound parameters (i.e. parameters accessed through the
  358. model class, rather than a model instance) this is the required/
  359. default unit for the parameter.
  360. """
  361. if self._model is None:
  362. return self._unit
  363. else:
  364. # orig_unit may be undefined early on in model instantiation
  365. return self._model._param_metrics[self.name].get('orig_unit',
  366. self._unit)
  367. @unit.setter
  368. def unit(self, unit):
  369. self._set_unit(unit)
  370. def _set_unit(self, unit, force=False):
  371. if self._model is None:
  372. raise AttributeError('Cannot set unit on a parameter definition')
  373. orig_unit = self._model._param_metrics[self.name]['orig_unit']
  374. if force:
  375. self._model._param_metrics[self.name]['orig_unit'] = unit
  376. else:
  377. if orig_unit is None:
  378. raise ValueError('Cannot attach units to parameters that were '
  379. 'not initially specified with units')
  380. else:
  381. raise ValueError('Cannot change the unit attribute directly, '
  382. 'instead change the parameter to a new quantity')
  383. @property
  384. def quantity(self):
  385. """
  386. This parameter, as a :class:`~astropy.units.Quantity` instance.
  387. """
  388. if self.unit is not None:
  389. return self.value * self.unit
  390. else:
  391. return None
  392. @quantity.setter
  393. def quantity(self, quantity):
  394. if not isinstance(quantity, Quantity):
  395. raise TypeError("The .quantity attribute should be set to a Quantity object")
  396. self.value = quantity.value
  397. self._set_unit(quantity.unit, force=True)
  398. @property
  399. def shape(self):
  400. """The shape of this parameter's value array."""
  401. if self._model is None:
  402. raise AttributeError('Parameter definition does not have a '
  403. 'shape.')
  404. shape = self._model._param_metrics[self._name]['shape']
  405. if len(self._model) > 1:
  406. # If we are dealing with a model *set* the shape is the shape of
  407. # the parameter within a single model in the set
  408. model_axis = self._model._model_set_axis
  409. if model_axis < 0:
  410. model_axis = len(shape) + model_axis
  411. shape = shape[:model_axis] + shape[model_axis + 1:]
  412. else:
  413. # When a model set is initialized, the dimension of the parameters
  414. # is increased by model_set_axis+1. To find the shape of a parameter
  415. # within a single model the extra dimensions need to be removed first.
  416. # The following dimension shows the number of models.
  417. # The rest of the shape tuple represents the shape of the parameter
  418. # in a single model.
  419. shape = shape[model_axis + 1:]
  420. return shape
  421. @property
  422. def size(self):
  423. """The size of this parameter's value array."""
  424. # TODO: Rather than using self.value this could be determined from the
  425. # size of the parameter in _param_metrics
  426. return np.size(self.value)
  427. @property
  428. def prior(self):
  429. if self._model is not None:
  430. prior = self._model._constraints['prior']
  431. return prior.get(self._name, self._prior)
  432. else:
  433. return self._prior
  434. @prior.setter
  435. def prior(self, val):
  436. if self._model is not None:
  437. self._model._constraints['prior'][self._name] = val
  438. else:
  439. raise AttributeError("can't set attribute 'prior' on Parameter "
  440. "definition")
  441. @property
  442. def posterior(self):
  443. if self._model is not None:
  444. posterior = self._model._constraints['posterior']
  445. return posterior.get(self._name, self._posterior)
  446. else:
  447. return self._posterior
  448. @posterior.setter
  449. def posterior(self, val):
  450. if self._model is not None:
  451. self._model._constraints['posterior'][self._name] = val
  452. else:
  453. raise AttributeError("can't set attribute 'posterior' on Parameter "
  454. "definition")
  455. @property
  456. def fixed(self):
  457. """
  458. Boolean indicating if the parameter is kept fixed during fitting.
  459. """
  460. if self._model is not None:
  461. fixed = self._model._constraints['fixed']
  462. return fixed.get(self._name, self._fixed)
  463. else:
  464. return self._fixed
  465. @fixed.setter
  466. def fixed(self, value):
  467. """Fix a parameter"""
  468. if self._model is not None:
  469. if not isinstance(value, bool):
  470. raise TypeError("Fixed can be True or False")
  471. self._model._constraints['fixed'][self._name] = value
  472. else:
  473. raise AttributeError("can't set attribute 'fixed' on Parameter "
  474. "definition")
  475. @property
  476. def tied(self):
  477. """
  478. Indicates that this parameter is linked to another one.
  479. A callable which provides the relationship of the two parameters.
  480. """
  481. if self._model is not None:
  482. tied = self._model._constraints['tied']
  483. return tied.get(self._name, self._tied)
  484. else:
  485. return self._tied
  486. @tied.setter
  487. def tied(self, value):
  488. """Tie a parameter"""
  489. if self._model is not None:
  490. if not callable(value) and value not in (False, None):
  491. raise TypeError("Tied must be a callable")
  492. self._model._constraints['tied'][self._name] = value
  493. else:
  494. raise AttributeError("can't set attribute 'tied' on Parameter "
  495. "definition")
  496. @property
  497. def bounds(self):
  498. """The minimum and maximum values of a parameter as a tuple"""
  499. if self._model is not None:
  500. bounds = self._model._constraints['bounds']
  501. return bounds.get(self._name, self._bounds)
  502. else:
  503. return self._bounds
  504. @bounds.setter
  505. def bounds(self, value):
  506. """Set the minimum and maximum values of a parameter from a tuple"""
  507. if self._model is not None:
  508. _min, _max = value
  509. if _min is not None:
  510. if not isinstance(_min, numbers.Number):
  511. raise TypeError("Min value must be a number")
  512. _min = float(_min)
  513. if _max is not None:
  514. if not isinstance(_max, numbers.Number):
  515. raise TypeError("Max value must be a number")
  516. _max = float(_max)
  517. bounds = self._model._constraints.setdefault('bounds', {})
  518. self._model._constraints['bounds'][self._name] = (_min, _max)
  519. else:
  520. raise AttributeError("can't set attribute 'bounds' on Parameter "
  521. "definition")
  522. @property
  523. def min(self):
  524. """A value used as a lower bound when fitting a parameter"""
  525. return self.bounds[0]
  526. @min.setter
  527. def min(self, value):
  528. """Set a minimum value of a parameter"""
  529. if self._model is not None:
  530. self.bounds = (value, self.max)
  531. else:
  532. raise AttributeError("can't set attribute 'min' on Parameter "
  533. "definition")
  534. @property
  535. def max(self):
  536. """A value used as an upper bound when fitting a parameter"""
  537. return self.bounds[1]
  538. @max.setter
  539. def max(self, value):
  540. """Set a maximum value of a parameter."""
  541. if self._model is not None:
  542. self.bounds = (self.min, value)
  543. else:
  544. raise AttributeError("can't set attribute 'max' on Parameter "
  545. "definition")
  546. @property
  547. def validator(self):
  548. """
  549. Used as a decorator to set the validator method for a `Parameter`.
  550. The validator method validates any value set for that parameter.
  551. It takes two arguments--``self``, which refers to the `Model`
  552. instance (remember, this is a method defined on a `Model`), and
  553. the value being set for this parameter. The validator method's
  554. return value is ignored, but it may raise an exception if the value
  555. set on the parameter is invalid (typically an `InputParameterError`
  556. should be raised, though this is not currently a requirement).
  557. The decorator *returns* the `Parameter` instance that the validator
  558. is set on, so the underlying validator method should have the same
  559. name as the `Parameter` itself (think of this as analogous to
  560. ``property.setter``). For example::
  561. >>> from astropy.modeling import Fittable1DModel
  562. >>> class TestModel(Fittable1DModel):
  563. ... a = Parameter()
  564. ... b = Parameter()
  565. ...
  566. ... @a.validator
  567. ... def a(self, value):
  568. ... # Remember, the value can be an array
  569. ... if np.any(value < self.b):
  570. ... raise InputParameterError(
  571. ... "parameter 'a' must be greater than or equal "
  572. ... "to parameter 'b'")
  573. ...
  574. ... @staticmethod
  575. ... def evaluate(x, a, b):
  576. ... return a * x + b
  577. ...
  578. >>> m = TestModel(a=1, b=2) # doctest: +IGNORE_EXCEPTION_DETAIL
  579. Traceback (most recent call last):
  580. ...
  581. InputParameterError: parameter 'a' must be greater than or equal
  582. to parameter 'b'
  583. >>> m = TestModel(a=2, b=2)
  584. >>> m.a = 0 # doctest: +IGNORE_EXCEPTION_DETAIL
  585. Traceback (most recent call last):
  586. ...
  587. InputParameterError: parameter 'a' must be greater than or equal
  588. to parameter 'b'
  589. On bound parameters this property returns the validator method itself,
  590. as a bound method on the `Parameter`. This is not often as useful, but
  591. it allows validating a parameter value without setting that parameter::
  592. >>> m.a.validator(42) # Passes
  593. >>> m.a.validator(-42) # doctest: +IGNORE_EXCEPTION_DETAIL
  594. Traceback (most recent call last):
  595. ...
  596. InputParameterError: parameter 'a' must be greater than or equal
  597. to parameter 'b'
  598. """
  599. if self._model is None:
  600. # For unbound parameters return the validator setter
  601. def validator(func, self=self):
  602. self._validator = func
  603. return self
  604. return validator
  605. else:
  606. # Return the validator method, bound to the Parameter instance with
  607. # the name "validator"
  608. def validator(self, value):
  609. if self._validator is not None:
  610. return self._validator(self._model, value)
  611. return types.MethodType(validator, self)
  612. def copy(self, name=None, description=None, default=None, unit=None,
  613. getter=None, setter=None, fixed=False, tied=False, min=None,
  614. max=None, bounds=None, prior=None, posterior=None):
  615. """
  616. Make a copy of this `Parameter`, overriding any of its core attributes
  617. in the process (or an exact copy).
  618. The arguments to this method are the same as those for the `Parameter`
  619. initializer. This simply returns a new `Parameter` instance with any
  620. or all of the attributes overridden, and so returns the equivalent of:
  621. .. code:: python
  622. Parameter(self.name, self.description, ...)
  623. """
  624. kwargs = locals().copy()
  625. del kwargs['self']
  626. for key, value in kwargs.items():
  627. if value is None:
  628. # Annoying special cases for min/max where are just aliases for
  629. # the components of bounds
  630. if key in ('min', 'max'):
  631. continue
  632. else:
  633. if hasattr(self, key):
  634. value = getattr(self, key)
  635. elif hasattr(self, '_' + key):
  636. value = getattr(self, '_' + key)
  637. kwargs[key] = value
  638. return self.__class__(**kwargs)
  639. @property
  640. def _raw_value(self):
  641. """
  642. Currently for internal use only.
  643. Like Parameter.value but does not pass the result through
  644. Parameter.getter. By design this should only be used from bound
  645. parameters.
  646. This will probably be removed are retweaked at some point in the
  647. process of rethinking how parameter values are stored/updated.
  648. """
  649. return self._get_model_value(self._model)
  650. def _bind(self, model):
  651. """
  652. Bind the `Parameter` to a specific `Model` instance; don't use this
  653. directly on *unbound* parameters, i.e. `Parameter` descriptors that
  654. are defined in class bodies.
  655. """
  656. self._model = model
  657. self._getter = self._create_value_wrapper(self._getter, model)
  658. self._setter = self._create_value_wrapper(self._setter, model)
  659. # TODO: These methods should probably be moved to the Model class, since it
  660. # has entirely to do with details of how the model stores parameters.
  661. # Parameter should just act as a user front-end to this.
  662. def _get_model_value(self, model):
  663. """
  664. This method implements how to retrieve the value of this parameter from
  665. the model instance. See also `Parameter._set_model_value`.
  666. These methods take an explicit model argument rather than using
  667. self._model so that they can be used from unbound `Parameter`
  668. instances.
  669. """
  670. if not hasattr(model, '_parameters'):
  671. # The _parameters array hasn't been initialized yet; just translate
  672. # this to an AttributeError
  673. raise AttributeError(self._name)
  674. # Use the _param_metrics to extract the parameter value from the
  675. # _parameters array
  676. param_metrics = model._param_metrics[self._name]
  677. param_slice = param_metrics['slice']
  678. param_shape = param_metrics['shape']
  679. value = model._parameters[param_slice]
  680. if param_shape:
  681. value = value.reshape(param_shape)
  682. else:
  683. value = value[0]
  684. return value
  685. def _set_model_value(self, model, value):
  686. """
  687. This method implements how to store the value of a parameter on the
  688. model instance.
  689. Currently there is only one storage mechanism (via the ._parameters
  690. array) but other mechanisms may be desireable, in which case really the
  691. model class itself should dictate this and *not* `Parameter` itself.
  692. """
  693. def _update_parameter_value(model, name, value):
  694. # TODO: Maybe handle exception on invalid input shape
  695. param_metrics = model._param_metrics[name]
  696. param_slice = param_metrics['slice']
  697. param_shape = param_metrics['shape']
  698. param_size = np.prod(param_shape)
  699. if np.size(value) != param_size:
  700. raise InputParameterError(
  701. "Input value for parameter {0!r} does not have {1} elements "
  702. "as the current value does".format(name, param_size))
  703. model._parameters[param_slice] = np.array(value).ravel()
  704. _update_parameter_value(model, self._name, value)
  705. if hasattr(model, "_param_map"):
  706. submodel_ind, param_name = model._param_map[self._name]
  707. if hasattr(model._submodels[submodel_ind], "_param_metrics"):
  708. _update_parameter_value(model._submodels[submodel_ind], param_name, value)
  709. @staticmethod
  710. def _create_value_wrapper(wrapper, model):
  711. """Wraps a getter/setter function to support optionally passing in
  712. a reference to the model object as the second argument.
  713. If a model is tied to this parameter and its getter/setter supports
  714. a second argument then this creates a partial function using the model
  715. instance as the second argument.
  716. """
  717. if isinstance(wrapper, np.ufunc):
  718. if wrapper.nin != 1:
  719. raise TypeError("A numpy.ufunc used for Parameter "
  720. "getter/setter may only take one input "
  721. "argument")
  722. elif wrapper is None:
  723. # Just allow non-wrappers to fall through silently, for convenience
  724. return None
  725. else:
  726. inputs, params = get_inputs_and_params(wrapper)
  727. nargs = len(inputs)
  728. if nargs == 1:
  729. pass
  730. elif nargs == 2:
  731. if model is not None:
  732. # Don't make a partial function unless we're tied to a
  733. # specific model instance
  734. model_arg = inputs[1].name
  735. wrapper = functools.partial(wrapper, **{model_arg: model})
  736. else:
  737. raise TypeError("Parameter getter/setter must be a function "
  738. "of either one or two arguments")
  739. return wrapper
  740. def __array__(self, dtype=None):
  741. # Make np.asarray(self) work a little more straightforwardly
  742. arr = np.asarray(self.value, dtype=dtype)
  743. if self.unit is not None:
  744. arr = Quantity(arr, self.unit, copy=False)
  745. return arr
  746. def __bool__(self):
  747. if self._model is None:
  748. return True
  749. else:
  750. return bool(self.value)
  751. __add__ = _binary_arithmetic_operation(operator.add)
  752. __radd__ = _binary_arithmetic_operation(operator.add, reflected=True)
  753. __sub__ = _binary_arithmetic_operation(operator.sub)
  754. __rsub__ = _binary_arithmetic_operation(operator.sub, reflected=True)
  755. __mul__ = _binary_arithmetic_operation(operator.mul)
  756. __rmul__ = _binary_arithmetic_operation(operator.mul, reflected=True)
  757. __pow__ = _binary_arithmetic_operation(operator.pow)
  758. __rpow__ = _binary_arithmetic_operation(operator.pow, reflected=True)
  759. __div__ = _binary_arithmetic_operation(operator.truediv)
  760. __rdiv__ = _binary_arithmetic_operation(operator.truediv, reflected=True)
  761. __truediv__ = _binary_arithmetic_operation(operator.truediv)
  762. __rtruediv__ = _binary_arithmetic_operation(operator.truediv, reflected=True)
  763. __eq__ = _binary_comparison_operation(operator.eq)
  764. __ne__ = _binary_comparison_operation(operator.ne)
  765. __lt__ = _binary_comparison_operation(operator.lt)
  766. __gt__ = _binary_comparison_operation(operator.gt)
  767. __le__ = _binary_comparison_operation(operator.le)
  768. __ge__ = _binary_comparison_operation(operator.ge)
  769. __neg__ = _unary_arithmetic_operation(operator.neg)
  770. __abs__ = _unary_arithmetic_operation(operator.abs)
  771. def param_repr_oneline(param):
  772. """
  773. Like array_repr_oneline but works on `Parameter` objects and supports
  774. rendering parameters with units like quantities.
  775. """
  776. out = array_repr_oneline(param.value)
  777. if param.unit is not None:
  778. out = '{0} {1!s}'.format(out, param.unit)
  779. return out