B
    q\*s                 @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl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mZ d dlmZ d dlmZ d dlZd dlmZ d dlmZ dd ZeejfZG d	d
 d
Zdd ZdOd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" Z*d#d$ Z+d%d& Z,d'd( Z-d)d* Z.d+d, Z/da0d-d. Z1d/Z2d0Z3d1d2 Z4d3d4 Z5d5d6 Z6d7d8 Z7d9d: Z8d;d< Z9d=d> Z:d?d@ Z;dAdB Z<dCdD Z=dEdF Z>edPdGdHZ?dIdJ Z@dKdL ZAdMdN ZBdS )Q    N)contextmanagersuppress)data)LooseVersion)wraps)AstropyUserWarningc             C   s   | |k| |k  S )N )abr   r   3lib/python3.7/site-packages/astropy/io/fits/util.py<lambda>   s    r   c                   s<   e Zd ZdZdZdd Zdd Zdd Z fd	d
Z  Z	S )NotifierMixina  
    Mixin class that provides services by which objects can register
    listeners to changes on that object.

    All methods provided by this class are underscored, since this is intended
    for internal use to communicate between classes in a generic way, and is
    not machinery that should be exposed to users of the classes involved.

    Use the ``_add_listener`` method to register a listener on an instance of
    the notifier.  This registers the listener with a weak reference, so if
    no other references to the listener exist it is automatically dropped from
    the list and does not need to be manually removed.

    Call the ``_notify`` method on the notifier to update all listeners
    upon changes.  ``_notify('change_type', *args, **kwargs)`` results
    in calling ``listener._update_change_type(*args, **kwargs)`` on all
    listeners subscribed to that notifier.

    If a particular listener does not have the appropriate update method
    it is ignored.

    Examples
    --------

    >>> class Widget(NotifierMixin):
    ...     state = 1
    ...     def __init__(self, name):
    ...         self.name = name
    ...     def update_state(self):
    ...         self.state += 1
    ...         self._notify('widget_state_changed', self)
    ...
    >>> class WidgetListener:
    ...     def _update_widget_state_changed(self, widget):
    ...         print('Widget {0} changed state to {1}'.format(
    ...             widget.name, widget.state))
    ...
    >>> widget = Widget('fred')
    >>> listener = WidgetListener()
    >>> widget._add_listener(listener)
    >>> widget.update_state()
    Widget fred changed state to 2
    Nc             C   s&   | j dkrt | _ || j t|< dS )z
        Add an object to the list of listeners to notify of changes to this
        object.  This adds a weakref to the list of listeners that is
        removed from the listeners list when the listener has no other
        references to it.
        N)
_listenersweakrefWeakValueDictionaryid)selflistenerr   r   r   _add_listenerP   s    

zNotifierMixin._add_listenerc          	   C   s2   | j dkrdS tt | j t|= W dQ R X dS )z
        Removes the specified listener from the listeners list.  This relies
        on object identity (i.e. the ``is`` operator).
        N)r   r   KeyErrorr   )r   r   r   r   r   _remove_listener]   s    

zNotifierMixin._remove_listenerc             O   sf   | j dkrdS d|}xH| j  D ]:}| }|dkr8q$t||r$t||}t|r$||| q$W dS )aA  
        Notify all listeners of some particular state change by calling their
        ``_update_<notification>`` method with the given ``*args`` and
        ``**kwargs``.

        The notification does not by default include the object that actually
        changed (``self``), but it certainly may if required.
        Nz_update_{0})r   format	valuerefshasattrgetattrcallable)r   ZnotificationargskwargsZmethod_namer   methodr   r   r   _notifyi   s    




zNotifierMixin._notifyc                s:   yt   }W n tk
r,   | j }Y nX d|d< |S )zj
        Exclude listeners when saving the listener's state, since they may be
        ephemeral.
        Nr   )super__getstate__AttributeError__dict__copy)r   state)	__class__r   r   r!      s    	zNotifierMixin.__getstate__)
__name__
__module____qualname____doc__r   r   r   r   r!   __classcell__r   r   )r&   r   r   !   s   +r   c             C   s   t t| S )z
    Returns the first item returned by iterating over an iterable object.

    Example:

    >>> a = [1, 2, 3]
    >>> first(a)
    1
    )nextiter)iterabler   r   r   first   s    r/   c             c   s   |dkrt  }y|  }W n tk
r8   | | }Y nX xLt|tddD ]6}||krN|| |V  xt||D ]
}|V  qvW qNW dS )a  
    Generator over all subclasses of a given class, in depth first order.

    >>> class A: pass
    >>> class B(A): pass
    >>> class C(A): pass
    >>> class D(B,C): pass
    >>> class E(D): pass
    >>>
    >>> for cls in itersubclasses(A):
    ...     print(cls.__name__)
    B
    D
    E
    C
    >>> # get ALL classes currently defined
    >>> [cls.__name__ for cls in itersubclasses(object)]
    [...'tuple', ...'type', ...]

    From http://code.activestate.com/recipes/576949/
    Nr'   )key)set__subclasses__	TypeErrorsortedoperator
attrgetteradditersubclasses)cls_seenZsubssubr   r   r   r8      s    
r8   c                s   t   fdd}|S )z
    This decorator registers a custom SIGINT handler to catch and ignore SIGINT
    until the wrapped function is completed.
    c           
      s   t  }t  dko| dk}G  fddd}| }|rJttj|}z | | W d |r|d k	rvttj| nttjtj |jrtX d S )N   Z
MainThreadc                   s    e Zd Zdd Z fddZdS )z5ignore_sigint.<locals>.wrapped.<locals>.SigintHandlerc             S   s
   d| _ d S )NF)sigint_received)r   r   r   r   __init__   s    z>ignore_sigint.<locals>.wrapped.<locals>.SigintHandler.__init__c                s   t d jt d| _d S )Nz/KeyboardInterrupt ignored until {} is complete!T)warningswarnr   r'   r   r=   )r   Zsignumframe)funcr   r   __call__   s    z>ignore_sigint.<locals>.wrapped.<locals>.SigintHandler.__call__N)r'   r(   r)   r>   rC   r   )rB   r   r   SigintHandler   s   rD   )		threadingZcurrentThreadZactiveCountZgetNamesignalSIGINTSIG_DFLr=   KeyboardInterrupt)r   r   Zcurr_threadZsingle_threadrD   Zsigint_handlerZold_handler)rB   r   r   wrapped   s    
zignore_sigint.<locals>.wrapped)r   )rB   rJ   r   )rB   r   ignore_sigint   s    %rK   c             C   s(   t | \}}x|D ]}P qW t||S )zmReturn the items of an iterable paired with its next item.

    Ex: s -> (s0,s1), (s1,s2), (s2,s3), ....
    )	itertoolsteezip)r.   r	   r
   _r   r   r   pairwise   s    
rP   c             C   s   t | tr| dS t | tjrxt| jjtjrxtj	| d
t| }|jj| jjd krt|tj| jjd f}|S t | tjrt| jjtjstd| S )Nascii   z$string operation on non-string array)
isinstancestrencodenpndarray
issubclassdtypetypestr_charviewitemsizeastypebytes_r3   )snsr   r   r   encode_ascii  s    

rc   c             C   s  t | trNy
| dS  tk
rJ   tdt | jddd} | ddS X nt | tj	rt
| jjtjr| jdkr| jjdd	}tjg |d
t| }ntj| dt| }|jjd | jjkr|tj| jjf}|S t | tj	r
t
| jjtjs
td| S )NrQ   zanon-ASCII characters are present in the FITS file header and have been replaced by "?" charactersreplace)errorsu   �?r   SU)rY   rR   z$string operation on non-string array)rS   bytesdecodeUnicodeDecodeErrorr?   r@   r   rd   rV   rW   rX   rY   rZ   r`   sizerT   arrayr]   r\   r^   r_   r[   r3   )ra   dtrb   r   r   r   decode_ascii  s*    


ro   c                s`   t  dr  S t  dr* jr*tdt  ds8dS t  dr\t fddd	D s\dS d
S )z
    Returns True if the file-like object can be read from.  This is a common-
    sense approximation of io.IOBase.readable.
    readableclosedzI/O operation on closed filereadFmodec             3   s   | ]}| j kV  qd S )N)rs   ).0c)fr   r   	<genexpr>H  s    zisreadable.<locals>.<genexpr>zr+T)r   rp   rq   
ValueErrorany)rv   r   )rv   r   
isreadable8  s    

 rz   c                s`   t  dr  S t  dr* jr*tdt  ds8dS t  dr\t fddd	D s\dS d
S )z
    Returns True if the file-like object can be written to.  This is a common-
    sense approximation of io.IOBase.writable.
    writablerq   zI/O operation on closed filewriteFrs   c             3   s   | ]}| j kV  qd S )N)rs   )rt   ru   )rv   r   r   rw   `  s    ziswritable.<locals>.<genexpr>zwa+T)r   r{   rq   rx   ry   )rv   r   )rv   r   
iswritableP  s    

 r}   c             C   s<   t | tjrdS t| dr$t| jS t| dr8t| jS dS )z
    Returns True if the given object represents an OS-level file (that is,
    ``isinstance(f, file)``).

    On Python 3 this also returns True if the given object is higher level
    wrapper on top of a FileIO object, such as a TextIOWrapper.
    TbufferrawF)rS   ioFileIOr   isfiler~   r   )rv   r   r   r   r   h  s    	



r   c             C   s   t | |ddS )a:  
    A wrapper around the `open()` builtin.

    This exists because `open()` returns an `io.BufferedReader` by default.
    This is bad, because `io.BufferedReader` doesn't support random access,
    which we need in some cases.  We must call open with buffering=0 to get
    a raw random-access file reader.
    r   )	buffering)open)filenamers   r   r   r   fileobj_openz  s    
r   c             C   sh   t | tr| S t | tjr$t| jS t| dr4| jS t| drD| jS t| drXt| j	S tt
| S dS )z
    Returns the 'name' of file-like object f, if it has anything that could be
    called its name.  Otherwise f's class or type is returned.  If f is a
    string f itself is returned.
    namer   r&   N)rS   rT   gzipGzipFilefileobj_namefileobjr   r   r   r&   rZ   )rv   r   r   r   r     s    





r   c             C   sb   t | trdS t| dr| jS t| dr<t| jdr<| jjS t| drZt| jdrZ| jjS dS dS )a  
    Returns True if the given file-like object is closed or if f is a string
    (and assumed to be a pathname).

    Returns False for all other types of objects, under the assumption that
    they are file-like objects with no sense of a 'closed' state.
    Trq   r   fpFN)rS   rT   r   rq   r   r   )rv   r   r   r   fileobj_closed  s    	

r   c             C   sh   t | drt | jdr| j}nBt | dr.| jS t | drLt | jdrL| j}nt | dr\| }ndS t|S )zm
    Returns the 'mode' string of a file-like object if such a thing exists.
    Otherwise returns None.
    r   rs   fileobj_moder   N)r   r   r   r   _fileobj_normalize_mode)rv   r   r   r   r   r     s    


r   c             C   sR   | j }t| tjr2|tjkr dS |tjkr.dS dS d|krN|dd}|d7 }|S )zTakes care of some corner cases in Python where the mode string
    is either oddly formatted or does not truly represent the file mode.
    rbwbN+ )rs   rS   r   r   ZREADZWRITErd   )rv   rs   r   r   r   r     s    

r   c             C   s<   t | dr| jS t| tjr dS t| }|r4d|kS dS dS )z
    Returns True if the give file or file-like object has a file open in binary
    mode.  When in doubt, returns True by default.
    binaryFr
   TN)r   r   rS   r   
TextIOBaser   )rv   rs   r   r   r   fileobj_is_binary  s    
r   c             C   s0   |r&|  }x|D ]}d |t|< qW | |S )N)r$   ord	translate)ra   tableZdeletecharsru   r   r   r   r     s
    
r   c                s0   |  d} fdddfdd|D S )z
    Like :func:`textwrap.wrap` but preserves existing paragraphs which
    :func:`textwrap.wrap` does not otherwise handle well.  Also handles section
    headers.
    z

c                s2   t fdd|  D r| S tj| f S d S )Nc             3   s   | ]}t | k V  qd S )N)len)rt   l)widthr   r   rw     s    z+fill.<locals>.maybe_fill.<locals>.<genexpr>)all
splitlinestextwrapfill)t)r   r   r   r   
maybe_fill  s    zfill.<locals>.maybe_fillc             3   s   | ]} |V  qd S )Nr   )rt   p)r   r   r   rw     s    zfill.<locals>.<genexpr>)splitjoin)textr   r   Z
paragraphsr   )r   r   r   r   r     s    
r   c       	      C   s  t | rtdkr<tjdkr8tt d tdk r8dandatrtd|j }||k rftj	| ||dS tj
||d	}x>td||D ].}t||| }tj	| ||| d|||< qW |S ntj	| ||dS n6t|j| }| |}tj|||d}| }|S dS )
z7Create a numpy array from a file or a file-like object.Ndarwinr   z10.9TFi   @)rY   count)rY   )r   CHUNKED_FROMFILEsysplatformr   Zmac_verintr^   rV   ZfromfileemptyrangeminrY   rr   
frombufferr$   )	ZinfilerY   r   Z
chunk_sizerm   ZbegendZ	read_sizera   r   r   r   _array_from_file*  s*    
 
r   l    ic             C   s   t |rt|tjsdd }nt}tjdkrT| jtd krT| jd dkrTt| j	 }n"tj
drlt| j	 }n
|| |S d}| tj } x,|| jk r|| |||  | ||7 }qW dS )	a  
    Write a numpy array to a file or a file-like object.

    Parameters
    ----------
    arr : `~numpy.ndarray`
        The Numpy array to write.
    outfile : file-like
        A file-like object such as a Python file object, an `io.BytesIO`, or
        anything else with a ``write`` method.  The file object must support
        the buffer interface in its ``write``.

    If writing directly to an on-disk file this delegates directly to
    `ndarray.tofile`.  Otherwise a slower Python implementation is used.
    c             S   s
   |  |S )N)Ztofile)r	   rv   r   r   r   r   f  s    z _array_to_file.<locals>.<lambda>r   r<   i   r   winN)r   rS   r   BufferedIOBase_array_to_file_liker   r   nbytes_OSX_WRITE_LIMITr^   
startswith_WIN_WRITE_LIMITr]   rV   rW   Zflatten)arrZoutfiler|   Z	chunksizeidxr   r   r   _array_to_fileT  s    

r   c             C   s   t | dkrdS | jjrBy|| j W n tk
r<   Y nX dS ttdrtxtj| ddD ]}||	  q\W nn| j
j}tjdkr|dkstjdkr|d	krx@| jD ]}|| 	  qW nx| jD ]}||	  qW dS )
zp
    Write a `~numpy.ndarray` to a file-like object (which is not supported by
    `numpy.ndarray.tofile`).
    r   NnditerC)orderlittle>Zbig<)r   flags
contiguousr|   r   r3   r   rV   r   ZtostringrY   	byteorderr   ZflatZbyteswap)r   r   itemr   r   r   r   r     s$    
r   c             C   sD   t | }|r t|tr t|}n|s6t| ts6t|}| | dS )z
    Write a string to a file, encoding to ASCII if the file is open in binary
    mode, or decoding if the file is open in text mode.
    N)r   rS   rT   rc   ro   r|   )rv   ra   Zbinmoder   r   r   _write_string  s    
r   c             C   sR   | j |kr| S | j j|jkrDt| j tjr:t|tjsD| |S | |S dS )z
    Converts an array to a new dtype--if the itemsize of the new dtype is
    the same as the old dtype and both types are not numeric, a view is
    returned.  Otherwise a new array must be created.
    N)rY   r^   rV   Z
issubdtypeZnumberr]   r_   )rm   rY   r   r   r   _convert_array  s    

r   c             C   s    | j dkstd| jd d > S )zg
    Given a numpy dtype, finds its "zero" point, which is exactly in the
    middle of its range.
    ur<      )kindAssertionErrorr^   )rY   r   r   r   _unsigned_zero  s    r   c             C   s   | j dko| jdkS )Nr      )r   r^   )rY   r   r   r   _is_pseudo_unsigned  s    r   c             C   s
   t | tS )N)rS   all_integer_types)valr   r   r   _is_int  s    r   c             C   s.   yt | }W n tk
r(   t| }Y nX |S )zAConverts a given string to either an int or a float if necessary.)r   rx   float)r   Znumr   r   r   _str_to_num  s
    r   c          	   C   s   g }|  d}t|t| | d }tj| d dtdfd}t|dkd }d}d}xt|D ]}	y:t||| kd d }
||
d  d }|
dkrd}W n t	k
r   t| }Y nX ||kr|| }|
| ||  t| |krP |}qdW |S )z
    Split a long string into parts where each part is no longer
    than ``strlen`` and no word is cut into two pieces.  But if
    there is one single word which is longer than ``strlen``, then
    it will be split in the middle of the word.
     r<   utf8)rY       r   )r   maxr   rV   r   rU   ri   Znonzeror   	Exceptionappend)inputZstrlenZwordsZnblanksZnmaxr   Z	blank_locoffsetZxoffsetr   Zlocr   r   r   _words_group  s,    
r   c             C   s2   | dk	rt j| } tj| d\}}t | |S )z
    Create a temporary file name which should not already exist.  Use the
    directory of the input file as the base name of the mkstemp() output.
    N)dir)ospathdirnametempfileZmkstempclose)r   rv   fnr   r   r   	_tmp_name  s
    
r   c             C   sL   t | tjr| S | }x2t|drF|jdk	rFt |jtjr>|jS |j}qW dS )zu
    If the array has an mmap.mmap at base of its base chain, return the mmap
    object; otherwise return None.
    baseN)rS   mmapr   r   )rm   r   r   r   r   _get_array_mmap(  s    r   c          
   c   s   y
d V  W n t k
r } zd}t| ts0| g} |d krHtj| jj}tj|rt	
|}tdd | D }||k rd||}x| D ]}|  qW t |t| W d d }~X Y nX d S )Nr   c             s   s   | ]}|j V  qd S )N)rl   )rt   hdur   r   r   rw   D  s    z$_free_space_check.<locals>.<genexpr>z6Not enough space on disk: requested {}, available {}. )OSErrorrS   listr   r   r   Z_filer   isdirr   Zget_free_space_in_dirsumr   Z_closerT   )Zhdulistr   excZerror_messageZ
free_spaceZhdulist_sizer   r   r   r   _free_space_check8  s"    



r   c          	   C   s*   yt t| S  ttfk
r$   |S X dS )z
    Attempts to extract an integer number from the given value. If the
    extraction fails, the value of the 'default' argument is returned.
    N)r   r   r3   rx   )valuedefaultr   r   r   _extract_numberO  s    r   c             C   s   t d| dS )a8  
    Return a string representing the path to the file requested from the
    io.fits test data set.

    .. versionadded:: 2.0.3

    Parameters
    ----------
    filename : str
        The filename of the test data file.

    Returns
    -------
    filepath : str
        The path to the requested file.
    zio/fits/tests/data/{}Zastropy)r   Zget_pkg_data_filenamer   )r   r   r   r   get_testdata_filepath]  s    r   c       
      C   s$  | j }|jdkrtd|jdkr&dnd}d|j| |j|}| |tj}t	 }|j
dkryd|jd f|_W n tk
r   Y nX xtd	|jd	 |D ]~}||||  }tj|jd
d td}xPtd|jd  dD ]8}	||d|	f dkM }d	|d|	f |< |d|	f d	k}qW qW | S )z
    Performs an in-place rstrip operation on string arrays. This is necessary
    since the built-in `np.char.rstrip` in Numpy does not perform an in-place
    calculation.
    ZSUz/This function can only be used on string arraysrg   r<   rR   z
{0}{1}u{2}r   r   r   N)rY   .    )rY   r   r3   r   r^   r   r]   rV   rW   Z
getbufsizendimshaper"   r   Zonesbool)
rm   rn   ZbpcZdt_intr
   bufsizejru   maskir   r   r   _rstrip_inplacer  s(    

r   )N)N)Cr   rL   r   r   r5   r   r   rF   r   r   r   rE   r?   r   
contextlibr   r   Zastropy.utilsr   Zdistutils.versionr   ZnumpyrV   r   Zastropy.utils.exceptionsr   Zcmpr   Zintegerr   r   r/   r8   rK   rP   rc   ro   rz   r}   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   sv   
u
%.$!&3+
'