B d%dZ7d&dZ8d'dZ9d?d(d)Z:d*d+Z;ed5dZ?e>> from numpy.lib.npyio import BagObj as BO >>> class BagDemo(object): ... 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||_dS)N)weakrefproxy_obj)selfobjr3B/opt/alt/python37/lib64/python3.7/site-packages/numpy/lib/npyio.py__init__FszBagObj.__init__cCs2yt|d|Stk r,t|YnXdS)Nr0)object__getattribute__KeyErrorAttributeError)r1keyr3r3r4r7JszBagObj.__getattribute__cCst|dS)z Enables dir(bagobj) to list the files in an NpzFile. This also enables tab-completion in an interpreter or IPython. r0)r6r7keys)r1r3r3r4__dir__PszBagObj.__dir__N)__name__ __module__ __qualname____doc__r5r7r<r3r3r3r4r-(sr-cOs2t|rt|}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. rNTZ allowZip64)rstrzipfileZZipFile)fileargskwargsrBr3r3r4zipfile_factoryYs rFc@sreZdZdZdddZddZd d Zd d Zd dZddZ ddZ ddZ ddZ ddZ ddZddZdS)NpzFilea 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: True 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 >>> npz.files ['y', 'x'] >>> 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]) FTNcCst|}||_g|_||_||_x:|jD]0}|drP|j|ddq,|j|q,W||_t ||_ |r|||_ nd|_ dS)Nz.npy) rFZnamelist_filesfiles allow_pickle pickle_kwargsendswithappendzipr-ffid)r1rQown_fidrKrLZ_zipxr3r3r4r5s    zNpzFile.__init__cCs|S)Nr3)r1r3r3r4 __enter__szNpzFile.__enter__cCs |dS)N)close)r1exc_type exc_value tracebackr3r3r4__exit__szNpzFile.__exit__cCs>|jdk r|jd|_|jdk r4|jd|_d|_dS)z" Close the file. N)rOrUrQrP)r1r3r3r4rUs    z NpzFile.closecCs |dS)N)rU)r1r3r3r4__del__szNpzFile.__del__cCsd}||jkrd}n||jkr*d}|d7}|r|j|}|ttj}||tjkr||j|}tj ||j |j dS|j|Sn t d|dS)Nrrz.npy)rKrLz%s is not a file in the archive) rIrJrOopenreadlenr MAGIC_PREFIXrU read_arrayrKrLr8)r1r:memberrmagicr3r3r4 __getitem__s"       zNpzFile.__getitem__cCs t|jS)N)iterrJ)r1r3r3r4__iter__szNpzFile.__iter__csfddjDS)zV Return a list of tuples, with each tuple (filename, array in file). csg|]}||fqSr3r3).0rP)r1r3r4 sz!NpzFile.items..)rJ)r1r3)r1r4itemssz NpzFile.itemsccs"x|jD]}|||fVqWdS)z8Generator that returns tuples (filename, array in file).N)rJ)r1rPr3r3r4 iteritemss zNpzFile.iteritemscCs|jS)z6Return files in the archive with a ``.npy`` extension.)rJ)r1r3r3r4r;sz NpzFile.keyscCs|S)z1Return an iterator over the files in the archive.)rd)r1r3r3r4iterkeysszNpzFile.iterkeyscCs |j|S)N)rJ __contains__)r1r:r3r3r4rjszNpzFile.__contains__)FTN)r=r>r?r@r5rTrYrUrZrbrdrgrhr;rirjr3r3r3r4rGhs=  rGTASCIIc Cs<d}t|trt|d}d}nt|r6|d}d}n|}|dkrJtdtjddkrft||d}ni}zd }tt j } | | } | t | t|  d | |r|} d}t|| ||d S| t j kr|rt j||d St j|||d Sn8|stdytj|f|Stdt|YnXWd|r6|XdS)a Load arrays or pickled objects from ``.npy``, ``.npz`` or pickled files. 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: True 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 on 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]) FrbT)rklatin1rz.encoding must be 'ASCII', 'latin1', or 'bytes'rr)encoding fix_importssPKr)rRrKrL)mode)rKrLz>allow_pickle=False, but file does not contain non-pickled dataz'Failed to interpret file %s as a pickleN) isinstancerr[r ValueErrorsys version_infodictr]rr^r\seekmin startswithrGZ open_memmapr_pickler'IOErrorreprrU) rCZ mmap_moderKrornrRrQrLZ _ZIP_PREFIXNratmpr3r3r4r' sJf         cCsd}t|tr0|ds |d}t|d}d}n8t|rd|jdsT|j|jd}|d}d}n|}tjddkrt |d}nd}z t |}t j ||||d Wd|r|XdS) 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 file name if it does not already have one. 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. arr : array_like Array data to be saved. See Also -------- savez : Save several arrays into a ``.npz`` archive savetxt, load Notes ----- For a description of the ``.npy`` format, see the module docstring of `numpy.lib.format` or the NumPy Enhancement Proposal http://docs.scipy.org/doc/numpy/neps/npy-format.html 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]) Fz.npywbTrr)roN)rKrL)rqrrMr[rnameparentrsrtrunp asanyarrayr write_arrayrU)rCZarrrKrorRrQrLr3r3r4r)s*3         cOst|||ddS)a 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 file name (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 file name 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 `numpy.lib.format` or the NumPy Enhancement Proposal http://docs.scipy.org/doc/numpy/neps/npy-format.html 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 -------- >>> 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_1', 'arr_0'] >>> 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) >>> npzfile.files ['y', 'x'] >>> npzfile['x'] array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) FN)_savez)rCrDkwdsr3r3r4r*sNcOst|||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 file names are arr_0, arr_1, etc. Parameters ---------- file : str or file Either the file name (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 file name 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 `numpy.lib.format` or the NumPy Enhancement Proposal http://docs.scipy.org/doc/numpy/neps/npy-format.html 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)rCrDrr3r3r4r+Ts=c Csddl}ddl}t|tr.|dsR|d}n$t|rR|jdsR|j|jd}|}x.floatconvcSs tt|S)N)boolint)rSr3r3r4z_getconv..cSs tt|S)N)rr)rSr3r3r4rrcSs tt|S)N)complexr)rSr3r3r4rrN) type issubclassrZbool_Zuint64Zint64ZintegerZ longdoubleZfloatingrZbytes_rr)dtypertypr3r3r4_getconvs&        r#Fc  sdk rNtttfr"tgnddDddDtd|} dk rbt|dk ry t|} Wntk r|g} YnXxN| D]F} y t | Wqtk r} zdt | f| _ Wdd} ~ XYqXqW| }d} yt |rt |}t|rd } |d r.d dl}t||}nP|d rRd dl}t||}n,tjd d krrtt|d}n tt|}nt|}Wntk rtdYnXgfddfddfdd}zt|}t|xt|D]}t|qWd}y"x|s*t|}||}qWWn0tk r^d}g}tj d|d dYnXt!|pj|}|\}}t!|dkrdd|D}n*fddt|D}|dkr|t"fg}xT| pi#D]B\}}|r y|$|}Wntk rwYnX|||<qWxt%t&'|g|D]\}}||t!d krNq,|rffdd|Dt!|kr||d}td|ddt(|D}||})|q,WWd| r|*Xt+|j,dkrj-dd d krd!_-|d"krtd#|j,|kr,t.j,|krd|dkrNt/n|d krdt0j1|rt!|dkrfd$d|j2DSj1SnSdS)%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 for Python 3k. 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, optional The characters or list of characters used to indicate the start of a comment; default: '#'. delimiter : str, optional The string used to separate values. By default, this is any whitespace. converters : dict, optional A dictionary mapping column number to a function that will convert that column to a float. 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; 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. .. versionadded:: 1.11.0 Also 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 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([('M', 21, 72.0), ('F', 35, 58.0)], 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.]) NcSsg|] }t|qSr3)r)recommentr3r3r4rfWszloadtxt..css|]}t|VqdS)N)reescape)rerr3r3r4 Zszloadtxt..|z\usecols must be an int or a sequence of ints but it contains at least one element of type %sFTz.gzrz.bz2Uz1fname must be a string, file handle, or generatorc s|jdkr|j}t|dkr(|jgdfS|dtfg}t|dkrvx2|jdddD]}||dd||fg}qTW|jgtt|j|fSnlg}g}xZ|jD]P}|j|\}}|\}} | ||j dkr| | q| t|| fqW||fSdS)z;Unpack a structured data-type, and produce re-packing info.Nrr) namesshaper]baselistrrZprodZfieldsextendndimrN) dtrpackingZdimtypesfieldtprZflat_dtZ flat_packing)flatten_dtype_internalr3r4rs&         z'loadtxt..flatten_dtype_internalcsz|dkr|dS|tkr t|S|tkr0t|Sd}g}x4|D],\}}||||||||7}q>Wt|SdS)z6Pack items into nested lists based on re-packing info.Nr)tuplerrN)rgrstartZretlengthZ subpacking) pack_itemsr3r4rs zloadtxt..pack_itemscsFt|}dk r&jt|ddd}|d}|r>|SgSdS)zChop off comments, strip, and split at delimiter. Note that although the file is opened as text, this function returns bytes. Nr)maxsplitrs )rrstrip)line)comments delimiterregex_commentsr3r4 split_lines  zloadtxt..split_linezloadtxt: Empty input file: "%s") stacklevelrcSsg|] }t|qSr3)r)rerr3r3r4rfscsg|]}qSr3r3)rer)defconvr3r4rfscsg|] }|qSr3r3)rer)valsr3r4rfsz"Wrong number of columns at line %dcSsg|]\}}||qSr3r3)reconvrr3r3r4rfsr)rr)rr)rrrz"Illegal value of ndmin keyword: %scsg|] }|qSr3r3)rer)Xr3r4rf s)3rqrrrrcompilejoinr TypeErroropindexrrDrrArrMgziprcZGzipFilebz2ZBZ2Filersrtr[rrrrrrangenext StopIterationwarningswarnr]rrgrr itertoolschainrOrNrUarrayrrsqueezeZ atleast_1d atleast_2dTr)rrrr convertersZskiprowsusecolsunpackZndminuser_convertersZusecols_as_listZcol_idxeZfownrfhrrrZ first_vals first_liner|Z dtype_typesrrrZline_numrgr3)rrrrrrrrr4r!sg                              %.18e  r# c Cst|trt|}t|}d}t|r.t|}t|rd}|drZddl} | |d} qt j ddkrtt|d} qt|d} nt |d r|} nt d z`t |}|jd kr|jjdkrt |j}d } qt|jj} n |jd } t |} t|ttfkr6t|| kr td t|t|tt|} nt|tr|d }t d|}|d kr| r|d||fg| }n |g| }||} n4| r|d| kr|n| s|| kr|n|} nt d|ft|dkr |dd|}| t!|||| rhx|D]L}g}x&|D]}|"|j#|"|j$q$W| t!| t||qWn\xZ|D]R}y| t!| t||Wn,t%k rt%dt|j| fYnXqnWt|dkr|dd|}| t!|||Wd|r | &XdS)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 : 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) a single specifier, `fmt='%.4e'`, resulting in numbers formatted like `' (%s+%sj)' % (fmt, fmt)` b) a full string specifying every real and imaginary part, e.g. `' %.4e %+.4ej %.4e %+.4ej %.4e %+.4ej'` for 3 columns c) 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 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 `_, 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 FTz.gzrNr~rrrz%fname must be a string or file handlerzfmt has wrong shape. %s%z'fmt has wrong number of %% formats: %sz (%s+%sj)rzinvalid fmt: %rrz?Mismatch between array dtype ('%s') and format specifier ('%s'))'rqrrrrArrMrr[rsrthasattrrrrZasarrayrrrrrr]descrrZ iscomplexobjrrrr9rrcountreplacerrrNrealimagrrU)rrZfmtrnewlineheaderZfooterrown_fhrrZncolZ iscomplex_XrZ n_fmt_charserrorrowZrow2Znumberr3r3r4r 'ss                    " cCsd}t|dst|d}d}zt|ds6tt|}t|tjsLt|}|| }|rt|dt st||j d}tj ||d}||_ntj ||d}|S|r| XdS) 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 File name 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. 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 `doc.structured_arrays`. 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([(1312L, 'foo'), (1534L, 'bar'), (444L, 'qux')], dtype=[('num', '>> output['num'] array([1312, 1534, 444], dtype=int64) Fr\rlTmatchr)rN)rr[rrrrqrrfindallr\rrrrU)rCZregexprrseqZnewdtypeoutputr3r3r4r,s$7     _zf%icIs<|dk r$|rtd|dkr$td|dk r4t|}t|trFt|}t|tttfr^t|}|rrddlm}m }|pxi}t|t st dt |d}ydt |rt|}t|trtjdd krttjj|d }nttjj|d }d }nt|}Wn&t k r"t d t |YnXt|||dj}t| | || d}xtD]t|qNWd}yNxH|st|}d kr||krd||dd}||}qhWWn0tk rd}g}tj d|d dYnXd kr |d!}||kr |d=| dk rnydd| dD} Wn@t"k rly t| } Wnt k rf| g} YnXYnXt#| px|} d kr|dd|Dd}n2t$r|dddDnr|dk rt%| | || ddk rt| rxJt&| D]>\}!t$|!r4'|!| <n|!dkr|!t#|| <qWdk rt#| krj(t)fdd| Dtj*n*dk rt#| krfdd| Dndk rdk rtj*|pd}"ddt| D}t|"t rx|"+D]\}#}$t$|#rNy'|#}#Wntk rLwYnX| rzy| '|#}#Wntk rxYnXt|$ttfrdd|$D}$n t|$g}$|#dkrx(|D]}%|%,|$qWn||#,|$qWnt|"ttfr(xt-|"|D]&\}&}'t|&}&|&|'kr|'.|&qWnRt|"t/rZ|"d}(x:|D]}'|',|(qDWn x|D]}'|',t|"gq`W|})|)dkrg})dg| }t|)t r$x|)+D]r\}#}$t$|#ry'|#}#Wntk rwYnX| ry| '|#}#Wntk rYnX|$||#<qWnHt|)ttfrbt#|)}*|*| krT|)|d|*<n |)d| }n |)g| }dkrddt-||D}nRt0d d }+t#|+dkrt-|+||},d!d|,D}nt-||},fd"d|,D}g}-x|+D]\}.t$|.r.y'|.}.|.Wntk r*wYnXn6| r`y| '|.Wntk r\wYnXn|.t#|rx||.}/nd}/|j1d |/||d#|-.fqW|1|-gj.}0|rg}1|1j.}2g}3|3j.}4xt&t23|g|D]\}5||5 t# }6|6dkrq| rfy fd$d| D Wn.t4k rb|4d|6fwYnXn"|6| kr|4d|6fq|0t |r|2td%dt- |Dt#|krPqW|r|5dk rxt&|D]\}7fd&dD}8y|76|8Wnt7k rd'}9t8t9}8xdt&|8D]X\}.}&y|7:|&Wn>t;tfk r|9d(7}9|9|.d|&f;}9t;|9YnX qHWYnXqWt#|3}:|:dk rft#|:|d)|  |dk rt#fd*d|3D};|3d|:|;}3||;8} fd+d|3D}9t#|9 rf|9x,|>D]$d2t>fd3d4|tCd;ntjA|<d8}Bn"tjA|d|DD]f\}F|k r |E|Fj kM}E|FtjEk rd2t>fd?d4|`_. Examples --------- >>> from io import StringIO >>> import numpy as np Comma delimited file with mixed dtype >>> s = StringIO("1,1.3,abcde") >>> data = np.genfromtxt(s, dtype=[('myint','i8'),('myfloat','f8'), ... ('mystring','S5')], delimiter=",") >>> data array((1, 1.3, '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, 'abcde'), dtype=[('myint', '>> s.seek(0) >>> data = np.genfromtxt(s, dtype="i8,f8,S5", ... names=['myint','myfloat','mystring'], delimiter=",") >>> data array((1, 1.3, 'abcde'), dtype=[('myint', '>> s = StringIO("11.3abcde") >>> data = np.genfromtxt(s, dtype=None, names=['intvar','fltvar','strvar'], ... delimiter=[1,3,5]) >>> data array((1, 1.3, 'abcde'), dtype=[('intvar', '.,cSsg|]}t|qSr3)rr)rerr3r3r4rfFscSsg|] }|qSr3)r)rerr3r3r4rfJs) defaultfmtrrrrrcsg|] }|qSr3r3)rer)rr3r4rfbscsg|] }|qSr3r3)rer)rr3r4rffsr3cSsg|]}tdgqS)r)r)rerr3r3r4rfoscSsg|] }t|qSr3)rA)rerr3r3r4rfs,cSsg|]\}}td||dqS)N)missing_valuesdefault)r)remissfillr3r3r4rfs)Z flatten_basecSs"g|]\}}}t|d||dqS)T)lockedrr)r)rerrrr3r3r4rfscs g|]\}}td||dqS)T)rrr)r)rerr)rr3r4rfs)r testing_valuerrcsg|] }|qSr3r3)rer)valuesr3r4rfscSsg|]\}}||kqSr3)r)revmr3r3r4rfscsg|]}t|qSr3)r)re_m)rr3r4rf&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)rr3)rer)nbrows skip_headerr3r4rf;scsg|]\}}||fqSr3r3)rerZnb)templater3r4rfDszSome errors were detected !rcs,g|]$\}fddtt|DqS)csg|]}|qSr3)Z _loose_call)re_r)rr3r4rfZsz)genfromtxt...)rr)rer)rows)rr4rfZscs,g|]$\}fddtt|DqS)csg|]}|qSr3)Z _strict_call)rer)rr3r4rf^sz)genfromtxt...)rr)rer)r)rr4rf^scSsg|] }|jqSr3)r)rerr3r3r4rfescSs&g|]\}}|tdtjfkr|qS)S)rrstring_)rerr r3r3r4rfgsz|S%ic3s|]}t|VqdS)N)r])rer)rr3r4rkszgenfromtxt..cSsg|]}|jr|jqSr3)Z_checkedr)recr3r3r4rfoscsg|]\}}||fqSr3r3)rerr)rr3r4rfsscsg|]\}}|tjfqSr3)rr)rerr)rr3r4rfvs)rOcss|] }|jVqdS)N)char)rerr3r3r4rsz4Nested fields involving objects are not supported...cSsg|] }d|fqS)rr3)rerr3r3r4rfscSsg|]}dtjfqS)r)rr)retr3r3r4rfscSsg|] }|jqSr3)r)rerr3r3r4rfsc3s|]}t|VqdS)N)r])rer)rr3r4rsrcSsg|]}|tjfqSr3)rr)rerr3r3r4rfscsg|]}|dkr|qS)rr3)rer)rr3r4rfs)JrrrrqrrrrZnumpy.marrrurrrrArrsrtrcrlib _datasourcer[r Z _handymanr rrrrrrrrr9r]rrrrrrrrgrrOrNrrupdaterr IndexErrorrUZ iterupgraderrrZupgraderinsertrmaxsetrrrNotImplementedErrorviewrrZ_maskrr)IrrrrrZ skip_footerrrZfilling_valuesrrrrrrrrrusemaskZlooseZ invalid_raiseZmax_rowsrrrZown_fhdZfhdrZvalidate_namesZ first_valuesrZfvalZnbcolsZcurrentZuser_missing_valuesr:rrvalueentryZ user_valueZuser_filling_valuesnZ dtype_flatZzipitZ uc_updatejr Zappend_to_rowsZmasksZappend_to_masksZinvalidZappend_to_invalidrZnbvaluesZ converterZcurrent_columnerrmsgZ nbinvalidZnbinvalid_skippeddataZ column_typesZ strcolidxrZddtypeZmdtyperZ outputmaskZrowmasksZ ishomogeneousZttyperZmvalr3) rrrrrrrrrrr r4r"Ks"                                                                           $              $  cKsd|d<t|f|S)z Load ASCII data stored in a file and return it as a single array. Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function. Fr")r")rrEr3r3r4r#s cKsd|d<t|f|S)a Load ASCII data stored in a text file and return a masked array. Parameters ---------- fname, kwargs : For a description of input parameters, see `genfromtxt`. See Also -------- numpy.genfromtxt : generic function to load ASCII data. Tr")r")rrEr3r3r4r$s cKsP|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. rNr"Fr) MaskedRecords) setdefaultgetr"numpy.ma.mrecordsr)r!rrecarray)rrEr"rr)r3r3r4r%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. rrrTrrrNr"Fr)r))r*r"r+r,r)r!rr-)rrErr"r)r3r3r4r& s         )NTTrk)TT)TN)rrrrrr)EZ __future__rrrrsrrrrr.operatorrrrZnumpyrrrrr Znumpy.core.multiarrayr r Z_iotoolsr r rrrrrrrrrZ numpy.compatrrrrrrrrtryZcPickleZfuture_builtinsrr(__all__r6r-rFrGr'r)r*r+rrrr!r r,r"r#r$r%r&r3r3r3r4sr  4$    1# ) PQ@ : ; LX{