B
    d]                @   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m	Z	m
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 d dlmZmZ d d	lmZmZ d d
lmZ ddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) d dl*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0 eddd Z1ddddddddddddddddgZ2ej3ej4ddZ4G d d! d!Z5d"d# Z6G d$d% d%eZ7eddPd)dZ8dQd*d+Z9e4e9dRd,dZ:d-d. Z;e4e;d/d Z<d0d1 Z=e4e=d2d Z>dSd3d4Z?d5d6 Z@d7ZAdTdd8d9d:ZBeedeCd;ddd dd&d d<df
dd8d=dZDe4eBeDZEdUd>d?ZFe4eFdVdEdZGeddWdFdZHdXdd8dGdHZIeedeCd;dd d dddddddCJeKe jLdId&d'dJdd&d'd'dd<fdd8dKdZMe4eIeMZNdLd ZOdMd ZPdNd ZQdOd ZRdS )Y    N)
itemgetterindex)Mapping   )format)
DataSource)	overrides)packbits
unpackbits)set_array_function_like_doc
set_module)	recursive)LineSplitterNameValidatorStringConverterConverterErrorConverterLockErrorConversionWarning_is_string_likehas_nested_fieldsflatten_dtype
easy_dtype_decode_line)asbytesasstr	asunicode	os_fspathos_PathLikepicklenumpyc              O   s   t jdtdd tj| |S )Nz0np.loads is deprecated, use pickle.loads instead   )
stacklevel)warningswarnDeprecationWarningr   loads)argskwargs r(   \/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/numpy/lib/npyio.pyr%      s    
r%   savetxtloadtxt
genfromtxt	ndfromtxt	mafromtxt
recfromtxt
recfromcsvloadsavesavezsavez_compressedr	   r
   	fromregexr   )modulec               @   s(   e Zd ZdZdd Zdd Zdd ZdS )	BagObjam  
    BagObj(obj)

    Convert attribute look-ups to getitems on the object passed in.

    Parameters
    ----------
    obj : class instance
        Object on which attribute look-up is performed.

    Examples
    --------
    >>> from numpy.lib.npyio import BagObj as BO
    >>> class BagDemo:
    ...     def __getitem__(self, key): # An instance of BagObj(BagDemo)
    ...                                 # will call this method when any
    ...                                 # attribute look-up is required
    ...         result = "Doesn't matter what you want, "
    ...         return result + "you're gonna get this"
    ...
    >>> demo_obj = BagDemo()
    >>> bagobj = BO(demo_obj)
    >>> bagobj.hello_there
    "Doesn't matter what you want, you're gonna get this"
    >>> bagobj.I_can_be_anything
    "Doesn't matter what you want, you're gonna get this"

    c             C   s   t || _d S )N)weakrefproxy_obj)selfobjr(   r(   r)   __init__Q   s    zBagObj.__init__c             C   s4   yt | d| S  tk
r.   t|d Y nX d S )Nr:   )object__getattribute__KeyErrorAttributeError)r;   keyr(   r(   r)   r?   U   s    zBagObj.__getattribute__c             C   s   t t| d S )z
        Enables dir(bagobj) to list the files in an NpzFile.

        This also enables tab-completion in an interpreter or IPython.
        r:   )listr>   r?   keys)r;   r(   r(   r)   __dir__[   s    zBagObj.__dir__N)__name__
__module____qualname____doc__r=   r?   rE   r(   r(   r(   r)   r7   3   s   r7   c             O   s4   t | dst| } ddl}d|d< |j| f||S )z
    Create a ZipFile.

    Allows for Zip64, and the `file` argument can accept file, str, or
    pathlib.Path objects. `args` and `kwargs` are passed to the zipfile.ZipFile
    constructor.
    readr   NT
allowZip64)hasattrr   zipfileZipFile)filer&   r'   rM   r(   r(   r)   zipfile_factoryd   s
    
rP   c               @   sj   e Zd ZdZdZdZd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S )NpzFilear  
    NpzFile(fid)

    A dictionary-like object with lazy-loading of files in the zipped
    archive provided on construction.

    `NpzFile` is used to load files in the NumPy ``.npz`` data archive
    format. It assumes that files in the archive have a ``.npy`` extension,
    other files are ignored.

    The arrays and file strings are lazily loaded on either
    getitem access using ``obj['key']`` or attribute lookup using
    ``obj.f.key``. A list of all files (without ``.npy`` extensions) can
    be obtained with ``obj.files`` and the ZipFile object itself using
    ``obj.zip``.

    Attributes
    ----------
    files : list of str
        List of all files in the archive with a ``.npy`` extension.
    zip : ZipFile instance
        The ZipFile object initialized with the zipped archive.
    f : BagObj instance
        An object on which attribute can be performed as an alternative
        to getitem access on the `NpzFile` instance itself.
    allow_pickle : bool, optional
        Allow loading pickled data. Default: False

        .. versionchanged:: 1.16.3
            Made default False in response to CVE-2019-6446.

    pickle_kwargs : dict, optional
        Additional keyword arguments to pass on to pickle.load.
        These are only useful when loading object arrays saved on
        Python 2 when using Python 3.

    Parameters
    ----------
    fid : file or str
        The zipped archive to open. This is either a file-like object
        or a string containing the path to the archive.
    own_fid : bool, optional
        Whether NpzFile should close the file handle.
        Requires that `fid` is a file-like object.

    Examples
    --------
    >>> from tempfile import TemporaryFile
    >>> outfile = TemporaryFile()
    >>> x = np.arange(10)
    >>> y = np.sin(x)
    >>> np.savez(outfile, x=x, y=y)
    >>> _ = outfile.seek(0)

    >>> npz = np.load(outfile)
    >>> isinstance(npz, np.lib.io.NpzFile)
    True
    >>> sorted(npz.files)
    ['x', 'y']
    >>> npz['x']  # getitem access
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    >>> npz.f.x  # attribute lookup
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

    NFc             C   s~   t |}| | _g | _|| _|| _x:| jD ]0}|drP| j|d d  q,| j| q,W || _t	| | _
|rz|| _d S )Nz.npy)rP   namelist_filesfilesallow_picklepickle_kwargsendswithappendzipr7   ffid)r;   r\   own_fidrV   rW   Z_zipxr(   r(   r)   r=      s    


zNpzFile.__init__c             C   s   | S )Nr(   )r;   r(   r(   r)   	__enter__   s    zNpzFile.__enter__c             C   s   |    d S )N)close)r;   exc_type	exc_value	tracebackr(   r(   r)   __exit__   s    zNpzFile.__exit__c             C   s>   | j dk	r| j   d| _ | jdk	r4| j  d| _d| _dS )z"
        Close the file.

        N)rZ   r`   r\   r[   )r;   r(   r(   r)   r`      s    



zNpzFile.closec             C   s   |    d S )N)r`   )r;   r(   r(   r)   __del__   s    zNpzFile.__del__c             C   s
   t | jS )N)iterrU   )r;   r(   r(   r)   __iter__   s    zNpzFile.__iter__c             C   s
   t | jS )N)lenrU   )r;   r(   r(   r)   __len__   s    zNpzFile.__len__c             C   s   d}|| j krd}n|| jkr*d}|d7 }|r| j|}|ttj}|  |tjkr|| j|}tj	|| j
| jdS | j|S ntd| d S )NFTz.npy)rV   rW   z%s is not a file in the archive)rT   rU   rZ   openrJ   rh   r   MAGIC_PREFIXr`   
read_arrayrV   rW   r@   )r;   rB   memberbytesmagicr(   r(   r)   __getitem__   s"    	



zNpzFile.__getitem__c             C   s   t jdtdd |  S )NziNpzFile.iteritems is deprecated in python 3, to match the removal of dict.itertems. Use .items() instead.r    )r!   )r"   r#   r$   items)r;   r(   r(   r)   	iteritems  s    
zNpzFile.iteritemsc             C   s   t jdtdd |  S )NzgNpzFile.iterkeys is deprecated in python 3, to match the removal of dict.iterkeys. Use .keys() instead.r    )r!   )r"   r#   r$   rD   )r;   r(   r(   r)   iterkeys  s    
zNpzFile.iterkeys)FFN)rF   rG   rH   rI   rZ   r\   r=   r_   rd   r`   re   rg   ri   rp   rr   rs   r(   r(   r(   r)   rQ   s   s   A 
"rQ   FTASCIIc             C   sF  |dkrt dt||d}t }t| dr<| }d}n|tt| d}d}d}	d	}
tt	j
}||}|t|t| d
 ||	s||
r|  t||||d}|S |t	j
kr|rt	j| |dS t	j|||dS nR|st dytj|f|S  tk
r6 } ztdt|  |W dd}~X Y nX W dQ R X dS )a  
    Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files.

    .. warning:: Loading files that contain object arrays uses the ``pickle``
                 module, which is not secure against erroneous or maliciously
                 constructed data. Consider passing ``allow_pickle=False`` to
                 load data that is known not to contain object arrays for the
                 safer handling of untrusted sources.

    Parameters
    ----------
    file : file-like object, string, or pathlib.Path
        The file to read. File-like objects must support the
        ``seek()`` and ``read()`` methods. Pickled files require that the
        file-like object support the ``readline()`` method as well.
    mmap_mode : {None, 'r+', 'r', 'w+', 'c'}, optional
        If not None, then memory-map the file, using the given mode (see
        `numpy.memmap` for a detailed description of the modes).  A
        memory-mapped array is kept on disk. However, it can be accessed
        and sliced like any ndarray.  Memory mapping is especially useful
        for accessing small fragments of large files without reading the
        entire file into memory.
    allow_pickle : bool, optional
        Allow loading pickled object arrays stored in npy files. Reasons for
        disallowing pickles include security, as loading pickled data can
        execute arbitrary code. If pickles are disallowed, loading object
        arrays will fail. Default: False

        .. versionchanged:: 1.16.3
            Made default False in response to CVE-2019-6446.

    fix_imports : bool, optional
        Only useful when loading Python 2 generated pickled files on Python 3,
        which includes npy/npz files containing object arrays. If `fix_imports`
        is True, pickle will try to map the old Python 2 names to the new names
        used in Python 3.
    encoding : str, optional
        What encoding to use when reading Python 2 strings. Only useful when
        loading Python 2 generated pickled files in Python 3, which includes
        npy/npz files containing object arrays. Values other than 'latin1',
        'ASCII', and 'bytes' are not allowed, as they can corrupt numerical
        data. Default: 'ASCII'

    Returns
    -------
    result : array, tuple, dict, etc.
        Data stored in the file. For ``.npz`` files, the returned instance
        of NpzFile class must be closed to avoid leaking file descriptors.

    Raises
    ------
    IOError
        If the input file does not exist or cannot be read.
    ValueError
        The file contains an object array, but allow_pickle=False given.

    See Also
    --------
    save, savez, savez_compressed, loadtxt
    memmap : Create a memory-map to an array stored in a file on disk.
    lib.format.open_memmap : Create or load a memory-mapped ``.npy`` file.

    Notes
    -----
    - If the file contains pickle data, then whatever object is stored
      in the pickle is returned.
    - If the file is a ``.npy`` file, then a single array is returned.
    - If the file is a ``.npz`` file, then a dictionary-like object is
      returned, containing ``{filename: array}`` key-value pairs, one for
      each file in the archive.
    - If the file is a ``.npz`` file, the returned value supports the
      context manager protocol in a similar fashion to the open function::

        with load('foo.npz') as data:
            a = data['a']

      The underlying file descriptor is closed when exiting the 'with'
      block.

    Examples
    --------
    Store data to disk, and load it again:

    >>> np.save('/tmp/123', np.array([[1, 2, 3], [4, 5, 6]]))
    >>> np.load('/tmp/123.npy')
    array([[1, 2, 3],
           [4, 5, 6]])

    Store compressed data to disk, and load it again:

    >>> a=np.array([[1, 2, 3], [4, 5, 6]])
    >>> b=np.array([1, 2])
    >>> np.savez('/tmp/123.npz', a=a, b=b)
    >>> data = np.load('/tmp/123.npz')
    >>> data['a']
    array([[1, 2, 3],
           [4, 5, 6]])
    >>> data['b']
    array([1, 2])
    >>> data.close()

    Mem-map the stored array, and then access the second row
    directly from disk:

    >>> X = np.load('/tmp/123.npy', mmap_mode='r')
    >>> X[1, :]
    memmap([4, 5, 6])

    )rt   latin1rn   z.encoding must be 'ASCII', 'latin1', or 'bytes')encodingfix_importsrJ   FrbTs   PKs   PKr   )r]   rV   rW   )mode)rV   rW   z@Cannot load file containing pickled data when allow_pickle=Falsez'Failed to interpret file %s as a pickleN)
ValueErrordict
contextlib	ExitStackrL   enter_contextrj   r   rh   r   rk   rJ   seekmin
startswithpop_allrQ   Zopen_memmaprl   r   r1   	ExceptionIOErrorrepr)rO   Z	mmap_moderV   rw   rv   rW   stackr\   r]   Z_ZIP_PREFIXZ_ZIP_SUFFIXNro   reter(   r(   r)   r1     s>    p




c             C   s   |fS )Nr(   )rO   arrrV   rw   r(   r(   r)   _save_dispatcher  s    r   c          	   C   sp   t | drt| }n$t| } | ds0| d } t| d}|(}t|}tj	|||t
|dd W dQ R X dS )a<  
    Save an array to a binary file in NumPy ``.npy`` format.

    Parameters
    ----------
    file : file, str, or pathlib.Path
        File or filename to which the data is saved.  If file is a file-object,
        then the filename is unchanged.  If file is a string or Path, a ``.npy``
        extension will be appended to the filename if it does not already
        have one.
    arr : array_like
        Array data to be saved.
    allow_pickle : bool, optional
        Allow saving object arrays using Python pickles. Reasons for disallowing
        pickles include security (loading pickled data can execute arbitrary
        code) and portability (pickled objects may not be loadable on different
        Python installations, for example if the stored objects require libraries
        that are not available, and not all pickled data is compatible between
        Python 2 and Python 3).
        Default: True
    fix_imports : bool, optional
        Only useful in forcing objects in object arrays on Python 3 to be
        pickled in a Python 2 compatible way. If `fix_imports` is True, pickle
        will try to map the new Python 3 names to the old module names used in
        Python 2, so that the pickle data stream is readable with Python 2.

    See Also
    --------
    savez : Save several arrays into a ``.npz`` archive
    savetxt, load

    Notes
    -----
    For a description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.

    Any data saved to the file is appended to the end of the file.

    Examples
    --------
    >>> from tempfile import TemporaryFile
    >>> outfile = TemporaryFile()

    >>> x = np.arange(10)
    >>> np.save(outfile, x)

    >>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file
    >>> np.load(outfile)
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])


    >>> with open('test.npy', 'wb') as f:
    ...     np.save(f, np.array([1, 2]))
    ...     np.save(f, np.array([1, 3]))
    >>> with open('test.npy', 'rb') as f:
    ...     a = np.load(f)
    ...     b = np.load(f)
    >>> print(a, b)
    # [1 2] [1 3]
    writez.npywb)rw   )rV   rW   N)rL   r|   nullcontextr   rX   rj   np
asanyarrayr   write_arrayr{   )rO   r   rV   rw   Zfile_ctxr\   r(   r(   r)   r2     s    =




c             o   s   |E d H  |  E d H  d S )N)values)rO   r&   kwdsr(   r(   r)   _savez_dispatcher  s    
r   c             O   s   t | ||d dS )a  Save several arrays into a single file in uncompressed ``.npz`` format.

    Provide arrays as keyword arguments to store them under the
    corresponding name in the output file: ``savez(fn, x=x, y=y)``.

    If arrays are specified as positional arguments, i.e., ``savez(fn,
    x, y)``, their names will be `arr_0`, `arr_1`, etc.

    Parameters
    ----------
    file : str or file
        Either the filename (string) or an open file (file-like object)
        where the data will be saved. If file is a string or a Path, the
        ``.npz`` extension will be appended to the filename if it is not
        already there.
    args : Arguments, optional
        Arrays to save to the file. Please use keyword arguments (see
        `kwds` below) to assign names to arrays.  Arrays specified as
        args will be named "arr_0", "arr_1", and so on.
    kwds : Keyword arguments, optional
        Arrays to save to the file. Each array will be saved to the
        output file with its corresponding keyword name.

    Returns
    -------
    None

    See Also
    --------
    save : Save a single array to a binary file in NumPy format.
    savetxt : Save an array to a file as plain text.
    savez_compressed : Save several arrays into a compressed ``.npz`` archive

    Notes
    -----
    The ``.npz`` file format is a zipped archive of files named after the
    variables they contain.  The archive is not compressed and each file
    in the archive contains one variable in ``.npy`` format. For a
    description of the ``.npy`` format, see :py:mod:`numpy.lib.format`.

    When opening the saved ``.npz`` file with `load` a `NpzFile` object is
    returned. This is a dictionary-like object which can be queried for
    its list of arrays (with the ``.files`` attribute), and for the arrays
    themselves.

    When saving dictionaries, the dictionary keys become filenames
    inside the ZIP archive. Therefore, keys should be valid filenames.
    E.g., avoid keys that begin with ``/`` or contain ``.``.

    Examples
    --------
    >>> from tempfile import TemporaryFile
    >>> outfile = TemporaryFile()
    >>> x = np.arange(10)
    >>> y = np.sin(x)

    Using `savez` with \*args, the arrays are saved with default names.

    >>> np.savez(outfile, x, y)
    >>> _ = outfile.seek(0) # Only needed here to simulate closing & reopening file
    >>> npzfile = np.load(outfile)
    >>> npzfile.files
    ['arr_0', 'arr_1']
    >>> npzfile['arr_0']
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

    Using `savez` with \**kwds, the arrays are saved with the keyword names.

    >>> outfile = TemporaryFile()
    >>> np.savez(outfile, x=x, y=y)
    >>> _ = outfile.seek(0)
    >>> npzfile = np.load(outfile)
    >>> sorted(npzfile.files)
    ['x', 'y']
    >>> npzfile['x']
    array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

    FN)_savez)rO   r&   r   r(   r(   r)   r3     s    Pc             o   s   |E d H  |  E d H  d S )N)r   )rO   r&   r   r(   r(   r)   _savez_compressed_dispatcherm  s    
r   c             O   s   t | ||d dS )a  
    Save several arrays into a single file in compressed ``.npz`` format.

    Provide arrays as keyword arguments to store them under the
    corresponding name in the output file: ``savez(fn, x=x, y=y)``.

    If arrays are specified as positional arguments, i.e., ``savez(fn,
    x, y)``, their names will be `arr_0`, `arr_1`, etc.

    Parameters
    ----------
    file : str or file
        Either the filename (string) or an open file (file-like object)
        where the data will be saved. If file is a string or a Path, the
        ``.npz`` extension will be appended to the filename if it is not
        already there.
    args : Arguments, optional
        Arrays to save to the file. Please use keyword arguments (see
        `kwds` below) to assign names to arrays.  Arrays specified as
        args will be named "arr_0", "arr_1", and so on.
    kwds : Keyword arguments, optional
        Arrays to save to the file. Each array will be saved to the
        output file with its corresponding keyword name.

    Returns
    -------
    None

    See Also
    --------
    numpy.save : Save a single array to a binary file in NumPy format.
    numpy.savetxt : Save an array to a file as plain text.
    numpy.savez : Save several arrays into an uncompressed ``.npz`` file format
    numpy.load : Load the files created by savez_compressed.

    Notes
    -----
    The ``.npz`` file format is a zipped archive of files named after the
    variables they contain.  The archive is compressed with
    ``zipfile.ZIP_DEFLATED`` and each file in the archive contains one variable
    in ``.npy`` format. For a description of the ``.npy`` format, see
    :py:mod:`numpy.lib.format`.


    When opening the saved ``.npz`` file with `load` a `NpzFile` object is
    returned. This is a dictionary-like object which can be queried for
    its list of arrays (with the ``.files`` attribute), and for the arrays
    themselves.

    Examples
    --------
    >>> test_array = np.random.rand(3, 2)
    >>> test_vector = np.random.rand(4)
    >>> np.savez_compressed('/tmp/123', a=test_array, b=test_vector)
    >>> loaded = np.load('/tmp/123.npz')
    >>> print(np.array_equal(test_array, loaded['a']))
    True
    >>> print(np.array_equal(test_vector, loaded['b']))
    True

    TN)r   )rO   r&   r   r(   r(   r)   r4   r  s    ?c          
   C   s   dd l }t| ds,t| } | ds,| d } |}x<t|D ]0\}}	d| }
|
| krbtd|
 |	||
< q:W |rz|j}n|j}t	| d|d}xT|
 D ]H\}
}	|
d }t|	}	|j|dd	d
}tj||	||d W d Q R X qW |  d S )Nr   r   z.npzzarr_%dz,Cannot use un-named variables and keyword %sw)ry   compressionz.npyT)force_zip64)rV   rW   )rM   rL   r   rX   	enumeraterD   rz   ZIP_DEFLATED
ZIP_STOREDrP   rq   r   r   rj   r   r   r`   )rO   r&   r   compressrV   rW   rM   ZnamedictivalrB   r   Zzipffnamer\   r(   r(   r)   r     s0    



r   c             C   s   dd }| j }t|tjr"dd S t|tjr4tjS t|tjrFtjS t|tjrZdd S t|tjrltjS t|tjr||S t|t	rdd S t|tj
rtS t|tjrtS tS dS )z; Find the correct dtype converter. Adapted from matplotlib c             S   s"   |    d| krt| S t| S )N0x)lowerfloatfromhex)r^   r(   r(   r)   	floatconv  s    
z_getconv.<locals>.floatconvc             S   s   t t| S )N)boolint)r^   r(   r(   r)   <lambda>      z_getconv.<locals>.<lambda>c             S   s   t t| S )N)r   r   )r^   r(   r(   r)   r     r   c             S   s   t t| ddS )Nz+--)complexr   replace)r^   r(   r(   r)   r     r   N)type
issubclassr   Zbool_Zuint64Zint64integerZ
longdoubleZfloatingr   bytes_r   unicode_r   r   )dtyper   typr(   r(   r)   _getconv  s*    
r   iP  )likec            C   s   |fS )Nr(   )r   r   comments	delimiter
convertersskiprowsusecolsunpackndminrv   max_rowsr   r(   r(   r)   _loadtxt_dispatcher  s    r   #rn   c               s  |dk	r(t | |||
|dS tdd }tdd fdd 	
f
d	d
}|dkrtd| dk	rtttfrgdd D dd D tddk	rt	}d}dkrdd}dk	ryt
}W n tk
r&   g}Y nX xR|D ]J}yt| W n6 tk
rt } zdt| f|_ W dd}~X Y nX q.W |t|}t|||\}d}ydt| trt| } t| rtjjj| ddtddtd}nt| t| ddW n. tk
r4 } ztd|W dd}~X Y nX dk	rFndkr`ddl}| zxtD ]}t qnW d}y"x|st		}qW W n0 tk
r   d	g }tj d|  dd Y nX t!p| t!|d krd!d |D n*fd"dt D  d kr. t"fgxv|p8i # D ]d\}}rvy$|}W n tk
rt   w>Y nX |rd#d$ }t%j&||d%|< n||< q>W fd&dD dxn|t'D ]b}dkrt(||nDt
j)}|d }|d  t!|7  < j*|dd' ||dd(f< qW W d|r>+  X dkrVt(g |j,d)kr|j)dd d*kr|d+_)j,|krt-j,|k r|d krt.n|dkrt/j0|rt!|d krfd,d|j1D S j0S nS dS )-a  
    Load data from a text file.

    Each row in the text file must have the same number of values.

    Parameters
    ----------
    fname : file, str, or pathlib.Path
        File, filename, or generator to read.  If the filename extension is
        ``.gz`` or ``.bz2``, the file is first decompressed. Note that
        generators should return byte strings.
    dtype : data-type, optional
        Data-type of the resulting array; default: float.  If this is a
        structured data-type, the resulting array will be 1-dimensional, and
        each row will be interpreted as an element of the array.  In this
        case, the number of columns used must match the number of fields in
        the data-type.
    comments : str or sequence of str, optional
        The characters or list of characters used to indicate the start of a
        comment. None implies no comments. For backwards compatibility, byte
        strings will be decoded as 'latin1'. The default is '#'.
    delimiter : str, optional
        The string used to separate values. For backwards compatibility, byte
        strings will be decoded as 'latin1'. The default is whitespace.
    converters : dict, optional
        A dictionary mapping column number to a function that will parse the
        column string into the desired value.  E.g., if column 0 is a date
        string: ``converters = {0: datestr2num}``.  Converters can also be
        used to provide a default value for missing data (but see also
        `genfromtxt`): ``converters = {3: lambda s: float(s.strip() or 0)}``.
        Default: None.
    skiprows : int, optional
        Skip the first `skiprows` lines, including comments; default: 0.
    usecols : int or sequence, optional
        Which columns to read, with 0 being the first. For example,
        ``usecols = (1,4,5)`` will extract the 2nd, 5th and 6th columns.
        The default, None, results in all columns being read.

        .. versionchanged:: 1.11.0
            When a single column has to be read it is possible to use
            an integer instead of a tuple. E.g ``usecols = 3`` reads the
            fourth column the same way as ``usecols = (3,)`` would.
    unpack : bool, optional
        If True, the returned array is transposed, so that arguments may be
        unpacked using ``x, y, z = loadtxt(...)``.  When used with a
        structured data-type, arrays are returned for each field.
        Default is False.
    ndmin : int, optional
        The returned array will have at least `ndmin` dimensions.
        Otherwise mono-dimensional axes will be squeezed.
        Legal values: 0 (default), 1 or 2.

        .. versionadded:: 1.6.0
    encoding : str, optional
        Encoding used to decode the inputfile. Does not apply to input streams.
        The special value 'bytes' enables backward compatibility workarounds
        that ensures you receive byte arrays as results if possible and passes
        'latin1' encoded strings to converters. Override this value to receive
        unicode arrays and pass strings as input to converters.  If set to None
        the system default is used. The default value is 'bytes'.

        .. versionadded:: 1.14.0
    max_rows : int, optional
        Read `max_rows` lines of content after `skiprows` lines. The default
        is to read all the lines.

        .. versionadded:: 1.16.0
    ${ARRAY_FUNCTION_LIKE}

        .. versionadded:: 1.20.0

    Returns
    -------
    out : ndarray
        Data read from the text file.

    See Also
    --------
    load, fromstring, fromregex
    genfromtxt : Load data with missing values handled as specified.
    scipy.io.loadmat : reads MATLAB data files

    Notes
    -----
    This function aims to be a fast reader for simply formatted files.  The
    `genfromtxt` function provides more sophisticated handling of, e.g.,
    lines with missing values.

    .. versionadded:: 1.10.0

    The strings produced by the Python float.hex method can be used as
    input for floats.

    Examples
    --------
    >>> from io import StringIO   # StringIO behaves like a file object
    >>> c = StringIO("0 1\n2 3")
    >>> np.loadtxt(c)
    array([[0., 1.],
           [2., 3.]])

    >>> d = StringIO("M 21 72\nF 35 58")
    >>> np.loadtxt(d, dtype={'names': ('gender', 'age', 'weight'),
    ...                      'formats': ('S1', 'i4', 'f4')})
    array([(b'M', 21, 72.), (b'F', 35, 58.)],
          dtype=[('gender', 'S1'), ('age', '<i4'), ('weight', '<f4')])

    >>> c = StringIO("1,0,2\n3,0,4")
    >>> x, y = np.loadtxt(c, delimiter=',', usecols=(0, 2), unpack=True)
    >>> x
    array([1., 3.])
    >>> y
    array([2., 4.])

    This example shows how `converters` can be used to convert a field
    with a trailing minus sign into a negative number.

    >>> s = StringIO('10.01 31.25-\n19.22 64.31\n17.57- 63.94')
    >>> def conv(fld):
    ...     return -float(fld[:-1]) if fld.endswith(b'-') else float(fld)
    ...
    >>> np.loadtxt(s, converters={0: conv, 1: conv})
    array([[ 10.01, -31.25],
           [ 19.22,  64.31],
           [-17.57,  63.94]])
    N)r   r   r   r   r   r   r   r   rv   r   r   c             S   s  |j dkr|j}t|dkr(|jgdfS |d tfg}t|dkrvx2|jddd D ]}||d d  || fg}qTW |jgtt|j |fS nlg }g }xZ|j D ]P}|j| \}}| |\}	}
|	|	 |j
dkr|	|
 q|t|	|
f qW ||fS dS )z;Unpack a structured data-type, and produce re-packing info.Nr   r   )namesshaperh   baserC   r   r   prodfieldsextendndimrY   )r;   dtr   packingdimtypesfieldtprn   Zflat_dtZflat_packingr(   r(   r)   flatten_dtype_internal  s&    


z'loadtxt.<locals>.flatten_dtype_internalc             S   sz   |dkr|d S |t kr t |S |tkr0t|S d}g }x4|D ],\}}|| ||||  | ||7 }q>W t |S dS )z6Pack items into nested lists based on re-packing info.Nr   )tuplerC   rY   )r;   rq   r   startr   lengthZ
subpackingr(   r(   r)   
pack_items  s    zloadtxt.<locals>.pack_itemsc                sB   t | d}  dk	r&j| ddd } | d} | r>| S g S )z2Chop off comments, strip, and split at delimiter. )rv   Nr   )maxsplitr   z
)r   splitstrip)line)r   r   rv   regex_commentsr(   r)   
split_line  s
    
zloadtxt.<locals>.split_linec             3   s   g }t g}t |}xt|D ]\}}	| t dkrFq(
r\ fdd
D  t kr| d }td| dd t D }|}|| t|| kr(|V  g }q(W |r|V  dS )a  Parse each line, including the first.

        The file read, `fh`, is a global defined above.

        Parameters
        ----------
        chunk_size : int
            At most `chunk_size` lines are read at a time, with iteration
            until all lines are read.

        r   c                s   g | ]} | qS r(   r(   ).0j)valsr(   r)   
<listcomp>  s    z.loadtxt.<locals>.read_data.<locals>.<listcomp>r   z"Wrong number of columns at line %dc             S   s   g | ]\}}||qS r(   r(   )r   convr   r(   r(   r)   r     s    N)	itertoolschainislicer   rh   rz   rZ   rY   )
chunk_sizeXZ	line_iterr   r   line_numrq   )
r   r   fh
first_liner   r   r   r   r   r   )r   r)   	read_data  s*    

zloadtxt.<locals>.read_data)r   r   r    z"Illegal value of ndmin keyword: %sc             S   s   g | ]}t |qS r(   )r   )r   r^   r(   r(   r)   r     s    zloadtxt.<locals>.<listcomp>c             s   s   | ]}t |V  qd S )N)reescape)r   commentr(   r(   r)   	<genexpr>   s    zloadtxt.<locals>.<genexpr>|Frn   Tz\usecols must be an int or a sequence of ints but it contains at least one element of type %srt)rv   rv   ru   z1fname must be a string, file handle, or generatorr    zloadtxt: Empty input file: "%s"r    )r!   r   c             S   s   g | ]}t |qS r(   )r   )r   r   r(   r(   r)   r   Y  s    c                s   g | ]} qS r(   r(   )r   r   )defconvr(   r)   r   \  s    c             S   s"   t | tkr|| S || dS )Nru   )r   rn   encode)r^   r   r(   r(   r)   tobytes_firstl  s    zloadtxt.<locals>.tobytes_first)r   c                s$   g | ]}|t k	r|n
 fd dqS )c                s
   |   S )N)r   )r^   )	fencodingr(   r)   r   u  r   z$loadtxt.<locals>.<listcomp>.<lambda>)rn   )r   r   )r   r(   r)   r   t  s   )Zrefcheck.   )r   r   )r   r   c                s   g | ]} | qS r(   r(   )r   r   )r   r(   r)   r     s    )2_loadtxt_with_liker   rz   
isinstancestrrn   r   compilejoinr   rC   	TypeErroropindexr   r&   r   r   r   r   r   r   lib_datasourcerj   getattrrf   localegetpreferredencodingrangenextStopIterationr"   r#   rh   r   rq   r   	functoolspartial_loadtxt_chunksizearrayr   resizer`   r   squeezeZ
atleast_1d
atleast_2dTr   )r   r   r   r   r   r   r   r   r   rv   r   r   r   r   user_convertersbyte_convertersZusecols_as_listZcol_idxr   Zdtype_typesZfownr   r   Z
first_valsr   r   r^   Znshapeposr(   )r   r   r   r   r   r   rv   r   r   r   r   r   r   r   r   r   r   r)   r+     s     
	+














 


c	       	      C   s   |fS )Nr(   )	r   r   fmtr   newlineheaderfooterr   rv   r(   r(   r)   _savetxt_dispatcher  s    r  %.18e 
r   # c	             C   s<  t |trt|}t|}G dd d}	d}
t | tr>t| } t| rnt| d  tj	j
j| d|d}d}
n"t| dr|	| |pd}ntd	zt|}|jd
ks|jdkrtd|j n@|jdkr|jjdkrt|j}d}nt|jj}n
|jd }t|}t|ttfkrRt||kr<tdt| t|tt|}nt |tr|d}td| }|dkr|rd||f g| }n
|g| }||}n4|r|d| kr|n|s||kr|n|}ntd|f t|d
kr"|dd| }||| |  |rx|D ]T}g }x&|D ]}| |j! | |j" q<W |t| | }||dd q.W nlxj|D ]b}y|t| | }W n< t#k
r } zt#dt|j|f |W dd}~X Y nX || qW t|d
kr$|dd| }||| |  W d|
r6|  X dS )a  
    Save an array to a text file.

    Parameters
    ----------
    fname : filename or file handle
        If the filename ends in ``.gz``, the file is automatically saved in
        compressed gzip format.  `loadtxt` understands gzipped files
        transparently.
    X : 1D or 2D array_like
        Data to be saved to a text file.
    fmt : str or sequence of strs, optional
        A single format (%10.5f), a sequence of formats, or a
        multi-format string, e.g. 'Iteration %d -- %10.5f', in which
        case `delimiter` is ignored. For complex `X`, the legal options
        for `fmt` are:

        * a single specifier, `fmt='%.4e'`, resulting in numbers formatted
          like `' (%s+%sj)' % (fmt, fmt)`
        * a full string specifying every real and imaginary part, e.g.
          `' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'` for 3 columns
        * a list of specifiers, one per column - in this case, the real
          and imaginary part must have separate specifiers,
          e.g. `['%.3e + %.3ej', '(%.15e%+.15ej)']` for 2 columns
    delimiter : str, optional
        String or character separating columns.
    newline : str, optional
        String or character separating lines.

        .. versionadded:: 1.5.0
    header : str, optional
        String that will be written at the beginning of the file.

        .. versionadded:: 1.7.0
    footer : str, optional
        String that will be written at the end of the file.

        .. versionadded:: 1.7.0
    comments : str, optional
        String that will be prepended to the ``header`` and ``footer`` strings,
        to mark them as comments. Default: '# ',  as expected by e.g.
        ``numpy.loadtxt``.

        .. versionadded:: 1.7.0
    encoding : {None, str}, optional
        Encoding used to encode the outputfile. Does not apply to output
        streams. If the encoding is something other than 'bytes' or 'latin1'
        you will not be able to load the file in NumPy versions < 1.14. Default
        is 'latin1'.

        .. versionadded:: 1.14.0


    See Also
    --------
    save : Save an array to a binary file in NumPy ``.npy`` format
    savez : Save several arrays into an uncompressed ``.npz`` archive
    savez_compressed : Save several arrays into a compressed ``.npz`` archive

    Notes
    -----
    Further explanation of the `fmt` parameter
    (``%[flag]width[.precision]specifier``):

    flags:
        ``-`` : left justify

        ``+`` : Forces to precede result with + or -.

        ``0`` : Left pad the number with zeros instead of space (see width).

    width:
        Minimum number of characters to be printed. The value is not truncated
        if it has more characters.

    precision:
        - For integer specifiers (eg. ``d,i,o,x``), the minimum number of
          digits.
        - For ``e, E`` and ``f`` specifiers, the number of digits to print
          after the decimal point.
        - For ``g`` and ``G``, the maximum number of significant digits.
        - For ``s``, the maximum number of characters.

    specifiers:
        ``c`` : character

        ``d`` or ``i`` : signed decimal integer

        ``e`` or ``E`` : scientific notation with ``e`` or ``E``.

        ``f`` : decimal floating point

        ``g,G`` : use the shorter of ``e,E`` or ``f``

        ``o`` : signed octal

        ``s`` : string of characters

        ``u`` : unsigned decimal integer

        ``x,X`` : unsigned hexadecimal integer

    This explanation of ``fmt`` is not complete, for an exhaustive
    specification see [1]_.

    References
    ----------
    .. [1] `Format Specification Mini-Language
           <https://docs.python.org/library/string.html#format-specification-mini-language>`_,
           Python Documentation.

    Examples
    --------
    >>> x = y = z = np.arange(0.0,5.0,1.0)
    >>> np.savetxt('test.out', x, delimiter=',')   # X is an array
    >>> np.savetxt('test.out', (x,y,z))   # x,y,z equal sized 1D arrays
    >>> np.savetxt('test.out', x, fmt='%1.4e')   # use exponential notation

    c               @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )zsavetxt.<locals>.WriteWrapz0Convert to bytes on bytestream inputs.

        c             S   s   || _ || _| j| _d S )N)r   rv   first_writedo_write)r;   r   rv   r(   r(   r)   r=   6  s    z#savetxt.<locals>.WriteWrap.__init__c             S   s   | j   d S )N)r   r`   )r;   r(   r(   r)   r`   ;  s    z savetxt.<locals>.WriteWrap.closec             S   s   |  | d S )N)r  )r;   vr(   r(   r)   r   >  s    z savetxt.<locals>.WriteWrap.writec             S   s0   t |tr| j| n| j|| j d S )N)r   rn   r   r   r   rv   )r;   r  r(   r(   r)   write_bytesA  s    
z&savetxt.<locals>.WriteWrap.write_bytesc             S   s   | j t| d S )N)r   r   r   )r;   r  r(   r(   r)   write_normalG  s    z'savetxt.<locals>.WriteWrap.write_normalc             S   sB   y|  | | j | _W n& tk
r<   | | | j| _Y nX d S )N)r  r   r   r  )r;   r  r(   r(   r)   r  J  s    

z&savetxt.<locals>.WriteWrap.first_writeN)
rF   rG   rH   rI   r=   r`   r   r  r  r  r(   r(   r(   r)   	WriteWrap2  s   r  Fwt)rv   Tr   ru   z%fname must be a string or file handler   r    z.Expected 1D or 2D array, got %dD array insteadr   Nzfmt has wrong shape.  %s%z'fmt has wrong number of %% formats:  %sz	 (%s+%sj)zinvalid fmt: %rr  z+-r   z?Mismatch between array dtype ('%s') and format specifier ('%s'))$r   rn   r   r   r   r   rj   r`   r   r   r   rL   rz   Zasarrayr   r   r   r	  r
  rh   r   Ziscomplexobjr   rC   r   rA   r   r   mapcountr   r   rY   realimagr   )r   r   r  r   r  r  r  r   rv   r  own_fhr   ZncolZiscomplex_Xr   Zn_fmt_charserrorrowZrow2numbersr  r   r(   r(   r)   r*     s    |
!











&c       	      C   s  d}t | ds&tjjj| d|d} d}zt|tjs>t|}|  }t|trht|tj	j
rht|}n t|tj	j
rt|trt|}t |dst|}||}|rt|d tst||jd  }tj||d}||_ntj||d}|S |r|   X d	S )
a  
    Construct an array from a text file, using regular expression parsing.

    The returned array is always a structured array, and is constructed from
    all matches of the regular expression in the file. Groups in the regular
    expression are converted to fields of the structured array.

    Parameters
    ----------
    file : str or file
        Filename or file object to read.
    regexp : str or regexp
        Regular expression used to parse the file.
        Groups in the regular expression correspond to fields in the dtype.
    dtype : dtype or list of dtypes
        Dtype for the structured array.
    encoding : str, optional
        Encoding used to decode the inputfile. Does not apply to input streams.

        .. versionadded:: 1.14.0

    Returns
    -------
    output : ndarray
        The output array, containing the part of the content of `file` that
        was matched by `regexp`. `output` is always a structured array.

    Raises
    ------
    TypeError
        When `dtype` is not a valid dtype for a structured array.

    See Also
    --------
    fromstring, loadtxt

    Notes
    -----
    Dtypes for structured arrays can be specified in several forms, but all
    forms specify at least the data type and field name. For details see
    `basics.rec`.

    Examples
    --------
    >>> f = open('test.dat', 'w')
    >>> _ = f.write("1312 foo\n1534  bar\n444   qux")
    >>> f.close()

    >>> regexp = r"(\d+)\s+(...)"  # match [digits, whitespace, anything]
    >>> output = np.fromregex('test.dat', regexp,
    ...                       [('num', np.int64), ('key', 'S3')])
    >>> output
    array([(1312, b'foo'), (1534, b'bar'), ( 444, b'qux')],
          dtype=[('num', '<i8'), ('key', 'S3')])
    >>> output['num']
    array([1312, 1534,  444])

    FrJ   r   )rv   Tmatchr   )r   N)rL   r   r   r   rj   r   r   rJ   rn   compatunicoder   r   r   r   findallr   r   r  r`   )	rO   regexpr   rv   r#  contentseqZnewdtypeoutputr(   r(   r)   r5     s.    <





c            C   s   |fS )Nr(   )r   r   r   r   skip_headerskip_footerr   missing_valuesfilling_valuesr   r   excludelistdeletecharsreplace_space	autostripcase_sensitive
defaultfmtr   usemasklooseinvalid_raiser   rv   r   r(   r(   r)   _genfromtxt_dispatcher  s    r=  _zf%ic      R         s  |dk	r@t | ||
|||||	||||||||||||dS |dk	rd|rTtd|dk rdtd|rxddlm}m} |p~i }t|tstdt| |d	krd}d
}nd}yVt| t	rt
| } t| trtjjj| d|d}t|}n| }t|}t|}W n6 tk
r< } ztdt|  |W dd}~X Y nX | t||||d} t||||d}!y~xt
D ]t| qrW d}"xX|"stt||}#d
kr|dk	r||#krd|#|dd }#| |#}"qW W n0 tk
r   d}#g }"tjd|  dd Y nX d
krF|"d  }$|dk	rF|$|krF|"d= |	dk	rydd |	dD }	W n@ tk
r   yt |	}	W n tk
r   |	g}	Y nX Y nX t!|	p|"}%d
kr|!dd |"D d}#n2t"r|!dd dD nr|!dk	r,t#||||ddk	r>t |	rxJt$|	D ]>\}&t"|&rp%|&|	< n|&dk rN|&t!|" |	< qNW dk	rt!|%kr҈j&t'fdd|	D t j(n*dk	rt!|%krfdd|	D ndk	rdk	rt j(|p$d}'t|'t)r<|'*d}'dd t|%D }t|'tr2x|'+ D ]\}(})t"|(ry%|(}(W n tk
r   wdY nX |	ry|	%|(}(W n tk
r   Y nX t|)t t,frd d |)D })n
t|)g})|(dkrx(|D ]}*|*-|) qW n||( -|) qdW nt|'t t,frzxt.|'|D ]&\}+},t|+}+|+|,krN|,/|+ qNW nRt|'tr|'d}-x:|D ]},|,-|- qW n x|D ]},|,-t|'g qW |}.|.dkrg }.dg|% }t|.trvx|.+ D ]r\}(})t"|(r:y%|(}(W n tk
r8   wY nX |	rfy|	%|(}(W n tk
rd   Y nX |)||(< qW nHt|.t t,frt!|.}/|/|%kr|.|d|/< n|.d|% }n
|.g|% }dkrd!d t.||D }nRt0d
d"}0t!|0dkrt.|0||}1d#d |1D }nt.||}1fd$d|1D }g }2x|+ D ]\}3 t"|3ry%|3}3|3W n tk
r|   w>Y nX n6|	ry|	%|3W n tk
r   w>Y nX n|3t!|#r|"|3 }4nd}4 t)krt1}5n"|rd%d& }6t2j3|6 d'}5n }5| j4|5d
|4| | d( |2/|5f q>W |4|2 g 		j/}7|rXg }8|8j/}9g }:|:j/};xt$t56|#g|D ]\}<| |<t!}=|=dkrqv|	ryfd)d|	D W n. t7k
r   |;
 d |=f wvY nX n"|=|%k	r|;
 d |=f qv|7t, |	r:|9t,d*d t.|D  t!	|krvP qvW W dQ R X dk
r0xt$|D ]\}>fd+d	D }?y|>8|? W n t9k

r(   d, }@t:t;	}?xdt$|?D ]X\}3}+y|><|+ W n> t=tfk

r   |@d-7 }@|@|3d 
 |+f; }@t=|@Y nX 	qW Y nX 	qnW t!|:}A|Adk
rt!	|A | d.|% |dk
rt!
fd/d|:D }B|:d|A|B  }:||B8 }fd0d|:D }@t!|@
r|@>dd1 d2|@}@|
rt|@ntj|@t?dd |dkr	d|  	|r|8d|  }8|r8t t.	fd3dt$|D  	nt t.	fd4dt$|D  		}Cdkr
d5d |D }Dd6d t$|DD |rrtjd7tj@dd fd8d9yfd:d|CD }CW n tAk
r   Y nX xD ]tjB|D< qW |Ddd }ExHt$|DD ]<\}FtC|FtjDrtEfd;d<|CD }G|F|Gf|E< qW dkrd=d> t.||DD }Ht!|Hdkr|H\}I|ItF }J}Kn2fd?dt$|ED }J|rfd@dt$|ED }Kn&t t.|E}Jt t.tFgt!|E }KtjG|C|JdA|rtjG|8|KdA}Lnr"j(dk	r"_(t!|0dkrdBdCd< |0D krhtHrXtIdDntjG|CdAn"tjG|CdEd |0D dA		J|rtjG|8t'dFd |0D dA}M|}K|MJ|K}Ln|r|d
}Ng xt$dGd |D D ]j\}O|kr>|N|OjkM }NtC|OtjDr.|OtEfdHd<|CD f}O/d|Of n/df qW |Ns|t!dkrrt'n
t'|OtG|C|rj(dk	rdId j(D }KntF}KtjG|8|KdA}Lj'j(|r(r(xTt.|D ]F\}P  fdJd jKD }x&|D ]}Q|L|P  |P |QkO  < q W qW |r>J||L_LtM|rdkr^jNS t!dkrxd  S fdKdD S S )La  
    Load data from a text file, with missing values handled as specified.

    Each line past the first `skip_header` lines is split at the `delimiter`
    character, and characters following the `comments` character are discarded.

    Parameters
    ----------
    fname : file, str, pathlib.Path, list of str, generator
        File, filename, list, or generator to read.  If the filename
        extension is `.gz` or `.bz2`, the file is first decompressed. Note
        that generators must return byte strings. The strings
        in a list or produced by a generator are treated as lines.
    dtype : dtype, optional
        Data type of the resulting array.
        If None, the dtypes will be determined by the contents of each
        column, individually.
    comments : str, optional
        The character used to indicate the start of a comment.
        All the characters occurring on a line after a comment are discarded.
    delimiter : str, int, or sequence, optional
        The string used to separate values.  By default, any consecutive
        whitespaces act as delimiter.  An integer or sequence of integers
        can also be provided as width(s) of each field.
    skiprows : int, optional
        `skiprows` was removed in numpy 1.10. Please use `skip_header` instead.
    skip_header : int, optional
        The number of lines to skip at the beginning of the file.
    skip_footer : int, optional
        The number of lines to skip at the end of the file.
    converters : variable, optional
        The set of functions that convert the data of a column to a value.
        The converters can also be used to provide a default value
        for missing data: ``converters = {3: lambda s: float(s or 0)}``.
    missing : variable, optional
        `missing` was removed in numpy 1.10. Please use `missing_values`
        instead.
    missing_values : variable, optional
        The set of strings corresponding to missing data.
    filling_values : variable, optional
        The set of values to be used as default when the data are missing.
    usecols : sequence, optional
        Which columns to read, with 0 being the first.  For example,
        ``usecols = (1, 4, 5)`` will extract the 2nd, 5th and 6th columns.
    names : {None, True, str, sequence}, optional
        If `names` is True, the field names are read from the first line after
        the first `skip_header` lines. This line can optionally be preceeded
        by a comment delimiter. If `names` is a sequence or a single-string of
        comma-separated names, the names will be used to define the field names
        in a structured dtype. If `names` is None, the names of the dtype
        fields will be used, if any.
    excludelist : sequence, optional
        A list of names to exclude. This list is appended to the default list
        ['return','file','print']. Excluded names are appended with an
        underscore: for example, `file` would become `file_`.
    deletechars : str, optional
        A string combining invalid characters that must be deleted from the
        names.
    defaultfmt : str, optional
        A format used to define default field names, such as "f%i" or "f_%02i".
    autostrip : bool, optional
        Whether to automatically strip white spaces from the variables.
    replace_space : char, optional
        Character(s) used in replacement of white spaces in the variable
        names. By default, use a '_'.
    case_sensitive : {True, False, 'upper', 'lower'}, optional
        If True, field names are case sensitive.
        If False or 'upper', field names are converted to upper case.
        If 'lower', field names are converted to lower case.
    unpack : bool, optional
        If True, the returned array is transposed, so that arguments may be
        unpacked using ``x, y, z = genfromtxt(...)``.  When used with a
        structured data-type, arrays are returned for each field.
        Default is False.
    usemask : bool, optional
        If True, return a masked array.
        If False, return a regular array.
    loose : bool, optional
        If True, do not raise errors for invalid values.
    invalid_raise : bool, optional
        If True, an exception is raised if an inconsistency is detected in the
        number of columns.
        If False, a warning is emitted and the offending lines are skipped.
    max_rows : int,  optional
        The maximum number of rows to read. Must not be used with skip_footer
        at the same time.  If given, the value must be at least 1. Default is
        to read the entire file.

        .. versionadded:: 1.10.0
    encoding : str, optional
        Encoding used to decode the inputfile. Does not apply when `fname` is
        a file object.  The special value 'bytes' enables backward compatibility
        workarounds that ensure that you receive byte arrays when possible
        and passes latin1 encoded strings to converters. Override this value to
        receive unicode arrays and pass strings as input to converters.  If set
        to None the system default is used. The default value is 'bytes'.

        .. versionadded:: 1.14.0
    ${ARRAY_FUNCTION_LIKE}

        .. versionadded:: 1.20.0

    Returns
    -------
    out : ndarray
        Data read from the text file. If `usemask` is True, this is a
        masked array.

    See Also
    --------
    numpy.loadtxt : equivalent function when no data is missing.

    Notes
    -----
    * When spaces are used as delimiters, or when no delimiter has been given
      as input, there should not be any missing data between two fields.
    * When the variables are named (either by a flexible dtype or with `names`),
      there must not be any header in the file (else a ValueError
      exception is raised).
    * Individual values are not stripped of spaces by default.
      When using a custom converter, make sure the function does remove spaces.

    References
    ----------
    .. [1] NumPy User Guide, section `I/O with NumPy
           <https://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html>`_.

    Examples
    --------
    >>> from io import StringIO
    >>> import numpy as np

    Comma delimited file with mixed dtype

    >>> s = StringIO(u"1,1.3,abcde")
    >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'),
    ... ('mystring','S5')], delimiter=",")
    >>> data
    array((1, 1.3, b'abcde'),
          dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])

    Using dtype = None

    >>> _ = s.seek(0) # needed for StringIO example only
    >>> data = np.genfromtxt(s, dtype=None,
    ... names = ['myint','myfloat','mystring'], delimiter=",")
    >>> data
    array((1, 1.3, b'abcde'),
          dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])

    Specifying dtype and names

    >>> _ = s.seek(0)
    >>> data = np.genfromtxt(s, dtype="i8,f8,S5",
    ... names=['myint','myfloat','mystring'], delimiter=",")
    >>> data
    array((1, 1.3, b'abcde'),
          dtype=[('myint', '<i8'), ('myfloat', '<f8'), ('mystring', 'S5')])

    An example with fixed-width columns

    >>> s = StringIO(u"11.3abcde")
    >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'],
    ...     delimiter=[1,3,5])
    >>> data
    array((1, 1.3, b'abcde'),
          dtype=[('intvar', '<i8'), ('fltvar', '<f8'), ('strvar', 'S5')])

    An example to show comments

    >>> f = StringIO('''
    ... text,# of chars
    ... hello world,11
    ... numpy,5''')
    >>> np.genfromtxt(f, dtype='S12,S12', delimiter=',')
    array([(b'text', b''), (b'hello world', b'11'), (b'numpy', b'5')],
      dtype=[('f0', 'S12'), ('f1', 'S12')])

    N)r   r   r   r0  r1  r   r2  r3  r   r   r4  r5  r6  r7  r8  r9  r   r:  r;  r<  r   rv   r   zPThe keywords 'skip_footer' and 'max_rows' can not be specified at the same time.r   z'max_rows' must be at least 1.r   )MaskedArraymake_mask_descrzNThe input argument 'converter' should be a valid dictionary (got '%s' instead)rn   TFr   )rv   zRfname must be a string, filehandle, list of strings, or generator. Got %s instead.)r   r   r7  rv   )r4  r5  r8  r6  r   z"genfromtxt: Empty input file: "%s"r    )r!   c             S   s   g | ]}|  qS r(   )r   )r   r>  r(   r(   r)   r   3  s    zgenfromtxt.<locals>.<listcomp>,c             S   s   g | ]}t | qS r(   )r   r   )r   r>  r(   r(   r)   r   =  s    c             S   s   g | ]}|  qS r(   )r   )r   r>  r(   r(   r)   r   @  s    )r9  r   r4  r5  r8  r6  c                s   g | ]} | qS r(   r(   )r   r>  )descrr(   r)   r   X  s    c                s   g | ]} | qS r(   r(   )r   r>  )r   r(   r)   r   \  s    r(   ru   c             S   s   g | ]}t d gqS )r   )rC   )r   r>  r(   r(   r)   r   g  s    c             S   s   g | ]}t |qS r(   )r   )r   r>  r(   r(   r)   r   }  s    c             S   s   g | ]\}}t d ||dqS )N)r2  default)r   )r   missfillr(   r(   r)   r     s   )Zflatten_basec             S   s"   g | ]\}}}t |d ||dqS )T)lockedr2  rC  )r   )r   r   rD  rE  r(   r(   r)   r     s   c                s    g | ]\}}t  d ||dqS )T)rF  r2  rC  )r   )r   rD  rE  )r   r(   r)   r     s   c             S   s"   t | tkr|| S || dS )Nru   )r   rn   r   )r^   r   r(   r(   r)   r     s    z!genfromtxt.<locals>.tobytes_first)r   )rF  testing_valuerC  r2  c                s   g | ]} | qS r(   r(   )r   r>  )r   r(   r)   r     s    c             S   s   g | ]\}}|  |kqS r(   )r   )r   r  mr(   r(   r)   r     s   c                s   g | ]}t  |qS r(   )r   )r   _m)r   r(   r)   r   '  s    z0Converter #%i is locked and cannot be upgraded: z"(occurred line #%i for value '%s')z-    Line #%%i (got %%i columns instead of %i)c                s    g | ]}|d    kr|qS )r   r(   )r   r>  )nbrowsr0  r(   r)   r   <  s    c                s   g | ]\}} ||f qS r(   r(   )r   r   nb)templater(   r)   r   E  s   zSome errors were detected !r  c                s,   g | ]$\}  fd dt t|D qS )c                s   g | ]}  |qS r(   )Z_loose_call)r   _r)r   r(   r)   r   [  s    z)genfromtxt.<locals>.<listcomp>.<listcomp>)r  r   )r   r   )rows)r   r)   r   [  s   c                s,   g | ]$\}  fd dt t|D qS )c                s   g | ]}  |qS r(   )Z_strict_call)r   rM  )r   r(   r)   r   _  s    z)genfromtxt.<locals>.<listcomp>.<listcomp>)r  r   )r   r   )rN  )r   r)   r   _  s   c             S   s   g | ]
}|j qS r(   )r   )r   r   r(   r(   r)   r   f  s    c             S   s   g | ]\}}|t jkr|qS r(   )r   r   )r   r   r  r(   r(   r)   r   h  s    zReading unicode strings without specifying the encoding argument is deprecated. Set the encoding, use None for the system default.c                s0   t | }x D ]}|| d||< qW t|S )Nru   )rC   r   r   )Zrow_tupr%  r   )	strcolidxr(   r)   encode_unicode_colsr  s    
z'genfromtxt.<locals>.encode_unicode_colsc                s   g | ]} |qS r(   r(   )r   r)rP  r(   r)   r   y  s    c             3   s   | ]}t |  V  qd S )N)rh   )r   r%  )r   r(   r)   r     s    zgenfromtxt.<locals>.<genexpr>c             S   s   h | ]\}}|j r|qS r(   )Z_checked)r   cZc_typer(   r(   r)   	<setcomp>  s   zgenfromtxt.<locals>.<setcomp>c                s   g | ]\}} | |fqS r(   r(   )r   r   r   )r9  r(   r)   r     s   c                s   g | ]\}} | t fqS r(   )r   )r   r   r   )r9  r(   r)   r     s   )r   Oc             s   s   | ]}|j V  qd S )N)char)r   r>  r(   r(   r)   r     s    z4Nested fields involving objects are not supported...c             S   s   g | ]}d |fqS )r   r(   )r   r>  r(   r(   r)   r     s    c             S   s   g | ]}d t fqS )r   )r   )r   tr(   r(   r)   r     s    c             S   s   g | ]
}|j qS r(   )r   )r   r   r(   r(   r)   r     s    c             3   s   | ]}t |  V  qd S )N)rh   )r   r%  )r   r(   r)   r     s    c             S   s   g | ]}|t fqS r(   )r   )r   r>  r(   r(   r)   r     s    c                s   g | ]}|d kr |qS )r   r(   )r   r>  )r   r(   r)   r     s    c                s   g | ]} | qS r(   r(   )r   r   )r/  r(   r)   r     s    )O_genfromtxt_with_likerz   Znumpy.mar?  r@  r   r{   r   r   r   r   r   r   r   r   rj   r|   closingr   rf   r   r   r   r  r   r   r   r  r"   r#   r   rA   rC   rh   r   r   r   r   rB  r   r   rn   decoderq   r   r   rZ   rY   r   r   r  r  updater   r   
IndexErrorZiterupgrader   r  r   upgrader   insertr   ZVisibleDeprecationWarningUnicodeEncodeErrorr   Z
issubdtype	charactermaxr   r  r   NotImplementedErrorviewr2  Z_maskr  r
  )Rr   r   r   r   r0  r1  r   r2  r3  r   r   r4  r5  r6  r7  r8  r9  r   r:  r;  r<  r   rv   r   r?  r@  r  r  r\   Zfid_ctxZfhdr   r   Zvalidate_namesZfirst_valuesr   ZfvalZnbcolscurrentZuser_missing_valuesrB   r   rD  valueentryZ
user_valueZuser_filling_valuesnZ
dtype_flatZzipitZ	uc_updater   rG  Z	user_convr   Zappend_to_rowsmasksZappend_to_masksinvalidZappend_to_invalidr   Znbvalues	converterZcurrent_columnerrmsgZ	nbinvalidZnbinvalid_skippeddataZcolumn_typesZsized_column_typesZcol_typeZn_charsr   Zuniform_typeZddtypeZmdtypeZ
outputmaskZrowmasksZishomogeneousttypenameZmvalr(   )r   r9  rB  r   rP  r   r   rJ  r/  rN  r0  rO  rL  r   r)   r,     s    @



 











































 
















$


c             K   s$   d|d< t jdtdd t| f|S )a  
    Load ASCII data stored in a file and return it as a single array.

    .. deprecated:: 1.17
        ndfromtxt` is a deprecated alias of `genfromtxt` which
        overwrites the ``usemask`` argument with `False` even when
        explicitly called as ``ndfromtxt(..., usemask=True)``.
        Use `genfromtxt` instead.

    Parameters
    ----------
    fname, kwargs : For a description of input parameters, see `genfromtxt`.

    See Also
    --------
    numpy.genfromtxt : generic function.

    Fr:  zGnp.ndfromtxt is a deprecated alias of np.genfromtxt, prefer the latter.r    )r!   )r"   r#   r$   r,   )r   r'   r(   r(   r)   r-     s
    
c             K   s$   d|d< t jdtdd t| f|S )a  
    Load ASCII data stored in a text file and return a masked array.

    .. deprecated:: 1.17
        np.mafromtxt is a deprecated alias of `genfromtxt` which
        overwrites the ``usemask`` argument with `True` even when
        explicitly called as ``mafromtxt(..., usemask=False)``.
        Use `genfromtxt` instead.

    Parameters
    ----------
    fname, kwargs : For a description of input parameters, see `genfromtxt`.

    See Also
    --------
    numpy.genfromtxt : generic function to load ASCII data.

    Tr:  zGnp.mafromtxt is a deprecated alias of np.genfromtxt, prefer the latter.r    )r!   )r"   r#   r$   r,   )r   r'   r(   r(   r)   r.   	  s
    
c             K   sP   | dd |dd}t| f|}|r@ddlm} ||}n|tj}|S )a  
    Load ASCII data from a file and return it in a record array.

    If ``usemask=False`` a standard `recarray` is returned,
    if ``usemask=True`` a MaskedRecords array is returned.

    Parameters
    ----------
    fname, kwargs : For a description of input parameters, see `genfromtxt`.

    See Also
    --------
    numpy.genfromtxt : generic function

    Notes
    -----
    By default, `dtype` is None, which means that the data-type of the output
    array will be determined from the data.

    r   Nr:  Fr   )MaskedRecords)
setdefaultgetr,   numpy.ma.mrecordsrn  rb  r   recarray)r   r'   r:  r/  rn  r(   r(   r)   r/   ,	  s    c             K   st   | dd | dd | dd | dd t| f|}|d	d
}|rdddlm} ||}n|tj}|S )a8  
    Load ASCII data stored in a comma-separated file.

    The returned array is a record array (if ``usemask=False``, see
    `recarray`) or a masked record array (if ``usemask=True``,
    see `ma.mrecords.MaskedRecords`).

    Parameters
    ----------
    fname, kwargs : For a description of input parameters, see `genfromtxt`.

    See Also
    --------
    numpy.genfromtxt : generic function to load ASCII data.

    Notes
    -----
    By default, `dtype` is None, which means that the data-type of the output
    array will be determined from the data.

    r8  r   r   Tr   rA  r   Nr:  Fr   )rn  )ro  r,   rp  rq  rn  rb  r   rr  )r   r'   r/  r:  rn  r(   r(   r)   r0   L	  s    )NFTrt   )NN)TT)TN)
NNNNNNNNNN)NNNNNNN)r  r  r  r   r   r  N)N)NNNNNNNNNNNNNNNNNNNNNN)Ssysosr   r  r   r"   r8   r|   operatorr   r   r   collections.abcr   r   r   r   r   r   r   Z
numpy.corer   Znumpy.core.multiarrayr	   r
   Znumpy.core.overridesr   r   Znumpy.core._internalr   Z_iotoolsr   r   r   r   r   r   r   r   r   r   r   Znumpy.compatr   r   r   r   r   r   r%   __all__r  Zarray_function_dispatchr7   rP   rQ   r1   r   r2   r   r3   r   r4   r   r   r  r   r   r+   r   r  r*   r5   r=  r   sortedZdefaultdeletecharsr,   rW  r-   r.   r/   r0   r(   r(   r(   r)   <module>   s   4 

1 *  )
JSB
%!     #  
  wb           R 