a
    ߙfbg                     @   s   d Z ddlZddlmZ ddlZddlmZ ddl	m
Z ddlmZ g dZed	d
ZeddZeddZG dd dejZdd ZG dd deZG dd dejZG dd deZdS )z\
This module contains the fundamental classes used for representing
coordinates in astropy.
    N)
namedtuple   )angle_formats)units)
isiterable)AngleLatitude	Longitude	hms_tuple)hms	dms_tuple)dr   r   signed_dms_tuple)signr   r   r   c                       s   e Zd ZdZejZdZd% fdd	Ze	dd Z
e	dd	 Z fd
dZedd Zedd Zedd Zedd Zd&ddZdd Zd'ddZd(ddZd)dd Zd!d" Zd#d$ Z  ZS )*r   u	  
    One or more angular value(s) with units equivalent to radians or degrees.

    An angle can be specified either as an array, scalar, tuple (see
    below), string, `~astropy.units.Quantity` or another
    :class:`~astropy.coordinates.Angle`.

    The input parser is flexible and supports a variety of formats.
    The examples below illustrate common ways of initializing an `Angle`
    object. First some imports::

      >>> from astropy.coordinates import Angle
      >>> from astropy import units as u

    The angle values can now be provided::

      >>> Angle('10.2345d')
      <Angle 10.2345 deg>
      >>> Angle(['10.2345d', '-20d'])
      <Angle [ 10.2345, -20.    ] deg>
      >>> Angle('1:2:30.43 degrees')
      <Angle 1.04178611 deg>
      >>> Angle('1 2 0 hours')
      <Angle 1.03333333 hourangle>
      >>> Angle(np.arange(1, 8), unit=u.deg)
      <Angle [1., 2., 3., 4., 5., 6., 7.] deg>
      >>> Angle('1°2′3″')
      <Angle 1.03416667 deg>
      >>> Angle('1°2′3″N')
      <Angle 1.03416667 deg>
      >>> Angle('1d2m3.4s')
      <Angle 1.03427778 deg>
      >>> Angle('1d2m3.4sS')
      <Angle -1.03427778 deg>
      >>> Angle('-1h2m3s')
      <Angle -1.03416667 hourangle>
      >>> Angle('-1h2m3sE')
      <Angle -1.03416667 hourangle>
      >>> Angle('-1h2.5m')
      <Angle -1.04166667 hourangle>
      >>> Angle('-1h2.5mW')
      <Angle 1.04166667 hourangle>
      >>> Angle('-1:2.5', unit=u.deg)
      <Angle -1.04166667 deg>
      >>> Angle((10, 11, 12), unit='hourangle')  # (h, m, s)
      <Angle 10.18666667 hourangle>
      >>> Angle((-1, 2, 3), unit=u.deg)  # (d, m, s)
      <Angle -1.03416667 deg>
      >>> Angle(10.2345 * u.deg)
      <Angle 10.2345 deg>
      >>> Angle(Angle(10.2345 * u.deg))
      <Angle 10.2345 deg>

    Parameters
    ----------
    angle : `~numpy.array`, scalar, `~astropy.units.Quantity`, :class:`~astropy.coordinates.Angle`
        The angle value. If a tuple, will be interpreted as ``(h, m,
        s)`` or ``(d, m, s)`` depending on ``unit``. If a string, it
        will be interpreted following the rules described above.

        If ``angle`` is a sequence or array of strings, the resulting
        values will be in the given ``unit``, or if `None` is provided,
        the unit will be taken from the first given value.

    unit : unit-like, optional
        The unit of the value specified for the angle.  This may be
        any string that `~astropy.units.Unit` understands, but it is
        better to give an actual unit object.  Must be an angular
        unit.

    dtype : `~numpy.dtype`, optional
        See `~astropy.units.Quantity`.

    copy : bool, optional
        See `~astropy.units.Quantity`.

    Raises
    ------
    `~astropy.units.UnitsError`
        If a unit is not provided or it is not an angular unit.
    TNc                    s   t |tjsĈ d ur$| t  t |tr<| | }nt |trt	| \}}|d u rb }t |trx| ||}| urtj||dd}n2t
|rt |tjr|jjdvsć fdd|D }t j| | f||d|S )NFcopyZSUVOc                    s   g | ]}t | d dqS )Fr   )r   ).0xunit 9lib/python3.9/site-packages/astropy/coordinates/angles.py
<listcomp>       z!Angle.__new__.<locals>.<listcomp>)dtyper   )
isinstanceuZQuantity_convert_unit_to_angle_unitUnittuple_tuple_to_floatstrformZparse_angler   npndarrayr   kindsuper__new__)clsangler   r   r   kwargsZ
angle_unit	__class__r   r   r)   p   s,    




zAngle.__new__c                 C   sD   |t jkrtj|  S |t jkr(tj|  S t d|  d| ddS )z
        Converts an angle represented as a 3-tuple or 2-tuple into a floating
        point number in the given unit.
        zCan not parse 'z' as unit ''N)r   	hourangler$   Zhms_to_hoursdegreeZdms_to_degrees
UnitsError)r+   r   r   r   r   r"      s
    



zAngle._tuple_to_floatc                 C   s   | t ju rt jS | S N)r   hourr0   r   r   r   r   r      s    z!Angle._convert_unit_to_angle_unitc                    s   t  | | d S r3   )r(   	_set_unitr   )selfr   r-   r   r   r5      s    zAngle._set_unitc                 C   s   | j S )zB
        The angle's value in hours (read-only property).
        )r0   r6   r   r   r   r4      s    z
Angle.hourc                 C   s   t t| j S )z
        The angle's value in hours, as a named tuple with ``(h, m, s)``
        members.  (This is a read-only property.)
        )r
   r$   Zhours_to_hmsr0   r7   r   r   r   hms   s    z	Angle.hmsc                 C   s   t t| j S )z
        The angle's value in degrees, as a named tuple with ``(d, m, s)``
        members.  (This is a read-only property.)
        )r   r$   degrees_to_dmsr1   r7   r   r   r   dms   s    z	Angle.dmsc                 C   s&   t t| jgtt| jR  S )a  
        The angle's value in degrees, as a named tuple with ``(sign, d, m, s)``
        members.  The ``d``, ``m``, ``s`` are thus always positive, and the sign of
        the angle is given by ``sign``. (This is a read-only property.)

        This is primarily intended for use with `dms` to generate string
        representations of coordinates that are correct for negative angles.
        )r   r%   r   r1   r$   r9   absr7   r   r   r   
signed_dms   s    
zAngle.signed_dmsFfromunit   c	                    s^  |du r| j }n| t|}tjdtjditjg dtjg ditjdtjdid}	d	kr|	vrxtd
 d|	 }
||
v r|
| |tju r|r| j}durdt d jqdjn$d	krd| j}fddn.|tju rV|r.| j	}dur&dt d jndjn&d	kr<d| j	}fddn|
tjr|r| |}durdt d jndjnxd	kr | |}|jddkrЈdd durfdd}|nfdd}|ntd|j dn
td fdd}tj|dgd}||}|jd krZ|d! }|S )"a
   A string representation of the angle.

        Parameters
        ----------
        unit : `~astropy.units.UnitBase`, optional
            Specifies the unit.  Must be an angular unit.  If not
            provided, the unit used to initialize the angle will be
            used.

        decimal : bool, optional
            If `True`, a decimal representation will be used, otherwise
            the returned string will be in sexagesimal form.

        sep : str, optional
            The separator between numbers in a sexagesimal
            representation.  E.g., if it is ':', the result is
            ``'12:41:11.1241'``. Also accepts 2 or 3 separators. E.g.,
            ``sep='hms'`` would give the result ``'12h41m11.1241s'``, or
            sep='-:' would yield ``'11-21:17.124'``.  Alternatively, the
            special string 'fromunit' means 'dms' if the unit is
            degrees, or 'hms' if the unit is hours.

        precision : int, optional
            The level of decimal precision.  If ``decimal`` is `True`,
            this is the raw precision, otherwise it gives the
            precision of the last place of the sexagesimal
            representation (seconds).  If `None`, or not provided, the
            number of decimal places is determined by the value, and
            will be between 0-8 decimal places as required.

        alwayssign : bool, optional
            If `True`, include the sign no matter what.  If `False`,
            only include the sign if it is negative.

        pad : bool, optional
            If `True`, include leading zeros when needed to ensure a
            fixed number of characters for sexagesimal representation.

        fields : int, optional
            Specifies the number of fields to display when outputting
            sexagesimal notation.  For example:

                - fields == 1: ``'5d'``
                - fields == 2: ``'5d45m'``
                - fields == 3: ``'5d45m32.5s'``

            By default, all fields are displayed.

        format : str, optional
            The format of the result.  If not provided, an unadorned
            string is returned.  Supported values are:

            - 'latex': Return a LaTeX-formatted string

            - 'unicode': Return a string containing non-ASCII unicode
              characters, such as the degree symbol

        Returns
        -------
        strrepr : str or array
            A string representation of the angle. If the angle is an array, this
            will be an array with a unicode dtype.

        Nr:   r8   )z^\circz	{}^\primez{}^{\prime\prime})z^{\mathrm{h}}z^{\mathrm{m}}z^{\mathrm{s}}u   °′″u   ʰᵐˢ)NlatexZunicoder=   zUnknown format 'r/   {0:0.zf}z{:g}c                    s   t j|  dS N)	precisionseppadfields)r$   Zdegrees_to_stringr   rE   rD   rB   rC   r   r   <lambda>.  s   z!Angle.to_string.<locals>.<lambda>c                    s   t j|  dS rA   )r$   Zhours_to_stringrF   rG   r   r   rH   =  s   z{0:1.formatr?   r   c                    s   dt   d | S )Nr@   zf}{1})r#   rJ   val)rB   unit_stringr   r   plain_unit_formatO  s    z*Angle.to_string.<locals>.plain_unit_formatc                    s   | d  S )Ngr   rL   )rN   r   r   rO   T  s    z0' can not be represented in sexagesimal notationz/The unit value provided is not an angular unit.c                    sN   t | sDt| } r,|ds,d| }dkr@d| d}|S |  }|S )N-+r?   $)r%   Zisnanfloat
startswith)rM   r   )
alwayssignrJ   funcr   r   	do_format_  s    
z"Angle.to_string.<locals>.do_formatU)Zotypesr   r   )r   r   r   r    r1   r0   
ValueErrorr#   rJ   r4   Zis_equivalentradianto_value	to_stringnamer2   r%   Z	vectorizendim)r6   r   decimalrC   rB   rV   rD   rE   rJ   Z
separatorsZsepsvaluesrO   rX   Zformat_ufuncresultr   )rV   rE   rJ   rW   rD   rB   rC   rN   r   r]      s    C










zAngle.to_stringc                 C   s   t j| jd}|| j}|| }| tj}tjddl || | }tj	|dd t
|dkr||| 8 }|||k  |8  < |||k   |7  < W d   n1 s0    Y  dS )zr
        Implementation that assumes ``angle`` is already validated
        and that wrapping is inplace.
        g     v@ignoreZinvalidFr   r   N)r   r1   tor   r\   viewr%   r&   errstateZ
nan_to_numany)r6   
wrap_angleZa360Zwrap_angle_floorZ
self_anglewrapsr   r   r   _wrap_ats  s    zAngle._wrap_atc                 C   s.   t |dd}|s|  } | | |r*dS | S )an  
        Wrap the `~astropy.coordinates.Angle` object at the given ``wrap_angle``.

        This method forces all the angle values to be within a contiguous
        360 degree range so that ``wrap_angle - 360d <= angle <
        wrap_angle``. By default a new Angle object is returned, but if the
        ``inplace`` argument is `True` then the `~astropy.coordinates.Angle`
        object is wrapped in place and nothing is returned.

        For instance::

          >>> from astropy.coordinates import Angle
          >>> import astropy.units as u
          >>> a = Angle([-20.0, 150.0, 350.0] * u.deg)

          >>> a.wrap_at(360 * u.deg).degree  # Wrap into range 0 to 360 degrees  # doctest: +FLOAT_CMP
          array([340., 150., 350.])

          >>> a.wrap_at('180d', inplace=True)  # Wrap into range -180 to 180 degrees  # doctest: +FLOAT_CMP
          >>> a.degree  # doctest: +FLOAT_CMP
          array([-20., 150., -10.])

        Parameters
        ----------
        wrap_angle : angle-like
            Specifies a single value for the wrap angle.  This can be any
            object that can initialize an `~astropy.coordinates.Angle` object,
            e.g. ``'180d'``, ``180 * u.deg``, or ``Angle(180, unit=u.deg)``.

        inplace : bool
            If `True` then wrap the object in place instead of returning
            a new `~astropy.coordinates.Angle`

        Returns
        -------
        out : Angle or None
            If ``inplace is False`` (default), return new
            `~astropy.coordinates.Angle` object with angles wrapped accordingly.
            Otherwise wrap in place and return `None`.
        Fr   N)r   r   rk   )r6   ri   Zinplacer   r   r   wrap_at  s
    )
zAngle.wrap_atc                 C   sL   d}|dur"|t t|| kM }|rD|durD|t | t|k M }t|S )a  
        Check if all angle(s) satisfy ``lower <= angle < upper``

        If ``lower`` is not specified (or `None`) then no lower bounds check is
        performed.  Likewise ``upper`` can be left unspecified.  For example::

          >>> from astropy.coordinates import Angle
          >>> import astropy.units as u
          >>> a = Angle([-20, 150, 350] * u.deg)
          >>> a.is_within_bounds('0d', '360d')
          False
          >>> a.is_within_bounds(None, '360d')
          True
          >>> a.is_within_bounds(-30 * u.deg, None)
          True

        Parameters
        ----------
        lower : angle-like or None
            Specifies lower bound for checking.  This can be any object
            that can initialize an `~astropy.coordinates.Angle` object, e.g. ``'180d'``,
            ``180 * u.deg``, or ``Angle(180, unit=u.deg)``.
        upper : angle-like or None
            Specifies upper bound for checking.  This can be any object
            that can initialize an `~astropy.coordinates.Angle` object, e.g. ``'180d'``,
            ``180 * u.deg``, or ``Angle(180, unit=u.deg)``.

        Returns
        -------
        is_within_bounds : bool
            `True` if all angles satisfy ``lower <= angle < upper``
        TN)r%   allr   bool)r6   lowerupperokr   r   r   is_within_bounds  s    !zAngle.is_within_boundsc                    s0   | j r| j dS  fdd}tj| d|idS )NrI   c                    s   | j  dS )NrI   )r]   rF   rI   r   r   	formatter  s    z$Angle._str_helper.<locals>.formatterrm   )rs   )Zisscalarr]   r%   Zarray2string)r6   rJ   rs   r   rI   r   _str_helper  s    zAngle._str_helperc                 C   s   |   S r3   rt   r7   r   r   r   __str__  s    zAngle.__str__c                 C   s   | j ddS )Nr?   rI   ru   r7   r   r   r   _repr_latex_  s    zAngle._repr_latex_)NNT)NFr=   NFFr>   N)F)NN)N)__name__
__module____qualname____doc__r   r[   Z_equivalent_unitZ _include_easy_conversion_membersr)   staticmethodr"   r   r5   propertyr4   r8   r:   r<   r]   rk   rl   rr   rt   rv   rw   __classcell__r   r   r-   r   r      s8   Q





   
 .
/
(
	r   c                 C   s8   t | trtdd | D S t | ttfr4| tS | S )zReturn any Angle subclass objects as an Angle objects.

    This is used to ensure that Latitude and Longitude change to Angle
    objects when they are used in calculations (such as lon/2.)
    c                 s   s   | ]}t |V  qd S r3   )_no_angle_subclass)r   Z_objr   r   r   	<genexpr>  r   z%_no_angle_subclass.<locals>.<genexpr>)r   r!   r   r	   rf   r   )objr   r   r   r     s    
r   c                       sD   e Zd ZdZd fdd	ZdddZ fddZ fd	d
Z  ZS )r   a  
    Latitude-like angle(s) which must be in the range -90 to +90 deg.

    A Latitude object is distinguished from a pure
    :class:`~astropy.coordinates.Angle` by virtue of being constrained
    so that::

      -90.0 * u.deg <= angle(s) <= +90.0 * u.deg

    Any attempt to set a value outside that range will result in a
    `ValueError`.

    The input angle(s) can be specified either as an array, list,
    scalar, tuple (see below), string,
    :class:`~astropy.units.Quantity` or another
    :class:`~astropy.coordinates.Angle`.

    The input parser is flexible and supports all of the input formats
    supported by :class:`~astropy.coordinates.Angle`.

    Parameters
    ----------
    angle : array, list, scalar, `~astropy.units.Quantity`, `~astropy.coordinates.Angle`
        The angle value(s). If a tuple, will be interpreted as ``(h, m, s)``
        or ``(d, m, s)`` depending on ``unit``. If a string, it will be
        interpreted following the rules described for
        :class:`~astropy.coordinates.Angle`.

        If ``angle`` is a sequence or array of strings, the resulting
        values will be in the given ``unit``, or if `None` is provided,
        the unit will be taken from the first given value.

    unit : unit-like, optional
        The unit of the value specified for the angle.  This may be
        any string that `~astropy.units.Unit` understands, but it is
        better to give an actual unit object.  Must be an angular
        unit.

    Raises
    ------
    `~astropy.units.UnitsError`
        If a unit is not provided or it is not an angular unit.
    `TypeError`
        If the angle parameter is an instance of :class:`~astropy.coordinates.Longitude`.
    Nc                    s8   t |trtdt j| |fd|i|}|  |S )Nz9A Latitude angle cannot be created from a Longitude angler   )r   r	   	TypeErrorr(   r)   _validate_angles)r*   r+   r   r,   r6   r-   r   r   r)   .  s
    
zLatitude.__new__c                 C   s   |du r| }t j|jd}t j|jd}tjdd0 t|j|k pXt|j|k}W d   n1 sn0    Y  |rtd	|t jdS )znCheck that angles are between -90 and 90 degrees.
        If not given, the check is done on the object itselfNg     Vg     V@rc   rd   zCLatitude angle(s) must be within -90 deg <= angle <= 90 deg, got {})
r   r1   re   r   r%   rg   rh   valuerZ   rJ   )r6   Zanglesro   rp   Zinvalid_anglesr   r   r   r   6  s     
zLatitude._validate_anglesc                    s:   t |trtd|tjjur(| | t || d S )Nz8A Longitude angle cannot be assigned to a Latitude angle)	r   r	   r   r%   ZmaZmaskedr   r(   __setitem__r6   itemr   r-   r   r   r   K  s
    

zLatitude.__setitem__c                    s   t  j|i |}t|S r3   r(   __array_ufunc__r   r6   argsr,   Zresultsr-   r   r   r   U  s    zLatitude.__array_ufunc__)N)N)	rx   ry   rz   r{   r)   r   r   r   r~   r   r   r-   r   r      s
   -

r   c                   @   s   e Zd Zejjd ZdS )LongitudeInfo)ri   N)rx   ry   rz   r   QuantityInfoZ_represent_as_dict_attrsr   r   r   r   r   Z  s   r   c                       sx   e Zd ZdZdZedej Ze	 Z
d fdd	Z fddZedd	 Zejd
d	 Z fddZ fddZ  ZS )r	   a  
    Longitude-like angle(s) which are wrapped within a contiguous 360 degree range.

    A ``Longitude`` object is distinguished from a pure
    :class:`~astropy.coordinates.Angle` by virtue of a ``wrap_angle``
    property.  The ``wrap_angle`` specifies that all angle values
    represented by the object will be in the range::

      wrap_angle - 360 * u.deg <= angle(s) < wrap_angle

    The default ``wrap_angle`` is 360 deg.  Setting ``wrap_angle=180 *
    u.deg`` would instead result in values between -180 and +180 deg.
    Setting the ``wrap_angle`` attribute of an existing ``Longitude``
    object will result in re-wrapping the angle values in-place.

    The input angle(s) can be specified either as an array, list,
    scalar, tuple, string, :class:`~astropy.units.Quantity`
    or another :class:`~astropy.coordinates.Angle`.

    The input parser is flexible and supports all of the input formats
    supported by :class:`~astropy.coordinates.Angle`.

    Parameters
    ----------
    angle : tuple or angle-like
        The angle value(s). If a tuple, will be interpreted as ``(h, m s)`` or
        ``(d, m, s)`` depending on ``unit``. If a string, it will be interpreted
        following the rules described for :class:`~astropy.coordinates.Angle`.

        If ``angle`` is a sequence or array of strings, the resulting
        values will be in the given ``unit``, or if `None` is provided,
        the unit will be taken from the first given value.

    unit : unit-like ['angle'], optional
        The unit of the value specified for the angle.  This may be
        any string that `~astropy.units.Unit` understands, but it is
        better to give an actual unit object.  Must be an angular
        unit.

    wrap_angle : angle-like or None, optional
        Angle at which to wrap back to ``wrap_angle - 360 deg``.
        If ``None`` (default), it will be taken to be 360 deg unless ``angle``
        has a ``wrap_angle`` attribute already (i.e., is a ``Longitude``),
        in which case it will be taken from there.

    Raises
    ------
    `~astropy.units.UnitsError`
        If a unit is not provided or it is not an angular unit.
    `TypeError`
        If the angle parameter is an instance of :class:`~astropy.coordinates.Latitude`.
    Nih  c                    sL   t |trtdt j| |fd|i|}|d u rBt|d|j}||_|S )Nz:A Longitude angle cannot be created from a Latitude angle.r   ri   )r   r   r   r(   r)   getattr_default_wrap_angleri   )r*   r+   r   ri   r,   r6   r-   r   r   r)     s    
zLongitude.__new__c                    s0   t |trtdt || | | j d S )Nz8A Latitude angle cannot be assigned to a Longitude angle)r   r   r   r(   r   rk   ri   r   r-   r   r   r     s    
zLongitude.__setitem__c                 C   s   | j S r3   )_wrap_angler7   r   r   r   ri     s    zLongitude.wrap_anglec                 C   s   t |dd| _| | j d S )NFr   )r   r   rk   ri   )r6   r   r   r   r   ri     s    c                    s    t  | t|d| j| _d S )Nr   )r(   __array_finalize__r   r   r   )r6   r   r-   r   r   r     s    zLongitude.__array_finalize__c                    s   t  j|i |}t|S r3   r   r   r-   r   r   r     s    zLongitude.__array_ufunc__)NN)rx   ry   rz   r{   r   r   r   Zdegr   r   infor)   r   r}   ri   setterr   r   r~   r   r   r-   r   r	   ^  s   5

r	   )r{   warningscollectionsr   Znumpyr%    r   r$   Zastropyr   r   Zastropy.utilsr   __all__r
   r   r   ZSpecificTypeQuantityr   r   r   r   r   r	   r   r   r   r   <module>   s$   


   \Z