B
    q\                 @   s   d Z ddlZddlZddlZddlZddlZddlmZ	 ddl
mZmZ ddlmZmZ ddlmZ ddlmZ d	d
dgZG dd deZG dd
 d
eeZG dd deZdd ZdddZdd Zdd ZG dd	 d	eZdd ZdS )z
This module defines two classes that deal with parameters.

It is unlikely users will need to work with these classes directly, unless they
define their own models.
    N)units)Quantity
UnitsError)
isiterableOrderedDescriptor   )array_repr_oneline)get_inputs_and_params	ParameterInputParameterErrorParameterErrorc               @   s   e Zd ZdZdS )r   zDGeneric exception class for all exceptions pertaining to Parameters.N)__name__
__module____qualname____doc__ r   r   :lib/python3.7/site-packages/astropy/modeling/parameters.pyr      s   c               @   s   e Zd ZdZdS )r   z:Used for incorrect input parameter values and definitions.N)r   r   r   r   r   r   r   r   r       s   c               @   s   e Zd ZdZdS )ParameterDefinitionErrorz3Exception in declaration of class-level Parameters.N)r   r   r   r   r   r   r   r   r   $   s   r   c          	   C   s   t | rHytj| td} W q ttfk
rD   tdt| Y qX nht	| t
rTn\t	| tjrnt|  } nBt	| tjtjfrt| } n&t	| trtdntdt| | S )z+Convert a parameter to float or float array)dtypez0Parameter of {0} could not be converted to floatz7Expected parameter to be of numerical type, not booleanz3Don't know how to convert parameter of {0} to float)r   npZ
asanyarrayfloat	TypeError
ValueErrorr   formattype
isinstancer   ZndarrayitemnumbersNumberZnumberbool)valuer   r   r   _tofloat(   s(    


r!   Fc                s   t   fdd}|S )Nc                sJ   | j d krtS | jd k	r(t| j| j}n| j}r< ||S  ||S d S )N)_modelNotImplementedunitr   r    )selfval
self_value)op	reflectedr   r   wrapperI   s    


z-_binary_arithmetic_operation.<locals>.wrapper)	functoolswraps)r(   r)   r*   r   )r(   r)   r   _binary_arithmetic_operationH   s    r-   c                s   t   fdd}|S )Nc                sT   | j d kr* tjkr&t| j| |S tS | jd k	rDt| j	| j}n| j	} ||S )N)
r"   operatorltsuper	__class____lt__r#   r$   r   r    )r%   r&   r'   )r(   r   r   r*   ]   s    


z-_binary_comparison_operation.<locals>.wrapper)r+   r,   )r(   r*   r   )r(   r   _binary_comparison_operation\   s    r3   c                s   t   fdd}|S )Nc                s6   | j d krtS | jd k	r(t| j| j}n| j} |S )N)r"   r#   r$   r   r    )r%   r'   )r(   r   r   r*   t   s    

z,_unary_arithmetic_operation.<locals>.wrapper)r+   r,   )r(   r*   r   )r(   r   _unary_arithmetic_operations   s    r4   c                   s  e Zd ZdZdZdZdZdR fdd		Zd
d Zdd Z	dd Z
dd Zdd Zdd Zedd Zedd Zedd Zejdd Zedd Zejdd ZdSd d!Zed"d# Zejd$d# Zed%d& Zed'd( Zed)d* Zejd+d* Zed,d- Zejd.d- Zed/d0 Zejd1d0 Zed2d3 Zejd4d3 Zed5d6 Zejd7d6 Zed8d9 Zejd:d9 Zed;d< Zejd=d< Zed>d? ZdTd@dAZ edBdC Z!dDdE Z"dFdG Z#dHdI Z$e%dJdK Z&dUdLdMZ'dNdO Z(e)e*j+Z,e)e*j+dPdQZ-e)e*j.Z/e)e*j.dPdQZ0e)e*j1Z2e)e*j1dPdQZ3e)e*j4Z5e)e*j4dPdQZ6e)e*j7Z8e)e*j7dPdQZ9e)e*j7Z:e)e*j7dPdQZ;e<e*j=Z>e<e*j?Z@e<e*jAZBe<e*jCZDe<e*jEZFe<e*jGZHeIe*jJZKeIe*jLZM  ZNS )Vr
   a  
    Wraps individual parameters.

    This class represents a model's parameter (in a somewhat broad sense).  It
    acts as both a descriptor that can be assigned to a class attribute to
    describe the parameters accepted by an individual model (this is called an
    "unbound parameter"), or it can act as a proxy for the parameter values on
    an individual model instance (called a "bound parameter").

    Parameter instances never store the actual value of the parameter directly.
    Rather, each instance of a model stores its own parameters parameter values
    in an array.  A *bound* Parameter simply wraps the value in a Parameter
    proxy which provides some additional information about the parameter such
    as its constraints.  In other words, this is a high-level interface to a
    model's adjustable parameter values.

    *Unbound* Parameters are not associated with any specific model instance,
    and are merely used by model classes to determine the names of their
    parameters and other information about each parameter such as their default
    values and default constraints.

    See :ref:`modeling-parameters` for more details.

    Parameters
    ----------
    name : str
        parameter name

        .. warning::

            The fact that `Parameter` accepts ``name`` as an argument is an
            implementation detail, and should not be used directly.  When
            defining a new `Model` class, parameter names are always
            automatically defined by the class attribute they're assigned to.
    description : str
        parameter description
    default : float or array
        default value to use for this parameter
    unit : `~astropy.units.Unit`
        if specified, the parameter will be in these units, and when the
        parameter is updated in future, it should be set to a
        :class:`~astropy.units.Quantity` that has equivalent units.
    getter : callable
        a function that wraps the raw (internal) value of the parameter
        when returning the value through the parameter proxy (eg. a
        parameter may be stored internally as radians but returned to the
        user as degrees)
    setter : callable
        a function that wraps any values assigned to this parameter; should
        be the inverse of getter
    fixed : bool
        if True the parameter is not varied during fitting
    tied : callable or False
        if callable is supplied it provides a way to link the value of this
        parameter to another parameter (or some other arbitrary function)
    min : float
        the lower bound of a parameter
    max : float
        the upper bound of a parameter
    bounds : tuple
        specify min and max as a single tuple--bounds may not be specified
        simultaneously with min or max
    model : `Model` instance
        binds the the `Parameter` instance to a specific model upon
        instantiation; this should only be used internally for creating bound
        Parameters, and should not be used for `Parameter` descriptors defined
        as class attributes
    )fixedtiedboundsprior	posteriorZ_parameters__name NFc                s   t    || _|  | _| _|d krbt|trb|d k	rV||j	sVt
d|||j	}|j}|| _|| _|d k	r|	d k	s|
d k	rtd|n|	|
f}|| _|| _|| _|| _|| _d | _d | _| |d | _| |d | _d | _|d k	r| | d S )NzMparameter default {0} does not have units equivalent to the required unit {1}z^bounds may not be specified simultaneously with min or or max when instantiating Parameter {0})r0   __init__r:   stripr   Z_descriptionr   r   Zis_equivalentr$   r   r   r    _default_unitr   _fixed_tied_bounds
_posterior_prior_orderr"   _create_value_wrapper_getter_setter
_validator_bind)r%   namedescriptiondefaultr$   gettersetterr5   r6   minmaxr7   r8   r9   model)r1   r   r   r<      s<    


zParameter.__init__c             C   s6   |d kr| S | j | j }|j| j || |S )N)r1   __new____dict__updaterJ   )r%   objZobjtypeZ	parameterr   r   r   __get__  s    
zParameter.__get__c             C   s   t |}|j| j d }|d kr>t|trl|j|j| j d< n.t|tsZtd| jn|j|j| j d< | j	d k	r| 	|| | j
d k	r| | j
|}| jd k	r||| j j}n||}| || d S )N	orig_unitzeThe '{0}' parameter should be given as a Quantity because it was originally initialized as a Quantity)r!   _param_metricsrK   r   r   r$   r   r   r:   rI   rH   rF   r    _set_model_value)r%   rV   r    Z
param_unitrO   r   r   r   __set__  s"    




zParameter.__set__c             C   s   | j d krtdt| j S )Nz+Parameter definitions do not have a length.)r"   r   len)r%   r   r   r   __len__8  s    
zParameter.__len__c             C   s"   | j }t| jdkr|g}|| S )Nr   )r    r\   r"   )r%   keyr    r   r   r   __getitem__=  s    zParameter.__getitem__c          	   C   s   | j }t| j}t|trnt|| dkr:td| jxhtt	|
t|  |D ]\}}| || qTW n6y|||< W n( tk
r   td|| j|Y nX d S )Nr   z;Slice assignment outside the parameter dimensions for '{0}'zBInput dimension {0} invalid for {1!r} parameter with dimension {2})r    r\   r"   r   slicer   r   rK   ziprangeindices__setitem__
IndexError)r%   r^   r    Zoldvaluen_modelsidxr&   r   r   r   rd   E  s    


"zParameter.__setitem__c             C   s   d | j}| jd kr2| jd k	rB|d | j7 }n|d | j7 }| jd k	r\|d | j7 }x0| jD ]&}t| |}|dkrd|d ||7 }qdW d | jj	|S )Nz'{0}'z, default={0}z, value={0}z
, unit={0})NF)NNz	, {0}={1}z{0}({1}))
r   r:   r"   r>   r    r$   constraintsgetattrr1   r   )r%   argsZconsr&   r   r   r   __repr___  s    



zParameter.__repr__c             C   s   | j S )zParameter name)r:   )r%   r   r   r   rK   s  s    zParameter.namec             C   s   | j dks"| jdks"t| j dkr(| jS t| j }| j j}| j}t|d|d t|   }t||}t|d|}tj	||dd}|S )zParameter default valueNr   )r   )Zaxis)
r"   r>   r\   _model_set_axisr   shapendimreshapeZrollaxisrepeat)r%   rf   Zmodel_set_axisrM   Z	new_shaper   r   r   rM   y  s    
zParameter.defaultc             C   s|   | j dkrtd| | j }| jdkr,|S | j j| j d }| j j| j d }|dk	rnt| |||jS | |S dS )z.The unadorned value proxied by this parameter.Nz*Parameter definition does not have a valueraw_unitrX   )	r"   AttributeError_get_model_valuerG   rY   rK   r   Zfloat64r    )r%   r    rr   rX   r   r   r   r      s    

zParameter.valuec             C   sJ   | j d krtd| jd k	r&| |}t|tr8td| | j | d S )Nz,Cannot set a value on a parameter definitionzThe .value property on parameters should be set to unitless values, not Quantity objects. To set a parameter to a quantity simply set the parameter directly without using .value)r"   rs   rH   r   r   r   rZ   )r%   r    r&   r   r   r   r      s    



c             C   s,   | j dkr| jS | j j| j d| jS dS )z
        The unit attached to this parameter, if any.

        On unbound parameters (i.e. parameters accessed through the
        model class, rather than a model instance) this is the required/
        default unit for the parameter.
        NrX   )r"   r?   rY   rK   get)r%   r   r   r   r$     s    

zParameter.unitc             C   s   |  | d S )N)	_set_unit)r%   r$   r   r   r   r$     s    c             C   sZ   | j d krtd| j j| j d }|r<|| j j| j d< n|d krNtdntdd S )Nz)Cannot set unit on a parameter definitionrX   zNCannot attach units to parameters that were not initially specified with unitszYCannot change the unit attribute directly, instead change the parameter to a new quantity)r"   rs   rY   rK   r   )r%   r$   forcerX   r   r   r   rv     s    

zParameter._set_unitc             C   s   | j dk	r| j| j  S dS dS )zQ
        This parameter, as a :class:`~astropy.units.Quantity` instance.
        N)r$   r    )r%   r   r   r   quantity  s    
zParameter.quantityc             C   s.   t |tstd|j| _| j|jdd d S )Nz:The .quantity attribute should be set to a Quantity objectT)rw   )r   r   r   r    rv   r$   )r%   rx   r   r   r   rx     s    
c             C   s   | j dkrtd| j j| j d }t| j dkr|| j j}|dk rlt|| }|d| ||d d  }n||d d }|S )z*The shape of this parameter's value array.Nz+Parameter definition does not have a shape.rn   r   r   )r"   rs   rY   r:   r\   rm   )r%   rn   Z
model_axisr   r   r   rn     s    
	zParameter.shapec             C   s   t | jS )z)The size of this parameter's value array.)r   sizer    )r%   r   r   r   ry     s    zParameter.sizec             C   s0   | j d k	r&| j jd }|| j| jS | jS d S )Nr8   )r"   _constraintsru   r:   rD   )r%   r8   r   r   r   r8     s    
zParameter.priorc             C   s*   | j d k	r|| j jd | j< ntdd S )Nr8   z3can't set attribute 'prior' on Parameter definition)r"   rz   r:   rs   )r%   r&   r   r   r   r8     s    
c             C   s0   | j d k	r&| j jd }|| j| jS | jS d S )Nr9   )r"   rz   ru   r:   rC   )r%   r9   r   r   r   r9   %  s    
zParameter.posteriorc             C   s*   | j d k	r|| j jd | j< ntdd S )Nr9   z7can't set attribute 'posterior' on Parameter definition)r"   rz   r:   rs   )r%   r&   r   r   r   r9   -  s    
c             C   s0   | j dk	r&| j jd }|| j| jS | jS dS )zS
        Boolean indicating if the parameter is kept fixed during fitting.
        Nr5   )r"   rz   ru   r:   r@   )r%   r5   r   r   r   r5   5  s    
zParameter.fixedc             C   s<   | j dk	r0t|tstd|| j jd | j< ntddS )zFix a parameterNzFixed can be True or Falser5   z3can't set attribute 'fixed' on Parameter definition)r"   r   r   r   rz   r:   rs   )r%   r    r   r   r   r5   A  s
    

c             C   s0   | j dk	r&| j jd }|| j| jS | jS dS )z
        Indicates that this parameter is linked to another one.

        A callable which provides the relationship of the two parameters.
        Nr6   )r"   rz   ru   r:   rA   )r%   r6   r   r   r   r6   L  s    
zParameter.tiedc             C   sB   | j dk	r6t|s"|dkr"td|| j jd | j< ntddS )zTie a parameterN)FNzTied must be a callabler6   z2can't set attribute 'tied' on Parameter definition)r"   callabler   rz   r:   rs   )r%   r    r   r   r   r6   Z  s
    
c             C   s0   | j dk	r&| j jd }|| j| jS | jS dS )z8The minimum and maximum values of a parameter as a tupleNr7   )r"   rz   ru   r:   rB   )r%   r7   r   r   r   r7   f  s    
zParameter.boundsc             C   s   | j dk	r|\}}|dk	r6t|tjs.tdt|}|dk	rZt|tjsRtdt|}| j jdi }||f| j jd | j< nt	ddS )z>Set the minimum and maximum values of a parameter from a tupleNzMin value must be a numberzMax value must be a numberr7   z4can't set attribute 'bounds' on Parameter definition)
r"   r   r   r   r   r   rz   
setdefaultr:   rs   )r%   r    Z_minZ_maxr7   r   r   r   r7   p  s    
c             C   s
   | j d S )z6A value used as a lower bound when fitting a parameterr   )r7   )r%   r   r   r   rP     s    zParameter.minc             C   s$   | j dk	r|| jf| _ntddS )z"Set a minimum value of a parameterNz1can't set attribute 'min' on Parameter definition)r"   rQ   r7   rs   )r%   r    r   r   r   rP     s    
c             C   s
   | j d S )z7A value used as an upper bound when fitting a parameterr   )r7   )r%   r   r   r   rQ     s    zParameter.maxc             C   s$   | j dk	r| j|f| _ntddS )z#Set a maximum value of a parameter.Nz1can't set attribute 'max' on Parameter definition)r"   rP   r7   rs   )r%   r    r   r   r   rQ     s    
c             C   s2   | j dkr| fdd}|S dd }t|| S dS )aA
  
        Used as a decorator to set the validator method for a `Parameter`.
        The validator method validates any value set for that parameter.
        It takes two arguments--``self``, which refers to the `Model`
        instance (remember, this is a method defined on a `Model`), and
        the value being set for this parameter.  The validator method's
        return value is ignored, but it may raise an exception if the value
        set on the parameter is invalid (typically an `InputParameterError`
        should be raised, though this is not currently a requirement).

        The decorator *returns* the `Parameter` instance that the validator
        is set on, so the underlying validator method should have the same
        name as the `Parameter` itself (think of this as analogous to
        ``property.setter``).  For example::

            >>> from astropy.modeling import Fittable1DModel
            >>> class TestModel(Fittable1DModel):
            ...     a = Parameter()
            ...     b = Parameter()
            ...
            ...     @a.validator
            ...     def a(self, value):
            ...         # Remember, the value can be an array
            ...         if np.any(value < self.b):
            ...             raise InputParameterError(
            ...                 "parameter 'a' must be greater than or equal "
            ...                 "to parameter 'b'")
            ...
            ...     @staticmethod
            ...     def evaluate(x, a, b):
            ...         return a * x + b
            ...
            >>> m = TestModel(a=1, b=2)  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            ...
            InputParameterError: parameter 'a' must be greater than or equal
            to parameter 'b'
            >>> m = TestModel(a=2, b=2)
            >>> m.a = 0  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            ...
            InputParameterError: parameter 'a' must be greater than or equal
            to parameter 'b'

        On bound parameters this property returns the validator method itself,
        as a bound method on the `Parameter`.  This is not often as useful, but
        it allows validating a parameter value without setting that parameter::

            >>> m.a.validator(42)  # Passes
            >>> m.a.validator(-42)  # doctest: +IGNORE_EXCEPTION_DETAIL
            Traceback (most recent call last):
            ...
            InputParameterError: parameter 'a' must be greater than or equal
            to parameter 'b'
        Nc             S   s
   | |_ |S )N)rI   )funcr%   r   r   r   	validator  s    z&Parameter.validator.<locals>.validatorc             S   s   | j d k	r|  | j|S d S )N)rI   r"   )r%   r    r   r   r   r~     s    
)r"   types
MethodType)r%   r~   r   r   r   r~     s
    :
zParameter.validatorc             C   s   t   }|d= xb| D ]V\}}|dkr|dkr6qn2t| |rLt| |}nt| d| rht| d| }|||< qW | jf |S )a  
        Make a copy of this `Parameter`, overriding any of its core attributes
        in the process (or an exact copy).

        The arguments to this method are the same as those for the `Parameter`
        initializer.  This simply returns a new `Parameter` instance with any
        or all of the attributes overridden, and so returns the equivalent of:

        .. code:: python

            Parameter(self.name, self.description, ...)

        r%   N)rP   rQ   _)localscopyitemshasattrri   r1   )r%   rK   rL   rM   r$   rN   rO   r5   r6   rP   rQ   r7   r8   r9   kwargsr^   r    r   r   r   r     s    

zParameter.copyc             C   s   |  | jS )ac  
        Currently for internal use only.

        Like Parameter.value but does not pass the result through
        Parameter.getter.  By design this should only be used from bound
        parameters.

        This will probably be removed are retweaked at some point in the
        process of rethinking how parameter values are stored/updated.
        )rt   r"   )r%   r   r   r   
_raw_value  s    zParameter._raw_valuec             C   s*   || _ | | j|| _| | j|| _dS )z
        Bind the `Parameter` to a specific `Model` instance; don't use this
        directly on *unbound* parameters, i.e. `Parameter` descriptors that
        are defined in class bodies.
        N)r"   rF   rG   rH   )r%   rR   r   r   r   rJ   "  s    zParameter._bindc             C   sV   t |dst| j|j| j }|d }|d }|j| }|rJ||}n|d }|S )a?  
        This method implements how to retrieve the value of this parameter from
        the model instance.  See also `Parameter._set_model_value`.

        These methods take an explicit model argument rather than using
        self._model so that they can be used from unbound `Parameter`
        instances.
        _parametersr`   rn   r   )r   rs   r:   rY   r   rp   )r%   rR   param_metricsparam_sliceparam_shaper    r   r   r   rt   0  s    



zParameter._get_model_valuec             C   sV   dd }||| j | t|drR|j| j  \}}t|j| drR||j| || dS )aW  
        This method implements how to store the value of a parameter on the
        model instance.

        Currently there is only one storage mechanism (via the ._parameters
        array) but other mechanisms may be desireable, in which case really the
        model class itself should dictate this and *not* `Parameter` itself.
        c             S   sZ   | j | }|d }|d }t|}t||krBtd||t| | j|< d S )Nr`   rn   zTInput value for parameter {0!r} does not have {1} elements as the current value does)	rY   r   Zprodry   r   r   ZarrayZravelr   )rR   rK   r    r   r   r   Z
param_sizer   r   r   _update_parameter_valueU  s    


z;Parameter._set_model_value.<locals>._update_parameter_value
_param_maprY   N)r:   r   r   Z
_submodels)r%   rR   r    r   Zsubmodel_indZ
param_namer   r   r   rZ   L  s    	
zParameter._set_model_valuec             C   s   t | tjr | jdkrtdn`| dkr,dS t| \}}t|}|dkrJn6|dkrx|dk	r|d j}tj	| f||i} ntd| S )aM  Wraps a getter/setter function to support optionally passing in
        a reference to the model object as the second argument.

        If a model is tied to this parameter and its getter/setter supports
        a second argument then this creates a partial function using the model
        instance as the second argument.
        r   zOA numpy.ufunc used for Parameter getter/setter may only take one input argumentN   zIParameter getter/setter must be a function of either one or two arguments)
r   r   ZufuncZninr   r	   r\   rK   r+   partial)r*   rR   ZinputsZparamsnargsZ	model_argr   r   r   rF   h  s    



zParameter._create_value_wrapperc             C   s.   t j| j|d}| jd k	r*t|| jdd}|S )N)r   F)r   )r   Zasarrayr    r$   r   )r%   r   Zarrr   r   r   	__array__  s    
zParameter.__array__c             C   s   | j d krdS t| jS d S )NT)r"   r   r    )r%   r   r   r   __bool__  s    
zParameter.__bool__T)r)   )r;   r;   NNNNFFNNNNNN)F)NNNNNNFFNNNNN)N)Or   r   r   r   rh   Z_class_attribute_Z_name_attribute_r<   rW   r[   r]   r_   rd   rk   propertyrK   rM   r    rO   r$   rv   rx   rn   ry   r8   r9   r5   r6   r7   rP   rQ   r~   r   r   rJ   rt   rZ   staticmethodrF   r   r   r-   r.   add__add____radd__sub__sub____rsub__mul__mul____rmul__pow__pow____rpow__truedivZ__div__Z__rdiv____truediv____rtruediv__r3   eq__eq__ne__ne__r/   r2   gt__gt__le__le__ge__ge__r4   neg__neg__abs__abs____classcell__r   r   )r1   r   r
      s   D
  5

	


J  
!$
	












c             C   s&   t | j}| jdk	r"d|| j}|S )z
    Like array_repr_oneline but works on `Parameter` objects and supports
    rendering parameters with units like quantities.
    Nz	{0} {1!s})r   r    r$   r   )Zparamoutr   r   r   param_repr_oneline  s    

r   )F)r   r+   r   r   r.   Znumpyr   Zastropyr   uZastropy.unitsr   r   Zastropy.utilsr   r   Zutilsr   r	   __all__	Exceptionr   r   r   r   r!   r-   r3   r4   r
   r   r   r   r   r   <module>   s4   
 
      4