U Dx`]@sddlZddlZddlZddlZddlZddlZddlZddlZddlm Z m Z ddl m Z ddlZddlmZddlmZddlmZddlmZmZdd lmZmZdd lmZdd lmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)dd l*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1ed ddZ2ddddddddddddddddgZ3ej4ej5d dZ5Gd d!d!Z6d"d#Z7Gd$d%d%e Z8ed dPd)dZ9dQd*d+Z:e5e:dRd,dZ;d-d.Ze5e>d2dZ?dSd3d4Z@d5d6ZAd7ZBdTdd8d9d:ZCeed eDd;ddddd&ddd?ZGe5eGdVdEdZHed dWdFdZIdXdd8dGdHZJeed eDd;ddddddddddCKeLe jMdId&d'dJdd&d'd'dd>> 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" cCst||_dSN)weakrefproxy_obj)selfobjr*r*r+__init__QszBagObj.__init__cCs6zt|d|WStk r0t|dYnXdS)Nr=)object__getattribute__KeyErrorAttributeError)r>keyr*r*r+rBUszBagObj.__getattribute__cCstt|dS)z Enables dir(bagobj) to list the files in an NpzFile. This also enables tab-completion in an interpreter or IPython. r=)listrArBkeysr>r*r*r+__dir__[szBagObj.__dir__N)__name__ __module__ __qualname____doc__r@rBrIr*r*r*r+r93sr9cOs4t|dst|}ddl}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. readrNT allowZip64)hasattrrzipfileZipFile)filer(r)rQr*r*r+zipfile_factoryds  rTc@sjeZdZdZdZdZdddZddZdd Zd d Z d d Z ddZ ddZ ddZ ddZddZdS)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]) NFcCszt|}||_g|_||_||_|jD]0}|drN|j|ddq*|j|q*||_t ||_ |rv||_ dS)N.npy) rTnamelist_filesfiles allow_pickle pickle_kwargsendswithappendzipr9ffid)r>raown_fidr[r\_zipxr*r*r+r@s    zNpzFile.__init__cCs|Sr:r*rHr*r*r+ __enter__szNpzFile.__enter__cCs |dSr:close)r>exc_type exc_value tracebackr*r*r+__exit__szNpzFile.__exit__cCs>|jdk r|jd|_|jdk r4|jd|_d|_dS)z" Close the file. N)r_rgrar`rHr*r*r+rgs    z NpzFile.closecCs |dSr:rfrHr*r*r+__del__szNpzFile.__del__cCs t|jSr:)iterrZrHr*r*r+__iter__szNpzFile.__iter__cCs t|jSr:)lenrZrHr*r*r+__len__szNpzFile.__len__cCsd}||jkrd}n||jkr*d}|d7}|r|j|}|ttj}||tjkr||j|}tj ||j |j dS|j|Sn t d|dS)NFTrVr[r\z%s is not a file in the archive) rYrZr_openrNror MAGIC_PREFIXrg read_arrayr[r\rC)r>rEmemberbytesmagicr*r*r+ __getitem__s$      zNpzFile.__getitem__cCstjdtdd|S)NziNpzFile.iteritems is deprecated in python 3, to match the removal of dict.itertems. Use .items() instead.r!r")r$r%r&itemsrHr*r*r+ iteritems s zNpzFile.iteritemscCstjdtdd|S)NzgNpzFile.iterkeys is deprecated in python 3, to match the removal of dict.iterkeys. Use .keys() instead.r!r")r$r%r&rGrHr*r*r+iterkeyss zNpzFile.iterkeys)FFN)rJrKrLrMr_rar@rerkrgrlrnrprxrzr{r*r*r*r+rUssB  "rUFTASCIIc Cs||dkrtdt||d}tL}t|dr<|}d}n|tt|d}d}d} d } tt j } | | } | t | t|  d | | s| | r|t||||d } | W5QRS| t j kr |rt j||d W5QRSt j|||d W5QRSnb|stdztj|f|WW5QRStk rl}ztdt||W5d}~XYnXW5QRXdS)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]) )r|latin1rvz.encoding must be 'ASCII', 'latin1', or 'bytes')encoding fix_importsrNFrbTsPKsPKr)rbr[r\)moderqz@Cannot load file containing pickled data when allow_pickle=Falsez'Failed to interpret file %s as a pickleN) ValueErrordict contextlib ExitStackrP enter_contextrrrrorrsrNseekmin startswithpop_allrUZ open_memmaprtrr3 ExceptionIOErrorrepr)rSZ mmap_moder[rr~r\stackrarbZ _ZIP_PREFIXZ _ZIP_SUFFIXNrwreter*r*r+r3sHp        cCs|fSr:r*)rSarrr[rr*r*r+_save_dispatchersrc Csnt|drt|}n$t|}|ds.|d}t|d}|(}t|}tj|||t |ddW5QRXdS)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] writerVwb)rrqN) rPrrr]rrnp asanyarrayr write_arrayr)rSrr[rZfile_ctxrar*r*r+r4s=      cos|EdH|EdHdSr:valuesrSr(kwdsr*r*r+_savez_dispatchers rcOst|||ddS)a1 Save several arrays into a single file in uncompressed ``.npz`` format. If arguments are passed in with no keywords, the corresponding variable names, in the ``.npz`` file, are 'arr_0', 'arr_1', etc. If keyword arguments are given, the corresponding variable names, in the ``.npz`` file will match the keyword names. 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. Since it is not possible for Python to know the names of the arrays outside `savez`, the arrays will be saved with names "arr_0", "arr_1", and so on. These arguments can be any expression. kwds : Keyword arguments, optional Arrays to save to the file. Arrays will be saved in the file with the keyword names. 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_savezrr*r*r+r5sOcos|EdH|EdHdSr:rrr*r*r+_savez_compressed_dispatcherls rcOst|||ddS)a Save several arrays into a single file in compressed ``.npz`` format. If keyword arguments are given, then filenames are taken from the keywords. If arguments are passed in with no keywords, then stored filenames are 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. Since it is not possible for Python to know the names of the arrays outside `savez`, the arrays will be saved with names "arr_0", "arr_1", and so on. These arguments can be any expression. kwds : Keyword arguments, optional Arrays to save to the file. Arrays will be saved in the file with the keyword names. 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 TNrrr*r*r+r6qs>c Csddl}t|ds,t|}|ds,|d}|}t|D]0\}} d|} | |kr`td| | || <q8|rv|j} n|j} t |d| d} | D]H\} } | d} t | } | j | dd d }tj|| ||d W5QRXq| dS) Nrrz.npzzarr_%dz,Cannot use un-named variables and keyword %sw)r compressionrVT) force_zip64rq)rQrPrr] enumeraterGr ZIP_DEFLATED ZIP_STOREDrTryrrrrrrrg)rSr(rcompressr[r\rQZnamedictivalrErZzipffnamerar*r*r+rs4     rcCsdd}|j}t|tjr"ddSt|tjr4tjSt|tjrFtjSt|tjrZddSt|tjrltjSt|tjr||St|t rddSt|tj rt St|tj rt StSdS)z; Find the correct dtype converter. Adapted from matplotlib cSs"|d|krt|St|S)N0x)lowerfloatfromhexrdr*r*r+ floatconvs z_getconv..floatconvcSs tt|Sr:)boolintrr*r*r+z_getconv..cSs tt|Sr:)rrrr*r*r+rrcSstt|ddS)N+--)complexrreplacerr*r*r+rrN)type issubclassrZbool_Zuint64int64integerZ longdoubleZfloatingrbytes_runicode_rr)dtypertypr*r*r+_getconvs*         riP)likec  Cs| fSr:r*) rrcomments delimiter convertersskiprowsusecolsunpackndminr~max_rowsrr*r*r+_loadtxt_dispatchersr#rvc s| dk r(t|||| | d Stdd} tdd  fdd f d d } |d krtd |dk rtttfrgd dDddDtd dk rt }d}dkrdd}dk r|z t }Wnt k r&g}YnX|D]J}z t |Wn6t k rr}zdt |f|_W5d}~XYnXq,|t|}t|| |\} d}zdt|trt|}t|rtjjj|ddtddtd}nt|t|ddWn.t k r0}ztd|W5d}~XYnXdk rBndkr\ddl}|ztD]}tqhd}z|st  }q~Wn0tk rd g}t j!d|ddYnXt"p|t"|d krd!d|Dn*fd"dtDd kr"t#fg |p*i$D]f\}}rjz%|}Wntk rhYq0YnX|rd#d$}t&j'||d%|<n||<q0fd&dDd| t(D]b}dkrt)||nDt j*}|d}|dt"|7<j+|dd'||dd(f<qW5|r,XdkrDt)g|j,d)krjj*ddd*krjd+_*j,|krt-j,|kr|d krt.n|dkrt/j0|rt"|d krfd,d|j1DSj0SnSdS)-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', '>> 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) rrrrrrrrr~rrc Ss|jdkr|j}t|dkr(|jgdfS|dtfg}t|dkrr|jdddD]}||dd||fg}qR|jgtt|j|fSnhg}g}|jD]P}|j|\}}||\} } | | |j dkr| | q| t| | fq||fSdS)z;Unpack a structured data-type, and produce re-packing info.Nrr) namesshaperobaserFrrprodfieldsextendndimr^) r>dtrpackingZdimtypesfieldtprvZflat_dtZ flat_packingr*r*r+flatten_dtype_internals&         z'loadtxt..flatten_dtype_internalcSsv|dkr|dS|tkr t|S|tkr0t|Sd}g}|D],\}}|||||||||7}qryrstartrlengthZ subpackingr*r*r+ pack_itemss  zloadtxt..pack_itemscsBt|d}dk r&j|ddd}|d}|r>|SgS)z2Chop off comments, strip, and split at delimiter. r~Nr)maxsplitrz )rsplitstrip)line)rrr~regex_commentsr*r+ split_lines   zloadtxt..split_linec3sg}tg}t|}t|D]\}} |tdkrDq& rZfdd Dtkr~|d}td|ddtD}|}||t||kr&|Vg}q&|r|VdS)aParse 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. rcsg|] }|qSr*r*).0jvalsr*r+ sz.loadtxt..read_data..rz"Wrong number of columns at line %dcSsg|]\}}||qSr*r*)rconvrr*r*r+rsN) itertoolschainislicerrorr_r^) chunk_sizeXZ line_iterrrline_numry) rrfh first_linerrrrrrrr+ read_datas,        zloadtxt..read_data)rrr!z"Illegal value of ndmin keyword: %scSsg|] }t|qSr*)r)rrdr*r*r+rszloadtxt..css|]}t|VqdSr:)reescape)rcommentr*r*r+ szloadtxt..|FrvTz\usecols must be an int or a sequence of ints but it contains at least one element of type %srtrr~r}z1fname must be a string, file handle, or generatorrzloadtxt: Empty input file: "%s"r!r"rcSsg|] }t|qSr*)r)rrr*r*r+rWscsg|]}qSr*r*rr)defconvr*r+rZscSs"t|tkr||S||dSNr}rrvencoderdrr*r*r+ tobytes_firstjs zloadtxt..tobytes_firstrcs$g|]}|tk r|n fddqS)cs |Sr:)rr fencodingr*r+rsrz$loadtxt...)rvrrrr*r+rrs )Zrefcheck.)rr)rrcsg|] }|qSr*r*rr)rr*r+rs)2_loadtxt_with_liker r isinstancestrrvrcompilejoinrrF TypeErroropindexrr(rrrrrrlib _datasourcerrgetattrrmlocalegetpreferredencodingrgrangenext StopIterationr$r%rorryr functoolspartial_loadtxt_chunksizearrayrresizersqueezeZ atleast_1d atleast_2dTr)rrrrrrrrrr~rrrruser_convertersbyte_convertersZusecols_as_listZcol_idxrZ dtype_typesZfownrrZ first_valsrrrdZnshapeposr*)rrrrrrr~rrrrrrrrrrr+r-s    +                                   c Cs|fSr:r*) rrfmtrnewlineheaderfooterrr~r*r*r+_savetxt_dispatchersr(%.18e  r# c  Cs0t|trt|}t|}Gddd} d} t|tr>t|}t|rnt|dtj j j|d|d} d} n"t |dr| ||pd} nt d zt |}|jd ks|jd krt d |jn@|jd kr|jjdkrt|j}d } n t|jj} n |jd } t|} t|ttfkrRt|| kr`_, 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@eZdZdZddZddZddZdd Zd d Zd d Z dS)zsavetxt..WriteWrapz0Convert to bytes on bytestream inputs. cSs||_||_|j|_dSr:)rr~ first_writedo_write)r>rr~r*r*r+r@4sz#savetxt..WriteWrap.__init__cSs|jdSr:)rrgrHr*r*r+rg9sz savetxt..WriteWrap.closecSs||dSr:)r.r>vr*r*r+r<sz savetxt..WriteWrap.writecSs0t|tr|j|n|j||jdSr:)r rvrrrr~r/r*r*r+ write_bytes?s z&savetxt..WriteWrap.write_bytescSs|jt|dSr:)rrrr/r*r*r+ write_normalEsz'savetxt..WriteWrap.write_normalcSsBz|||j|_Wn&tk r<|||j|_YnXdSr:)r2rrr1r/r*r*r+r-Hs    z&savetxt..WriteWrap.first_writeN) rJrKrLrMr@rgrr1r2r-r*r*r*r+ WriteWrap0sr3FwtrTrr}z%fname must be a string or file handlerr!z.Expected 1D or 2D array, got %dD array insteadrNzfmt has wrong shape. %s%z'fmt has wrong number of %% formats: %sz (%s+%sj)zinvalid fmt: %rr+rrz?Mismatch between array dtype ('%s') and format specifier ('%s'))$r rvrrrrrrrgrrrrPrZasarrayrrrrr rorZ iscomplexobjrrFrrDr rmapcountrrr^realimagr)rrr$rr%r&r'rr~r3own_fhrZncolZ iscomplex_XrZ n_fmt_charserrorrowZrow2numbersr0rr*r*r+r,s| !                c Cs d}t|ds&tjjj|d|d}d}zt|tjs>t|}|}t|t rht|tj j rht |}n t|tj j rt|t rt |}t|dst|}||}|rt|dtst||jd}tj||d}||_ntj||d}|WS|r|Xd 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', '>> output['num'] array([1312, 1534, 444]) FrNrrTmatchrrN)rPrrrrrrgr rrNrvcompatunicoderrrr findallrrr) rSregexprr~r:contentseqZnewdtypeoutputr*r*r+r7s.<       cCs|fSr:r*)rrrr skip_header skip_footerrmissing_valuesfilling_valuesrr excludelist deletechars replace_space autostripcase_sensitive defaultfmtrusemaskloose invalid_raiserr~rr*r*r+_genfromtxt_dispatcher srU_zf%icRsR|dk r@t||| ||||| | | | |||||||||dS|dk rd|rTtd|dkrdtd|rxddlm}m}|p~i}t|tstdt||d krd}d }nd }zTt|t rt |}t|t rt j jj|d |d }t|}n |}t|}t|}Wn6tk r:}ztdt||W5d}~XYnX|t||||d} t| | || d}!zvt D]t|qnd}"|"stt||}#d kr|dk r||#krd|#|dd}#| |#}"qWn0tk r d}#g}"tjd|ddYnXd kr<|"d}$|dk r<|$|kr<|"d=| dk rzdd| dD} Wn@tk rz t | } Wntk r| g} YnXYnXt!| p|"}%d kr|!dd|"Dd}#n2t"r|!dddDnr|!dk r"t#| | || ddk r4t | rt$| D]>\}&t"|&rd%|&| <n|&dkrB|&t!|"| <qBdk rt!|%krĈj&t 'fdd| Dt j(n*dk rt!|%krfdd| Dndk rdk rt j(|pd}'t|'t)r.|'*d}'ddt|%D}t|'tr|'+D]\}(})t"|(rz%|(}(Wntk rYqTYnX| rz| %|(}(Wntk rYnXt|)t t,frd d|)D})n t |)g})|(dkr |D]}*|*-|)qn||(-|)qTnt|'t t,frbt.|'|D]&\}+},t |+}+|+|,kr8|,/|+q8nJt|'t r|'d}-|D]},|,-|-q|n|D]},|,-t |'gq|}.|.dkrg}.dg|%}t|.trT|.+D]t\}(})t"|(rz%|(}(Wntk rYqYnX| rFz| %|(}(Wntk rDYnX|)||(<qnHt|.t t,frt!|.}/|/|%kr|.|d|/<n |.d|%}n |.g|%}dkrd!dt.||D}nRt0d d"}0t!|0dkrt.|0||}1d#d|1D}nt.||}1fd$d|1D}g}2|+D]\}3t"|3r^z%|3}3|3Wntk rZYqYnXn8| rz| %|3Wntk rYqYnXn|3t!|#r|"|3}4nd}4t)krt1}5n"|rd%d&}6t2j3|6d'}5n}5|j4|5d |4||d(|2/|5fq|4|2g j/}7|r6g}8|8j/}9g}:|:j/};t$t56|#g|D]\}<| |< t! }=|=dkrxqR| rz fd)d| D Wn0t7k r|; d|=fYqRYnXn"|=|%kr|; d|=fqR|7t, | r|9t,d*dt. |Dt! |krR q0qRW5QRXdk rt$|D]\}>fd+d D}?z|>8|?Wnt9k rd,}@t:t; }?t$|?D]X\}3}+z|><|+Wn>t=tfk r|@d-7}@|@|3d |+f;}@t=|@YnX qYnX qLt!|:}A|Adk rt! |A|d.|% |dk rlt! fd/d|:D}B|:d|A|B}:||B8} fd0d|:D}@t!|@ r|@>dd1d2|@}@| rt|@ntj|@t?dd|dk r d|  | r|8d| }8| rt t. fd3dt$|D nt t. fd4dt$|D }Cdk rd5d|D}Dd6dt$|DD | rʈ rtjd7t j@dd fd8d9zfd:d|CD}CWntAk rYnX D]t jB|D< q|Ddd}Et$|DD]<\}Ft C|Ft jD rtEfd;d<|CD}G|F|Gf|E< qވdk rd=d>t.||DD}Ht!|Hdk rZ|H\}I|ItF}J}Kn2fd?dt$|ED}J| rfd@dt$|ED}Kn&t t.|E}Jt t.tFgt!|E}Kt jG|C|JdA|rt jG|8|KdA}Ln rj(dk r_(t!|0dk rdBdCd<|0Dk r8tH r(tIdDnt jG|CdAn"t jG|CdEd|0DdA J|rt jG|8t 'dFd|0DdA}M|}K|MJ|K}Ln|rHd }Ngt$dGd|DD]j\}O|kr |N|OjkM}Nt C|Ot jD r|OtEfdHd<|CDf}O/d|Ofn/df q|NsHt!dkr>t 'n t '|Ot G|C|rj(dk rxdIdj(D}KntF}Kt jG|8|KdA}Lj'j(|rrt.|D]B\}PfdJdjKD}|D]}Q|L|P|P|QkO<qȐq|rJ||L_Lt M|rNdkr"jNSt!dkr<dSfdKdDSS)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 proceeded 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 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 variables 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 `_. 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', '>> _ = 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', '>> _ = 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', '>> 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', '>> 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)rrrrHrIrrJrKrrrLrMrNrOrPrQrrRrSrTrr~rzPThe keywords 'skip_footer' and 'max_rows' can not be specified at the same time.rz'max_rows' must be at least 1.r) MaskedArraymake_mask_descrzNThe input argument 'converter' should be a valid dictionary (got '%s' instead)rvTFrrzRfname must be a string, filehandle, list of strings, or generator. Got %s instead.)rrrOr~)rLrMrPrNrz"genfromtxt: Empty input file: "%s"r!r"cSsg|] }|qSr*rrrVr*r*r+r1szgenfromtxt..,cSsg|]}t|qSr*)r rrZr*r*r+r;scSsg|] }|qSr*rYrZr*r*r+r>s)rQrrLrMrPrNcsg|] }|qSr*r*rZ)descrr*r+rVscsg|] }|qSr*r*rZ)rr*r+rZsr*r}cSsg|]}tdgqSr)rFrZr*r*r+rescSsg|] }t|qSr*)r rZr*r*r+r{scSsg|]\}}td||dqS)N)rJdefaultrrmissfillr*r*r+rs)Z flatten_basecSs"g|]\}}}t|d||dqST)lockedrJr^r_)rrrarbr*r*r+rs cs g|]\}}td||dqSrcr_r`r@r*r+rs cSs"t|tkr||S||dSrrrr*r*r+rs z!genfromtxt..tobytes_firstr)rd testing_valuer^rJcsg|] }|qSr*r*rZrr*r+rscSsg|]\}}||kqSr*rY)rr0mr*r*r+rscsg|]}t|qSr*)r)r_mrr*r+r%sz0Converter #%i is locked and cannot be upgraded: z"(occurred line #%i for value '%s')z- Line #%%i (got %%i columns instead of %i)cs g|]}|dkr|qS)rr*rZ)nbrowsrHr*r+r:scsg|]\}}||fqSr*r*)rrnb)templater*r+rCszSome errors were detected !r+cs,g|]$\}fddtt|DqS)csg|]}|qSr*)Z _loose_callr_rrr*r+rYs)genfromtxt...r6rrrowsrr+rYscs,g|]$\}fddtt|DqS)csg|]}|qSr*)Z _strict_callrlrr*r+r]srnrorrprr+r]scSsg|] }|jqSr*rrr*r*r+rdscSsg|]\}}|tjkr|qSr*)rr)rrr0r*r*r+rfs zReading unicode strings without specifying the encoding argument is deprecated. Set the encoding, use None for the system default.cs,t|}D]}||d||<q t|Sr)rFrr)Zrow_tupr<r) strcolidxr*r+encode_unicode_colspsz'genfromtxt..encode_unicode_colscsg|] }|qSr*r*)rr)rtr*r+rwsc3s|]}t|VqdSr:rorr<rhr*r+rszgenfromtxt..cSsh|]\}}|jr|qSr*)Z_checked)rcZc_typer*r*r+ szgenfromtxt..csg|]\}}||fqSr*r*rrrrQr*r+rscsg|]\}}|tfqSr*rrzr{r*r+rsr@Ocss|] }|jVqdSr:)charrZr*r*r+rsz4Nested fields involving objects are not supported...cSsg|] }d|fqSr]r*rZr*r*r+rscSsg|] }dtfqSr]r|)rtr*r*r+rscSsg|] }|jqSr*rrrr*r*r+rsc3s|]}t|VqdSr:rvrwrhr*r+rscSsg|] }|tfqSr*r|rZr*r*r+rscsg|]}|dkr|qSr]r*rZrr*r+rscsg|] }|qSr*r*r )rGr*r+rs)O_genfromtxt_with_likerZnumpy.marWrXr rrrrrr rrrrrrclosingrrmrrrrrrrrr$r%rrDrFrorrrrr\rrrvdecoderyrrr_r^rrrrupdaterr IndexErrorZ iterupgraderr6rupgraderinsertrZVisibleDeprecationWarningUnicodeEncodeErrorrZ issubdtype charactermaxrrrNotImplementedErrorviewrJZ_maskrr )RrrrrrHrIrrJrKrrrLrMrNrOrPrQrrRrSrTrr~rrWrXr!r"raZfid_ctxZfhdrrZvalidate_namesZ first_valuesrZfvalZnbcolscurrentZuser_missing_valuesrErravalueentryZ user_valueZuser_filling_valuesnZ dtype_flatZzipitZ uc_updaterreZ user_convrZappend_to_rowsmasksZappend_to_masksinvalidZappend_to_invalidrZnbvalues converterZcurrent_columnerrmsgZ nbinvalidZnbinvalid_skippeddataZ column_typesZsized_column_typesZcol_typeZn_charsrZ uniform_typeZddtypeZmdtypeZ outputmaskZrowmasksZ ishomogeneousttypenameZmvalr*)rrQr\rrtrrrirGrqrHrsrkrr+r.s0@                                                                                           cKs$d|d<tjdtddt|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. FrRzGnp.ndfromtxt is a deprecated alias of np.genfromtxt, prefer the latter.r!r"r$r%r&r.rr)r*r*r+r/scKs$d|d<tjdtddt|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. TrRzGnp.mafromtxt is a deprecated alias of np.genfromtxt, prefer the latter.r!r"rrr*r*r+r0 scKsP|dd|dd}t|f|}|r@ddlm}||}n |tj}|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. rNrRFr MaskedRecords) setdefaultgetr.numpy.ma.mrecordsrrrrecarray)rr)rRrGrr*r*r+r1* s      cKst|dd|dd|dd|ddt|f|}|d d }|rdd d lm}||}n |tj}|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. rPrrTrr[rNrRFrr)rr.rrrrrr)rr)rGrRrr*r*r+r2J s         )NFTr|)NN)TT)TN) NNNNNNNNNN)NNNNNNN)r)r*r+rrr,N)N)NNNNNNNNNNNNNNNNNNNNNN)Tsysosrrrr$r;roperatorrrrcollections.abcrr rrrrrZ numpy.corerZnumpy.core.multiarrayr r Znumpy.core.overridesr r Znumpy.core._internalr Z_iotoolsrrrrrrrrrrrZ numpy.compatrrrrrrrr'__all__rZarray_function_dispatchr9rTrUr3rr4rr5rr6rrrrrr-r r(r,r7rUrsortedZdefaultdeletecharsr.rr/r0r1r2r*r*r*r+sV     4$ 1* *  J Q @ %! %  x b Z