a
    ߙfb4                     @   s   d Z ddl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 dgZg d	Zd
Zede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dZdd  Zd(d!d"ZG d#d$ d$eZG d%d& d&eZdS ))z@
This module provides utility functions for the models package.
    )UserDict)MutableMapping)	signatureN)units)
deprecated	AliasDict)r   poly_map_domaincombellipse_extentzY
AliasDict is deprecated because it no longer serves a function anywhere
inside astropy.
z5.0c                   @   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_storedict_aliases)selfparentaliases r   5lib/python3.9/site-packages/astropy/modeling/utils.py__init__g   s    
zAliasDict.__init__c                 C   sB   || j v r8z| j| j |  W S  ty6   t|Y n0 | j| S r   r   r   KeyErrorr   r   keyr   r   r   __getitem__l   s    
zAliasDict.__getitem__c                 C   s*   || j v r|| j| j | < n
|| j|< d S r   )r   r   r   )r   r   valuer   r   r   __setitem__u   s    
zAliasDict.__setitem__c                 C   sF   || j v r:z| j| j | = W qB ty6   t|Y qB0 n| j|= d S r   r   r   r   r   r   __delitem__{   s    
zAliasDict.__delitem__c                 c   s:   | j  D ]\}}|| jv r
|V  q
| jD ]
}|V  q*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)r   itemsr   r   )r   r   aliasr   r   r   __iter__   s
    

zAliasDict.__iter__c                 C   s   t tt| S r   )lenlistiterr   r   r   r   __len__   s    zAliasDict.__len__c                 C   sH   |   }| j D ] \}}|| jv r| j| ||< q|| j t|S r   )r   r   r   r   updater   repr)r   Z
store_copyr   r    r   r   r   __repr__   s    
zAliasDict.__repr__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r!   r&   r)   r   r   r   r   r      s   C		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 r   r   ).0xy)operr   r   	<genexpr>       z>make_binary_operator_eval.<locals>.<lambda>.<locals>.<genexpr>)tuplezip)inputsparamsfgr1   r   r   <lambda>   s    z+make_binary_operator_eval.<locals>.<lambda>r   )r1   r9   r:   r   r8   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   z5Expected "domain" and window to be a tuple of size 2.   r   )nparrayZfloat64shape
ValueError)ZoldxZdomainZwindowZsclZoffr   r   r   r      s     0r   c                 C   s,   | d ur(t | jdkr tdt| S | S )Nr=   z-domain and window should be tuples of size 2.)r@   Z
asanyarrayrB   rC   r4   r   r   r   r   _validate_domain_window   s
    rE   c                 C   sP   || ks| dk s|dk rdS d}t t|| | D ]}|| |  |d  }q2|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   r?   )rangemin)Nkvaljr   r   r   r	      s    r	   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)Z	separatorZsuppress_small c                 s   s   | ]}|  V  qd S r   )stripr.   lr   r   r   r2      r3   z%array_repr_oneline.<locals>.<genexpr>)r@   Zarray2stringjoin
splitlines)rA   rr   r   r   array_repr_oneline   s    rS   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   rN   r   r   r   r2      r3   z!combine_labels.<locals>.<genexpr>c                 s   s   | ]}|d  V  qdS )1Nr   )r.   rR   r   r   r   r2     r3   )setintersectionr4   )leftrightr   r   r   combine_labels   s    
rZ   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 half size of a box encapsulating a rotated 2D
    ellipse.

    Parameters
    ----------
    a : float or `~astropy.units.Quantity`
        The ellipse semimajor axis.
    b : float or `~astropy.units.Quantity`
        The ellipse semiminor axis.
    theta : float or `~astropy.units.Quantity` ['angle']
        The rotation angle as an angular quantity
        (`~astropy.units.Quantity` or `~astropy.coordinates.Angle`) or
        a value in radians (as a float). The rotation angle increases
        counterclockwise.

    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arctan2ZtanZcosZsin
isinstanceuQuantityabs)abZthetatZdxZdyr   r   r   r
     s    400r
   c                 C   sd   t | }g }g }|j D ]@}|j|j|jfv r8td|j|jkrP|	| q|	| q||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kindZVAR_POSITIONALZVAR_KEYWORDrC   defaultemptyappend)funcZsigr6   r7   paramr   r   r   get_inputs_and_paramsE  s    rj   c                 C   s^   i }| D ]P}g ||< |d ur6||v r6||  ||  |d ur||v r||  ||  q|S r   )extend)keysZeq1Zeq2eqr   r   r   r   _combine_equivalency_dictb  s    rn   c                 C   s"   t | tjr| tjS t| S )z Convert ``value`` to radian. )r[   r\   r]   toZradr@   Zdeg2radrD   r   r   r   
_to_radianp  s    rp   c                 C   s    |dur| |  |S t| S )z3 Convert value with ``raw_unit`` to ``orig_unit``. N)ro   r@   Zrad2deg)r   Zraw_unitZ	orig_unitr   r   r   _to_orig_unitw  s    rq   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                    sD   || _ || _i }|jD ]}t||}t||||< qt | d S r   )_modelconstraint_typeZparam_namesgetattrsuperr   )r   Zmodelrt   cnameri   	__class__r   r   r     s    

z_ConstraintsDict.__init__c                    s,   t  || t| j|}t|| j| d S r   )rv   r   ru   rs   setattrrt   )r   r   rJ   ri   ry   r   r   r     s    z_ConstraintsDict.__setitem__)r*   r+   r,   r-   r   r   __classcell__r   r   ry   r   rr   ~  s   	rr   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 r   )rv   r   
_unique_id)r   Z	unique_idZspecial_operatorsry   r   r   r     s    z_SpecialOperatorsDict.__init__c                    s,   || v rt d| dnt || d S )NzSpecial operator "z" already exists)rC   rv   r   r   r   rJ   ry   r   r   
_set_value  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DeprecationWarningr   r   r   r   r     s    z!_SpecialOperatorsDict.__setitem__c                 C   s   |  j d7  _ | j S )Nr?   )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_nameoperatorr   r   r   r   add  s    z_SpecialOperatorsDict.add)
r*   r+   r,   r-   r   r   r   r   r   r|   r   r   ry   r   r}     s   
r}   )NN)NN) r-   collectionsr   collections.abcr   inspectr   Znumpyr@   r   Zastropyr   r\   Zastropy.utils.decoratorsr   Z__doctest_skip____all__Zdeprecation_msgr   r<   r   rE   r	   rS   rZ   r
   rj   rn   rp   rq   rr   r}   r   r   r   r   <module>   s4    ?

