B
    do                 @   s:  d Z ddlmZmZ ddlmZ ddlm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 d	d
ddddgZedG dd	 d	ZG dd
 d
eZG dd deZdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Z d#d$ Z!d/d%d&Z"d'd( Z#d0d)d*Z$G d+d, d,eZ%G d-d. d.eZ&dS )1z@
This module provides utility functions for the models package.
    )dequeUserDict)MutableMapping)	signatureN)
deprecated)
isiterablecheck_broadcast)unitsExpressionTree	AliasDictr   poly_map_domaincombellipse_extentz4.0c               @   s   e Zd ZdddddgZd"ddZd	d
 Zdd Zedd Ze	dd Z
e	dd Ze	dd Zdd Zdd Zdd Zd#ddZdd Zd$d d!ZdS )%r
   leftrightvalueinputsoutputsNc             C   s:   || _ || _|| _|| _|d k	r0||kr0| }|| _d S )N)r   r   r   r   copyr   )selfr   r   r   r   r    r   c/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/astropy/modeling/utils.py__init__   s    zExpressionTree.__init__c                s   t  fdd jD S )Nc             3   s   | ]}|t  |fV  qd S )N)getattr).0slot)r   r   r   	<genexpr>*   s    z.ExpressionTree.__getstate__.<locals>.<genexpr>)dict	__slots__)r   r   )r   r   __getstate__'   s    zExpressionTree.__getstate__c             C   s&   x |  D ]\}}t| || q
W d S )N)itemssetattr)r   stater   r   r   r   r   __setstate__,   s    zExpressionTree.__setstate__c             C   s   t | tr|| S | |fS )N)
isinstancer
   )branchadictkeyr   r   r   _recursive_lookup0   s    
z ExpressionTree._recursive_lookupc          	      sL  i }t  jts$ fdd jD S  jdkrh jj}x. jD ]$}  j||\}}||f||< q>W n jdkr jj} jj}xt jD ]v\}}|t	 jjk r҈  j| jj| \}}||f||< q  j| jj|t	 jj  \}}||f||< qW n< jj}x2 jjD ]&}  j||\}}||f||< qW |S )zf
        Map the names of the inputs to this ExpressionTree to the inputs to the leaf models.
        c                s   i | ]} j |f|qS r   )r   )r   inp)r   r   r   
<dictcomp>=   s    z-ExpressionTree.inputs_map.<locals>.<dictcomp>|&)
r$   r   strr   r   
inputs_mapr(   r   	enumeratelen)r   r.   Zl_inputs_mapr)   mZinp2Zr_inputs_mapir   )r   r   r.   6   s4    
zExpressionTree.inputs_mapc          	      sL  i }t  jts$ fdd jD S  jdkrh jj}x. jD ]$}  j||\}}||f||< q>W n jdkr jj} jj}xt jD ]v\}}|t	 jjk r҈  j| jj| \}}||f||< q  j| jj|t	 jj  \}}||f||< qW n< jj}x2 jjD ]&}  j||\}}||f||< qW |S )zh
        Map the names of the outputs to this ExpressionTree to the outputs to the leaf models.
        c                s   i | ]} j |f|qS r   )r   )r   out)r   r   r   r*   c   s    z.ExpressionTree.outputs_map.<locals>.<dictcomp>r+   r,   )
r$   r   r-   r   r   outputs_mapr(   r   r/   r0   )r   r4   Zr_outputs_mapr3   r1   Zout2Zl_outputs_mapr2   r   )r   r   r4   \   s4    
zExpressionTree.outputs_mapc             C   s   | j d ko| jd kS )N)r   r   )r   r   r   r   isleaf   s    zExpressionTree.isleafc             c   sR   t | g}xB|rL| }|V  |jd k	r4||j |jd k	r||j qW d S )N)r   popr   appendr   )r   stacknoder   r   r   traverse_preorder   s    


z ExpressionTree.traverse_preorderc             c   sN   t  }| }x>|s|d k	rH|d k	r2|| |j}q| }|V  |j}qW d S )N)r   r7   r   r6   r   )r   r8   r9   r   r   r   traverse_inorder   s    
zExpressionTree.traverse_inorderc             c   s   t | g}d }x|r|d }|d ks8||jks8||jkrh|jd k	rP||j q|jd k	r||j n,|j|kr|jd k	r||j n
| V  |}qW d S )N)r   r   r   r7   r6   )r   r8   lastr9   r   r   r   traverse_postorder   s    



z!ExpressionTree.traverse_postorderr   c             C   sJ  t  }|dkrdd }|dkr"d}d}x|  D ]}|jr^||||j|f |d7 }q2||j }t|dk rvq2| }	| }
g }xV|
|	fD ]J}|d dkr|| q|\}}||kr|dks||k r|||f qW t|dkr|\}
}	|||
d |	d df q2t|dkr0||
 q2|| q2W | d S )a"  Evaluate the expression represented by this tree.

        ``Operators`` should be a dictionary mapping operator names ('tensor',
        'product', etc.) to a function that implements that operator for the
        correct number of operands.

        If given, ``getter`` is a function evaluated on each *leaf* node's
        value before applying the operator between them.  This could be used,
        for example, to operate on an attribute of the node values rather than
        directly on the node values.  The ``getter`` is passed both the index
        of the leaf (a count starting at 0 that is incremented after each leaf
        is found) and the leaf node itself.

        The ``start`` and ``stop`` arguments allow evaluating a sub-expression
        within the expression tree.

        Nc             S   s   |S )Nr   )idxr   r   r   r   <lambda>       z)ExpressionTree.evaluate.<locals>.<lambda>r         r<   )r   r>   r5   r7   r   r0   r6   extend)r   	operatorsgetterstartstopr8   leaf_idxr9   operatorr   r   operandsoperandr?   r   r   r   evaluate   s:    

	zExpressionTree.evaluatec             C   sX   g }x8| j | jfD ](}t|tr0||  q|| qW | j| j|d |d dS )Nr   rB   )r   r   )r   r   r$   r
   r7   r   	__class__r   )r   childrenchildr   r   r   r      s    
zExpressionTree.copyc       	      C   s   d}t  }|d krdd }x|  D ]}|jrH|||| |d7 }q$||j }| }| }|jd k	r|jjs||jj |k rd| d}|jd k	r|jjs||jj |k rd| d}|d||j|f q$W d|S )	Nr   c             S   s   d|  dS )N[]r   )r2   lr   r   r   r@     rA   z2ExpressionTree.format_expression.<locals>.<lambda>rB   ()  )	r   r>   r5   r7   r   r6   r   r   join)	r   Zoperator_precedenceZformat_leafrI   rK   r9   Z
oper_orderr   r   r   r   r   format_expression  s(    
z ExpressionTree.format_expression)NNNN)Nr   N)N)__name__
__module____qualname__r   r   r   r#   staticmethodr(   propertyr.   r4   r5   r:   r;   r>   rM   r   rY   r   r   r   r   r
      s   
&&
Rc               @   sL   e Zd ZdZeZdd Zdd Zdd Zdd	 Z	d
d Z
dd Zdd ZdS )r   a=  
    Creates a `dict` like object that wraps an existing `dict` or other
    `MutableMapping`, along with a `dict` of *key aliases* that translate
    between specific keys in this dict to different keys in the underlying
    dict.

    In other words, keys that do not have an associated alias are accessed and
    stored like a normal `dict`.  However, a key that has an alias is accessed
    and stored to the "parent" dict via the alias.

    Parameters
    ----------
    parent : dict-like
        The parent `dict` that aliased keys and accessed from and stored to.

    aliases : dict-like
        Maps keys in this dict to their associated keys in the parent dict.

    Examples
    --------

    >>> parent = {'a': 1, 'b': 2, 'c': 3}
    >>> aliases = {'foo': 'a', 'bar': 'c'}
    >>> alias_dict = AliasDict(parent, aliases)
    >>> alias_dict['foo']
    1
    >>> alias_dict['bar']
    3

    Keys in the original parent dict are not visible if they were not
    aliased:

    >>> alias_dict['b']
    Traceback (most recent call last):
    ...
    KeyError: 'b'

    Likewise, updates to aliased keys are reflected back in the parent dict:

    >>> alias_dict['foo'] = 42
    >>> alias_dict['foo']
    42
    >>> parent['a']
    42

    However, updates/insertions to keys that are *not* aliased are not
    reflected in the parent dict:

    >>> alias_dict['qux'] = 99
    >>> alias_dict['qux']
    99
    >>> 'qux' in parent
    False

    In particular, updates on the `AliasDict` to a key that is equal to
    one of the aliased keys in the parent dict does *not* update the parent
    dict.  For example, ``alias_dict`` aliases ``'foo'`` to ``'a'``.  But
    assigning to a key ``'a'`` on the `AliasDict` does not impact the
    parent:

    >>> alias_dict['a'] = 'nope'
    >>> alias_dict['a']
    'nope'
    >>> parent['a']
    42
    c             C   s   || _ |  | _t|| _d S )N)_parent_store_type_storer   _aliases)r   parentaliasesr   r   r   r   u  s    
zAliasDict.__init__c             C   sB   || j kr8y| j| j |  S  tk
r6   t|Y nX | j| S )N)rb   r_   KeyErrorra   )r   r'   r   r   r   __getitem__z  s    
zAliasDict.__getitem__c             C   s*   || j kr|| j| j | < n
|| j|< d S )N)rb   r_   ra   )r   r'   r   r   r   r   __setitem__  s    
zAliasDict.__setitem__c             C   sH   || j kr<y| j| j | = W qD tk
r8   t|Y qDX n| j|= d S )N)rb   r_   re   ra   )r   r'   r   r   r   __delitem__  s    
zAliasDict.__delitem__c             c   sB   x&| j  D ]\}}|| jkr|V  qW x| jD ]
}|V  q0W dS )z
        First iterates over keys from the parent dict (if the aliased keys are
        present in the parent), followed by any keys in the local store.
        N)rb   r    r_   ra   )r   r'   aliasr   r   r   __iter__  s
    

zAliasDict.__iter__c             C   s   t tt| S )N)r0   listiter)r   r   r   r   __len__  s    zAliasDict.__len__c             C   sL   |   }x.| j D ] \}}|| jkr| j| ||< qW || j t|S )N)r`   rb   r    r_   updatera   repr)r   Z
store_copyr'   ri   r   r   r   __repr__  s    
zAliasDict.__repr__N)rZ   r[   r\   __doc__r   r`   r   rf   rg   rh   rj   rm   rp   r   r   r   r   r   *  s   B		c                   sN   e Zd ZdZdZd fdd	Zdd Zedd Ze	d	d
 Z
dd Z  ZS )_BoundingBoxa;  
    Base class for models with custom bounding box templates (methods that
    return an actual bounding box tuple given some adjustable parameters--see
    for example `~astropy.modeling.models.Gaussian1D.bounding_box`).

    On these classes the ``bounding_box`` property still returns a `tuple`
    giving the default bounding box for that instance of the model.  But that
    tuple may also be a subclass of this class that is callable, and allows
    a new tuple to be returned using a user-supplied value for any adjustable
    parameters to the bounding box.
    Nc                s    t  | |}|d k	r||_|S )N)super__new___model)clsZinput_ru   r   )rN   r   r   rt     s    z_BoundingBox.__new__c             O   s   t dd S )NzPThis bounding box is fixed by the model and does not have adjustable parameters.)NotImplementedError)r   argskwargsr   r   r   __call__  s    z_BoundingBox.__call__c             C   s>  |j }|dkrd|jj d}yt|dk}W nF tk
r\   tdd |D dk}Y n tk
rv   t|Y nX t|r|st|t|dkr| t	|d fS | t	|S d|jj d|j  d	}yt
d
d |D }W n tk
r   d}Y nX t||krd}t|r |s(t|| dd |D S dS )a%  
        Validate a given bounding box sequence against the given model (which
        may be either a subclass of `~astropy.modeling.Model` or an instance
        thereof, so long as the ``.inputs`` attribute is defined.

        Currently this just checks that the bounding_box is either a 2-tuple
        of lower and upper bounds for 1-D models, or an N-tuple of 2-tuples
        for N-D models.

        This also returns a normalized version of the bounding_box input to
        ensure it is always an N-tuple (even for the 1-D case).
        rB   zBounding box for z model must be a sequence
            of length 2 consisting of a lower and upper bound, or a 1-tuple
            containing such a sequence as its sole element.))rC   )rB   rC   c             S   s   g | ]}|  qS r   )Zto_value)r   br   r   r   
<listcomp>  s    z)_BoundingBox.validate.<locals>.<listcomp>r   z0 model must be a sequence
            of length z (the number of model inputs) consisting of pairs of
            lower and upper bounds for those inputs on which to evaluate the model.c             S   s   g | ]}t |d kqS )rC   )r0   )r   r2   r   r   r   r|     s    Fc             s   s   | ]}t |V  qd S )N)tuple)r   Zboundsr   r   r   r     s    z(_BoundingBox.validate.<locals>.<genexpr>N)Zn_inputsrN   rZ   npshape	TypeError
ValueErrorr   r0   r}   all)rv   modelZbounding_boxndZMESSAGEZvalid_shaper   r   r   validate  s0    
z_BoundingBox.validatec             C   s   t | d trt| S dS d S )Nr   rB   )r$   r}   r0   )r   r   r   r   	dimension   s    z_BoundingBox.dimensionc                sV   j dkr&td d    gS j dkrJ fddtj D S tddS )z
        Given a resolution find the meshgrid approximation of the bounding box.

        Parameters
        ----------
        resolution: float
            The resolution of the grid.
        rB   r   c                s.   g | ]&}t | d  | d    qS )r   rB   )r~   arange)r   r2   )
resolutionr   r   r   r|     s    z'_BoundingBox.domain.<locals>.<listcomp>z)Bounding box must have positive dimensionN)r   r~   r   ranger   )r   r   r   )r   r   r   domain  s
    


z_BoundingBox.domain)N)rZ   r[   r\   rq   ru   rt   rz   classmethodr   r^   r   r   __classcell__r   r   )rN   r   rr     s   	5rr   c                s    fddS )a  
    Given a binary operator (as a callable of two arguments) ``oper`` and
    two callables ``f`` and ``g`` which accept the same arguments,
    returns a *new* function that takes the same arguments as ``f`` and ``g``,
    but passes the outputs of ``f`` and ``g`` in the given ``oper``.

    ``f`` and ``g`` are assumed to return tuples (which may be 1-tuples).  The
    given operator is applied element-wise to tuple outputs).

    Example
    -------

    >>> from operator import add
    >>> def prod(x, y):
    ...     return (x * y,)
    ...
    >>> sum_of_prod = make_binary_operator_eval(add, prod, prod)
    >>> sum_of_prod(3, 5)
    (30,)
    c                s(   t fddt | || |D S )Nc             3   s   | ]\}} ||V  qd S )Nr   )r   xy)operr   r   r   0  s    z>make_binary_operator_eval.<locals>.<lambda>.<locals>.<genexpr>)r}   zip)r   params)fgr   r   r   r@   /  s    z+make_binary_operator_eval.<locals>.<lambda>r   )r   r   r   r   )r   r   r   r   make_binary_operator_eval  s    r   c             C   s   t j|t jd}t j|t jd}|jdks4|jdkr<td|d |d  |d |d   }|d |d  |d |d   |d |d   }|||   S )a  
    Map domain into window by shifting and scaling.

    Parameters
    ----------
    oldx : array
          original coordinates
    domain : list or tuple of length 2
          function domain
    window : list or tuple of length 2
          range into which to map the domain
    )Zdtype)rC   z5Expected "domain" and window to be a tuple of size 2.rB   r   )r~   arrayZfloat64r   r   )Zoldxr   ZwindowZscloffr   r   r   r   4  s     0c             C   s,   | d k	r(t | jdkr tdt| S | S )N)rC   z-domain and window should be tuples of size 2.)r~   Z
asanyarrayr   r   r}   )r   r   r   r   _validate_domain_windowJ  s
    r   c             C   sT   || ks| dk s|dk rdS d}x.t t|| | D ]}|| |  |d  }q4W |S )z
    The number of combinations of N things taken k at a time.

    Parameters
    ----------
    N : int, array
        Number of things.
    k : int, array
        Number of elements taken.

    r   rB   )r   min)Nkvaljr   r   r   r   R  s    c             C   s(   t j| ddd}ddd | D S )zR
    Represents a multi-dimensional Numpy array flattened onto a single line.
    z, T)	separatorZsuppress_smallrV   c             s   s   | ]}|  V  qd S )N)strip)r   rS   r   r   r   r   k  s    z%array_repr_oneline.<locals>.<genexpr>)r~   Zarray2stringrX   
splitlines)r   rr   r   r   array_repr_onelinef  s    r   c             C   s:   t | |r2tdd | D } tdd |D }| | S )aR  
    For use with the join operator &: Combine left input/output labels with
    right input/output labels.

    If none of the labels conflict then this just returns a sum of tuples.
    However if *any* of the labels conflict, this appends '0' to the left-hand
    labels and '1' to the right-hand labels so there is no ambiguity).
    c             s   s   | ]}|d  V  qdS )0Nr   )r   rS   r   r   r   r   y  s    z!combine_labels.<locals>.<genexpr>c             s   s   | ]}|d  V  qdS )1Nr   )r   r   r   r   r   r   z  s    )setintersectionr}   )r   r   r   r   r   combine_labelsn  s    
r   c             C   s   t | t | | }| t | t | |t | t |  }t || t | }|t | t | | t | t |  }t|tjst|tjrt t||gS t ||gS )a  
    Calculates the extent of a box encapsulating a rotated 2D ellipse.

    Parameters
    ----------
    a : float or `~astropy.units.Quantity`
        Major axis.
    b : float or `~astropy.units.Quantity`
        Minor axis.
    theta : float or `~astropy.units.Quantity` ['angle']
        Rotation angle. If given as a floating-point value, it is assumed to be
        in radians.

    Returns
    -------
    offsets : tuple
        The absolute value of the offset distances from the ellipse center that
        define its bounding box region, ``(dx, dy)``.

    Examples
    --------
    .. plot::
        :include-source:

        import numpy as np
        import matplotlib.pyplot as plt
        from astropy.modeling.models import Ellipse2D
        from astropy.modeling.utils import ellipse_extent, render_model

        amplitude = 1
        x0 = 50
        y0 = 50
        a = 30
        b = 10
        theta = np.pi/4

        model = Ellipse2D(amplitude, x0, y0, a, b, theta)

        dx, dy = ellipse_extent(a, b, theta)

        limits = [x0 - dx, x0 + dx, y0 - dy, y0 + dy]

        model.bounding_box = limits

        image = render_model(model)

        plt.imshow(image, cmap='binary', interpolation='nearest', alpha=.5,
                  extent = limits)
        plt.show()
    )	r~   Zarctan2tancossinr$   uQuantityabs)ar{   thetatZdxZdyr   r   r   r     s    400c             C   sh   t | }g }g }xN|j D ]@}|j|j|jfkr:td|j|jkrR|	| q|	| qW ||fS )z
    Given a callable, determine the input variables and the
    parameters.

    Parameters
    ----------
    func : callable

    Returns
    -------
    inputs, params : tuple
        Each entry is a list of inspect.Parameter objects
    z)Signature must not have *args or **kwargs)
r   
parametersvalueskindVAR_POSITIONALVAR_KEYWORDr   defaultemptyr7   )funcsigr   r   paramr   r   r   get_inputs_and_params  s    r   c             C   s    | j d kr| j| S | j|S )N)unitr   Zquantityto)Z	parameterr   r   r   r   _parameter_with_unit  s    

r   c             C   s   |d kr| S | | | S )N)r   )r   Zold_unitZnew_unitr   r   r   _parameter_without_unit  s    r   c             C   sb   i }xX| D ]P}g ||< |d k	r8||kr8||  ||  |d k	r
||kr
||  ||  q
W |S )N)rD   )keysZeq1Zeq2eqr'   r   r   r   _combine_equivalency_dict  s    
r   c             C   s"   t | tjr| tjS t| S )z Convert ``value`` to radian. )r$   r   r   r   Zradr~   Zdeg2rad)r   r   r   r   
_to_radian  s    r   c             C   s    |dk	r| |  |S t| S )z3 Convert value with ``raw_unit`` to ``orig_unit``. N)r   r~   Zrad2deg)r   Zraw_unitZ	orig_unitr   r   r   _to_orig_unit  s    r   c                   s,   e Zd ZdZ fddZ fddZ  ZS )_ConstraintsDictzv
    Wrapper around UserDict to allow updating the constraints
    on a Parameter when the dictionary is updated.
    c                sH   || _ || _i }x&|jD ]}t||}t||||< qW t | d S )N)ru   constraint_typeZparam_namesr   rs   r   )r   r   r   cnamer   )rN   r   r   r     s    
z_ConstraintsDict.__init__c                s,   t  || t| j|}t|| j| d S )N)rs   rg   r   ru   r!   r   )r   r'   r   r   )rN   r   r   rg     s    z_ConstraintsDict.__setitem__)rZ   r[   r\   rq   r   rg   r   r   r   )rN   r   r     s   	r   c                   sJ   e Zd ZdZdi f fdd	Z fddZdd Zd	d
 Zdd Z  Z	S )_SpecialOperatorsDicta  
    Wrapper around UserDict to allow for better tracking of the Special
    Operators for CompoundModels. This dictionary is structured so that
    one cannot inadvertently overwrite an existing special operator.

    Parameters
    ----------
    unique_id: int
        the last used unique_id for a SPECIAL OPERATOR
    special_operators: dict
        a dictionary containing the special_operators

    Notes
    -----
    Direct setting of operators (`dict[key] = value`) into the
    dictionary has been deprecated in favor of the `.add(name, value)`
    method, so that unique dictionary keys can be generated and tracked
    consistently.
    r   c                s   t  | || _d S )N)rs   r   
_unique_id)r   	unique_idZspecial_operators)rN   r   r   r   ,  s    z_SpecialOperatorsDict.__init__c                s,   || krt d| dnt || d S )NzSpecial operator "z" already exists)r   rs   rg   )r   r'   r   )rN   r   r   
_set_value0  s    z _SpecialOperatorsDict._set_valuec             C   s   |  || ttd d S )Nz
            Special operator dictionary assignment has been deprecated.
            Please use `.add` instead, so that you can capture a unique
            key for your operator.
            )r   warningswarnDeprecationWarning)r   r'   r   r   r   r   rg   6  s    z!_SpecialOperatorsDict.__setitem__c             C   s   |  j d7  _ | j S )NrB   )r   )r   r   r   r   _get_unique_id@  s    z$_SpecialOperatorsDict._get_unique_idc             C   s   ||   f}| || |S )a  
        Adds a special operator to the dictionary, and then returns the
        unique key that the operator is stored under for later reference.

        Parameters
        ----------
        operator_name: str
            the name for the operator
        operator: function
            the actual operator function which will be used

        Returns
        -------
        the unique operator key for the dictionary
            `(operator_name, unique_id)`
        )r   r   )r   Zoperator_namerJ   r'   r   r   r   addE  s    z_SpecialOperatorsDict.add)
rZ   r[   r\   rq   r   r   rg   r   r   r   r   r   )rN   r   r     s   
r   )NN)NN)'rq   collectionsr   r   collections.abcr   inspectr   numpyr~   r   Zastropy.utils.decoratorsr   Zastropy.utilsr   r   Zastropyr	   r   __all__r
   r   r}   rr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s>   
   k?

