mpi4py 并行讀/寫 numpy npy 文件的方法

上一篇中我們介紹了 mpi4py 中獲得高性能 I/O 的方法和建議,下面我們將介紹 mpi4py 并行讀/寫 numpy npy 文件的方法。

在使用 mpi4py 寫并行計(jì)算程序時(shí)經(jīng)常涉及到對(duì) numpy 數(shù)組的操作,常用的操作是將一個(gè)大的 numpy 數(shù)組按照某種特定的方式分布到各個(gè) MPI 進(jìn)程中進(jìn)行并行處理。在某些時(shí)候可能需要將這個(gè)數(shù)組存儲(chǔ)到文件中,無論只是為了保存中間數(shù)據(jù)作為 checkpoint 或保存最后結(jié)果以做進(jìn)一步分析用。numpy 中將數(shù)組存儲(chǔ)到文件所使用的標(biāo)準(zhǔn)文件格式是 npy 文件。它是一種進(jìn)行 numpy 數(shù)組存儲(chǔ)的非常方便的文件格式,numpy 提供一些方法方便地將一個(gè)數(shù)組存儲(chǔ)到一個(gè) npy 文件中并且能夠從中完全地恢復(fù)該 numpy 數(shù)組。不過 numpy 本身并不支持將分布在多個(gè) MPI 進(jìn)程中的 numpy 數(shù)組直接地寫入一個(gè) npy 文件。一種方式是每個(gè)進(jìn)程將其本地子數(shù)組寫入一個(gè)單獨(dú)的 npy 文件。但是這在某些情況下并不方便,比如說 MPI 程序想以一種不同的分布方式從這些 npy 文件中重新讀入數(shù)據(jù)時(shí)。一種更方便的方式是各個(gè) MPI 進(jìn)程將其本地子數(shù)組并行地寫入一個(gè)共同的 noy 文件。我們可以有多種方式,比如說可以先將分布在各個(gè)進(jìn)程中的數(shù)據(jù)收集到一個(gè)進(jìn)程中,然后由這個(gè)進(jìn)程將這個(gè)整體的數(shù)組存儲(chǔ)到文件中。但這是一種非常低效的操作方式,我們完全可以使用前面介紹過的并行 I/O 操作將這個(gè)數(shù)組并行地寫入文件。前面已經(jīng)介紹過 mpi4py 中讀/寫文件中數(shù)組的方法,不過我們一直使用的是普通的二進(jìn)制文件,僅僅只包含數(shù)組的數(shù)據(jù),沒有添加其它任何額外的信息,如數(shù)組的 shape,排列方式等,而 numpy npy 文件是包含這些恢復(fù)數(shù)組所需的必要信息的。從 npy 文件中讀取數(shù)據(jù)并恢復(fù)成一個(gè)分布在各個(gè) MPI 進(jìn)程上的 numpy 數(shù)組是一個(gè)逆操作,我們也希望能以一種并行的方式高效地完成這種操作。在下面我們將首先介紹 npy 文件的存儲(chǔ)格式,然后介紹使用 mpi4py 并行讀寫 npy 文件的方法。

注意:將數(shù)組并行存入文件或從文件中并行讀取數(shù)組的另一種常用方式是使用并行的 HDF5??梢栽?mpi4py 中使用并行的 h5py 完成并行 HDF5 文件操作,這在前面作過相應(yīng)的介紹。

npy 文件簡介

numpy npy 文件是一種將 numpy 數(shù)組存儲(chǔ)到硬盤并包含所存儲(chǔ)數(shù)組的全部信息的一種文件格式,它是一種二進(jìn)制文件,是 numpy 存儲(chǔ)數(shù)組的標(biāo)準(zhǔn)格式。在 npy 文件的頭部(header)中紀(jì)錄了包括數(shù)組的 shape,dtype 和存儲(chǔ)順序等必要信息,允許在不同的應(yīng)用甚至不同的主機(jī)環(huán)境中正確讀取并重構(gòu)存儲(chǔ)在文件中的數(shù)組。

一個(gè) numpy 數(shù)組是以 native 的二進(jìn)制格式存儲(chǔ)在 noy 文件中的,即數(shù)組在 npy 文件中與其在內(nèi)存中有相同的表示方式。因此數(shù)組在存儲(chǔ)到 npy 文件或是讀取到內(nèi)存的過程中都不需要進(jìn)行類型轉(zhuǎn)換,避免數(shù)據(jù)精度損失。

對(duì) npy 文件更詳細(xì)的介紹可用參見這里。

npy 文件格式

版本 1.0

版本 1.0 的 npy 文件的數(shù)據(jù)格式如下:

  • 前 6 字節(jié)是一個(gè) magic string: "\x93NUMPY"。
  • 接下來的一個(gè)字節(jié)是主版本號(hào),如 "\x01"。
  • 接下來的一個(gè)字節(jié)是次版本號(hào),如 "\x00"。
  • 接下來的 2 個(gè)字節(jié)構(gòu)成一個(gè)小端無符號(hào)短整型數(shù)表示文件 header 的長度 HEADER_LEN。
  • 接下來 HEADER_LEN 個(gè)字節(jié)是用來描述數(shù)組信息的 header。它是一個(gè) Python 字典的 ASCII 字符串表示,由一個(gè)換行符 "\n" 結(jié)尾,并在 "\n" 之前有一定數(shù)目的空格 padding。

字典中包含以下描述數(shù)組信息的鍵:

"descr": dtype.descr。可以傳遞給 numpy.dtype() 創(chuàng)建該數(shù)組的 dtype 的描述字符串。
"fortran_order": bool。True 或者 False 表明是 Fortran 排列方式或 C 排列方式。
"shape": tuple of int。數(shù)組的 shape。

  • 接下來就是數(shù)組的 native 二進(jìn)制數(shù)據(jù)。如果數(shù)組的 dtype 包含 Python 對(duì)象(即 dtype.hasobject == True),則存儲(chǔ)在 npy 文件中的是數(shù)組的 pickle 化表示,否則是數(shù)組本身的連續(xù)字節(jié)序列。

版本 2.0

版本 1.0 只允許在 header 中最多存儲(chǔ) 65536 字節(jié)的信息,版本 2.0 將這一限制擴(kuò)展到了 4 GB。如果描述 數(shù)組的 header 信息超過版本 1.0 的限制,numpy 會(huì)自動(dòng)將數(shù)據(jù)存為版本 2.0,否則會(huì)使用兼容性更好的版本 1.0。

npy 文件的具體實(shí)現(xiàn)見這里的代碼

numpy npy 文件操作方法

numpy 中將數(shù)組存儲(chǔ)到 noy 文件中及從 npy 文件中恢復(fù)數(shù)組的最主要兩個(gè)方法如下:

numpy.save(file, arr, allow_pickle=True, fix_imports=True)

將一個(gè)數(shù)組存儲(chǔ)為一個(gè) numpy npy 格式的二進(jìn)制文件。

numpy.load(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding='ASCII')

從一個(gè) npy,npz 或 pickle 文件中加載 numpy 數(shù)組。

這兩個(gè)函數(shù)的參數(shù)介紹和使用方法請(qǐng)參考 numpy 相關(guān)文檔。

mpi4py 并行讀/寫 npy 文件

從前面的介紹中可以看出,除了文件前面的 magic string 及 header 等內(nèi)容需要特別地加以注意之外,數(shù)組本身在 npy 文件中的存儲(chǔ)并無特別之處,完全可以使用我們前面介紹的并行 I/O 方法進(jìn)行并行讀/寫操作。

并行寫入數(shù)組的步驟

  1. 創(chuàng)建并打開一個(gè) npy 文件。
  2. 由某個(gè)進(jìn)程(如 process 0)構(gòu)造 npy 文件前面的 magic string 及 header 等信息并將其寫入文件中。注意 header 中的 shape 應(yīng)該是整體數(shù)組的 shape,而非該進(jìn)程本地子數(shù)組的 shape。
  3. 各個(gè)進(jìn)程移動(dòng)其獨(dú)立文件指針至文件當(dāng)前的末尾位置。
  4. 根據(jù)數(shù)組的數(shù)據(jù)類型和在各個(gè)進(jìn)程中的分布方式創(chuàng)建 etype 和 filetype,并設(shè)置文件視圖。
  5. 各個(gè)進(jìn)程將本地子數(shù)組并行寫入文件,盡量采用集合寫操作以提高 I/O 性能。
  6. 關(guān)閉文件。

并行讀取數(shù)組的步驟

  1. 打開一個(gè) npy 文件。
  2. 各個(gè)進(jìn)程讀取位于文件前面的相應(yīng)數(shù)據(jù)以確定文件所使用的版本及 header 的長度。
  3. 各個(gè)進(jìn)程讀取 header 并解析數(shù)組的 shape,dtype 和排列順序等信息。
  4. 根據(jù)數(shù)組的 shape,dtype 及數(shù)組將要在各個(gè)進(jìn)程上的分布方式預(yù)先分配本地子數(shù)組數(shù)據(jù)緩沖區(qū)。
  5. 根據(jù)數(shù)組的數(shù)據(jù)類型和在各個(gè)進(jìn)程中的分布方式創(chuàng)建 etype 和 filetype,并設(shè)置文件視圖。
  6. 各個(gè)進(jìn)程并行地從文件中讀取數(shù)據(jù)到本地子數(shù)組的數(shù)據(jù)緩沖區(qū),盡量采用集合讀操作以提高 I/O 性能。
  7. 關(guān)閉文件。

例程

下面給出例程。下面的 format.py 文件是由 numpy 的 npy 格式實(shí)現(xiàn)做了一些小的改動(dòng)得到。在 npy_io.py 中的函數(shù) parallel_read_array 和 parallel_write_array 實(shí)現(xiàn)了并行讀/寫 npy 文件中一個(gè)按照某個(gè)軸(行、列等)分布在各個(gè) MPI 進(jìn)程上的 nympy 數(shù)組的功能。注意:此實(shí)現(xiàn)只支持按 C 數(shù)組順序存放且 dtype 中不包含 Python 對(duì)象的數(shù)組。對(duì)更一般的情況,根據(jù)前面對(duì)并行 I/O 及對(duì) noy 文件格式的相關(guān)介紹,讀者應(yīng)該不難實(shí)現(xiàn)。

# format.py

"""
Binary serialization

NPY format
==========

A simple format for saving numpy arrays to disk with the full
information about them.

The ``.npy`` format is the standard binary file format in NumPy for
persisting a *single* arbitrary NumPy array on disk. The format stores all
of the shape and dtype information necessary to reconstruct the array
correctly even on another machine with a different architecture.
The format is designed to be as simple as possible while achieving
its limited goals.

The ``.npz`` format is the standard format for persisting *multiple* NumPy
arrays on disk. A ``.npz`` file is a zip file containing multiple ``.npy``
files, one for each array.

Capabilities
------------

- Can represent all NumPy arrays including nested record arrays and
  object arrays.

- Represents the data in its native binary form.

- Supports Fortran-contiguous arrays directly.

- Stores all of the necessary information to reconstruct the array
  including shape and dtype on a machine of a different
  architecture.  Both little-endian and big-endian arrays are
  supported, and a file with little-endian numbers will yield
  a little-endian array on any machine reading the file. The
  types are described in terms of their actual sizes. For example,
  if a machine with a 64-bit C "long int" writes out an array with
  "long ints", a reading machine with 32-bit C "long ints" will yield
  an array with 64-bit integers.

- Is straightforward to reverse engineer. Datasets often live longer than
  the programs that created them. A competent developer should be
  able to create a solution in their preferred programming language to
  read most ``.npy`` files that he has been given without much
  documentation.

- Allows memory-mapping of the data. See `open_memmep`.

- Can be read from a filelike stream object instead of an actual file.

- Stores object arrays, i.e. arrays containing elements that are arbitrary
  Python objects. Files with object arrays are not to be mmapable, but
  can be read and written to disk.

Limitations
-----------

- Arbitrary subclasses of numpy.ndarray are not completely preserved.
  Subclasses will be accepted for writing, but only the array data will
  be written out. A regular numpy.ndarray object will be created
  upon reading the file.

.. warning::

  Due to limitations in the interpretation of structured dtypes, dtypes
  with fields with empty names will have the names replaced by 'f0', 'f1',
  etc. Such arrays will not round-trip through the format entirely
  accurately. The data is intact; only the field names will differ. We are
  working on a fix for this. This fix will not require a change in the
  file format. The arrays with such structures can still be saved and
  restored, and the correct dtype may be restored by using the
  ``loadedarray.view(correct_dtype)`` method.

File extensions
---------------

We recommend using the ``.npy`` and ``.npz`` extensions for files saved
in this format. This is by no means a requirement; applications may wish
to use these file formats but use an extension specific to the
application. In the absence of an obvious alternative, however,
we suggest using ``.npy`` and ``.npz``.

Version numbering
-----------------

The version numbering of these formats is independent of NumPy version
numbering. If the format is upgraded, the code in `numpy.io` will still
be able to read and write Version 1.0 files.

Format Version 1.0
------------------

The first 6 bytes are a magic string: exactly ``\\x93NUMPY``.

The next 1 byte is an unsigned byte: the major version number of the file
format, e.g. ``\\x01``.

The next 1 byte is an unsigned byte: the minor version number of the file
format, e.g. ``\\x00``. Note: the version of the file format is not tied
to the version of the numpy package.

The next 2 bytes form a little-endian unsigned short int: the length of
the header data HEADER_LEN.

The next HEADER_LEN bytes form the header data describing the array's
format. It is an ASCII string which contains a Python literal expression
of a dictionary. It is terminated by a newline (``\\n``) and padded with
spaces (``\\x20``) to make the total of
``len(magic string) + 2 + len(length) + HEADER_LEN`` be evenly divisible
by 64 for alignment purposes.

The dictionary contains three keys:

    "descr" : dtype.descr
      An object that can be passed as an argument to the `numpy.dtype`
      constructor to create the array's dtype.
    "fortran_order" : bool
      Whether the array data is Fortran-contiguous or not. Since
      Fortran-contiguous arrays are a common form of non-C-contiguity,
      we allow them to be written directly to disk for efficiency.
    "shape" : tuple of int
      The shape of the array.

For repeatability and readability, the dictionary keys are sorted in
alphabetic order. This is for convenience only. A writer SHOULD implement
this if possible. A reader MUST NOT depend on this.

Following the header comes the array data. If the dtype contains Python
objects (i.e. ``dtype.hasobject is True``), then the data is a Python
pickle of the array. Otherwise the data is the contiguous (either C-
or Fortran-, depending on ``fortran_order``) bytes of the array.
Consumers can figure out the number of bytes by multiplying the number
of elements given by the shape (noting that ``shape=()`` means there is
1 element) by ``dtype.itemsize``.

Format Version 2.0
------------------

The version 1.0 format only allowed the array header to have a total size of
65535 bytes.  This can be exceeded by structured arrays with a large number of
columns.  The version 2.0 format extends the header size to 4 GiB.
`numpy.save` will automatically save in 2.0 format if the data requires it,
else it will always use the more compatible 1.0 format.

The description of the fourth element of the header therefore has become:
"The next 4 bytes form a little-endian unsigned int: the length of the header
data HEADER_LEN."

Notes
-----
The ``.npy`` format, including motivation for creating it and a comparison of
alternatives, is described in the `"npy-format" NEP
<https://www.numpy.org/neps/nep-0001-npy-format.html>`_, however details have
evolved with time and this document is more current.

"""
from __future__ import division, absolute_import, print_function

import numpy
import sys
import io
import warnings
from numpy.lib.utils import safe_eval
from numpy.compat import asbytes, asstr, isfileobj, long, basestring

if sys.version_info[0] >= 3:
    import pickle
else:
    import cPickle as pickle


MAGIC_PREFIX = b'\x93NUMPY'
MAGIC_LEN = len(MAGIC_PREFIX) + 2
ARRAY_ALIGN = 64 # plausible values are powers of 2 between 16 and 4096
BUFFER_SIZE = 2**18  # size of buffer for reading npz files in bytes

# difference between version 1.0 and 2.0 is a 4 byte (I) header length
# instead of 2 bytes (H) allowing storage of large structured arrays

def _check_version(version):
    if version not in [(1, 0), (2, 0), None]:
        msg = "we only support format version (1,0) and (2, 0), not %s"
        raise ValueError(msg % (version,))

def magic(major, minor):
    """ Return the magic string for the given file format version.

    Parameters
    ----------
    major : int in [0, 255]
    minor : int in [0, 255]

    Returns
    -------
    magic : str

    Raises
    ------
    ValueError if the version cannot be formatted.
    """
    if major < 0 or major > 255:
        raise ValueError("major version must be 0 <= major < 256")
    if minor < 0 or minor > 255:
        raise ValueError("minor version must be 0 <= minor < 256")
    if sys.version_info[0] < 3:
        return MAGIC_PREFIX + chr(major) + chr(minor)
    else:
        return MAGIC_PREFIX + bytes([major, minor])

def read_magic(fp):
    """ Read the magic string to get the version of the file format.

    Parameters
    ----------
    fp : filelike object

    Returns
    -------
    major : int
    minor : int
    """
    magic_str = _read_bytes(fp, MAGIC_LEN, "magic string")
    if magic_str[:-2] != MAGIC_PREFIX:
        msg = "the magic string is not correct; expected %r, got %r"
        raise ValueError(msg % (MAGIC_PREFIX, magic_str[:-2]))
    if sys.version_info[0] < 3:
        major, minor = map(ord, magic_str[-2:])
    else:
        major, minor = magic_str[-2:]
    return major, minor

def dtype_to_descr(dtype):
    """
    Get a serializable descriptor from the dtype.

    The .descr attribute of a dtype object cannot be round-tripped through
    the dtype() constructor. Simple types, like dtype('float32'), have
    a descr which looks like a record array with one field with '' as
    a name. The dtype() constructor interprets this as a request to give
    a default name.  Instead, we construct descriptor that can be passed to
    dtype().

    Parameters
    ----------
    dtype : dtype
        The dtype of the array that will be written to disk.

    Returns
    -------
    descr : object
        An object that can be passed to `numpy.dtype()` in order to
        replicate the input dtype.

    """
    if dtype.names is not None:
        # This is a record array. The .descr is fine.  XXX: parts of the
        # record array with an empty name, like padding bytes, still get
        # fiddled with. This needs to be fixed in the C implementation of
        # dtype().
        return dtype.descr
    else:
        return dtype.str

def header_data_from_array_1_0(array):
    """ Get the dictionary of header metadata from a numpy.ndarray.

    Parameters
    ----------
    array : numpy.ndarray

    Returns
    -------
    d : dict
        This has the appropriate entries for writing its string representation
        to the header of the file.
    """
    d = {'shape': array.shape}
    if array.flags.c_contiguous:
        d['fortran_order'] = False
    elif array.flags.f_contiguous:
        d['fortran_order'] = True
    else:
        # Totally non-contiguous data. We will have to make it C-contiguous
        # before writing. Note that we need to test for C_CONTIGUOUS first
        # because a 1-D array is both C_CONTIGUOUS and F_CONTIGUOUS.
        d['fortran_order'] = False

    d['descr'] = dtype_to_descr(array.dtype)
    return d

def _write_array_header(fp, d, version=None):
    """ Write the header for an array and returns the version used

    Parameters
    ----------
    fp : filelike object
    d : dict
        This has the appropriate entries for writing its string representation
        to the header of the file.
    version: tuple or None
        None means use oldest that works
        explicit version will raise a ValueError if the format does not
        allow saving this data.  Default: None
    Returns
    -------
    version : tuple of int
        the file version which needs to be used to store the data
    """
    import struct
    header = ["{"]
    for key, value in sorted(d.items()):
        # Need to use repr here, since we eval these when reading
        header.append("'%s': %s, " % (key, repr(value)))
    header.append("}")
    header = "".join(header)
    header = asbytes(_filter_header(header))

    hlen = len(header) + 1 # 1 for newline
    padlen_v1 = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize('<H') + hlen) % ARRAY_ALIGN)
    padlen_v2 = ARRAY_ALIGN - ((MAGIC_LEN + struct.calcsize('<I') + hlen) % ARRAY_ALIGN)

    # Which version(s) we write depends on the total header size; v1 has a max of 65535
    if hlen + padlen_v1 < 2**16 and version in (None, (1, 0)):
        version = (1, 0)
        header_prefix = magic(1, 0) + struct.pack('<H', hlen + padlen_v1)
        topad = padlen_v1
    elif hlen + padlen_v2 < 2**32 and version in (None, (2, 0)):
        version = (2, 0)
        header_prefix = magic(2, 0) + struct.pack('<I', hlen + padlen_v2)
        topad = padlen_v2
    else:
        msg = "Header length %s too big for version=%s"
        msg %= (hlen, version)
        raise ValueError(msg)

    # Pad the header with spaces and a final newline such that the magic
    # string, the header-length short and the header are aligned on a
    # ARRAY_ALIGN byte boundary.  This supports memory mapping of dtypes
    # aligned up to ARRAY_ALIGN on systems like Linux where mmap()
    # offset must be page-aligned (i.e. the beginning of the file).
    header = header + b' '*topad + b'\n'

    fp.Write(header_prefix)
    fp.Write(header)
    return version

def write_array_header_1_0(fp, d):
    """ Write the header for an array using the 1.0 format.

    Parameters
    ----------
    fp : filelike object
    d : dict
        This has the appropriate entries for writing its string
        representation to the header of the file.
    """
    _write_array_header(fp, d, (1, 0))


def write_array_header_2_0(fp, d):
    """ Write the header for an array using the 2.0 format.
        The 2.0 format allows storing very large structured arrays.

    .. versionadded:: 1.9.0

    Parameters
    ----------
    fp : filelike object
    d : dict
        This has the appropriate entries for writing its string
        representation to the header of the file.
    """
    _write_array_header(fp, d, (2, 0))

def read_array_header_1_0(fp):
    """
    Read an array header from a filelike object using the 1.0 file format
    version.

    This will leave the file object located just after the header.

    Parameters
    ----------
    fp : filelike object
        A file object or something with a `.read()` method like a file.

    Returns
    -------
    shape : tuple of int
        The shape of the array.
    fortran_order : bool
        The array data will be written out directly if it is either
        C-contiguous or Fortran-contiguous. Otherwise, it will be made
        contiguous before writing it out.
    dtype : dtype
        The dtype of the file's data.

    Raises
    ------
    ValueError
        If the data is invalid.

    """
    return _read_array_header(fp, version=(1, 0))

def read_array_header_2_0(fp):
    """
    Read an array header from a filelike object using the 2.0 file format
    version.

    This will leave the file object located just after the header.

    .. versionadded:: 1.9.0

    Parameters
    ----------
    fp : filelike object
        A file object or something with a `.read()` method like a file.

    Returns
    -------
    shape : tuple of int
        The shape of the array.
    fortran_order : bool
        The array data will be written out directly if it is either
        C-contiguous or Fortran-contiguous. Otherwise, it will be made
        contiguous before writing it out.
    dtype : dtype
        The dtype of the file's data.

    Raises
    ------
    ValueError
        If the data is invalid.

    """
    return _read_array_header(fp, version=(2, 0))


def _filter_header(s):
    """Clean up 'L' in npz header ints.

    Cleans up the 'L' in strings representing integers. Needed to allow npz
    headers produced in Python2 to be read in Python3.

    Parameters
    ----------
    s : byte string
        Npy file header.

    Returns
    -------
    header : str
        Cleaned up header.

    """
    import tokenize
    if sys.version_info[0] >= 3:
        from io import StringIO
    else:
        from StringIO import StringIO

    tokens = []
    last_token_was_number = False
    # adding newline as python 2.7.5 workaround
    string = asstr(s) + "\n"
    for token in tokenize.generate_tokens(StringIO(string).readline):
        token_type = token[0]
        token_string = token[1]
        if (last_token_was_number and
                token_type == tokenize.NAME and
                token_string == "L"):
            continue
        else:
            tokens.append(token)
        last_token_was_number = (token_type == tokenize.NUMBER)
    # removing newline (see above) as python 2.7.5 workaround
    return tokenize.untokenize(tokens)[:-1]


def _read_array_header(fp, version):
    """
    see read_array_header_1_0
    """
    # Read an unsigned, little-endian short int which has the length of the
    # header.
    import struct
    if version == (1, 0):
        hlength_type = '<H'
    elif version == (2, 0):
        hlength_type = '<I'
    else:
        raise ValueError("Invalid version %r" % version)

    hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), "array header length")
    header_length = struct.unpack(hlength_type, hlength_str)[0]
    header = _read_bytes(fp, header_length, "array header")

    # The header is a pretty-printed string representation of a literal
    # Python dictionary with trailing newlines padded to a ARRAY_ALIGN byte
    # boundary. The keys are strings.
    #   "shape" : tuple of int
    #   "fortran_order" : bool
    #   "descr" : dtype.descr
    header = _filter_header(header)
    try:
        d = safe_eval(header)
    except SyntaxError as e:
        msg = "Cannot parse header: %r\nException: %r"
        raise ValueError(msg % (header, e))
    if not isinstance(d, dict):
        msg = "Header is not a dictionary: %r"
        raise ValueError(msg % d)
    keys = sorted(d.keys())
    if keys != ['descr', 'fortran_order', 'shape']:
        msg = "Header does not contain the correct keys: %r"
        raise ValueError(msg % (keys,))

    # Sanity-check the values.
    if (not isinstance(d['shape'], tuple) or
            not numpy.all([isinstance(x, (int, long)) for x in d['shape']])):
        msg = "shape is not valid: %r"
        raise ValueError(msg % (d['shape'],))
    if not isinstance(d['fortran_order'], bool):
        msg = "fortran_order is not a valid bool: %r"
        raise ValueError(msg % (d['fortran_order'],))
    try:
        dtype = numpy.dtype(d['descr'])
    except TypeError as e:
        msg = "descr is not a valid dtype descriptor: %r"
        raise ValueError(msg % (d['descr'],))

    return d['shape'], d['fortran_order'], dtype


def _read_bytes(fp, size, error_template="ran out of data"):
    """
    Read from file-like object until size bytes are read.
    Raises ValueError if not EOF is encountered before size bytes are read.
    Non-blocking objects only supported if they derive from io objects.

    Required as e.g. ZipExtFile in python 2.6 can return less data than
    requested.
    """
    data = bytes()
    while True:
        # io files (default in python3) return None or raise on
        # would-block, python2 file will truncate, probably nothing can be
        # done about that.  note that regular files can't be non-blocking
        try:
            # r = fp.read(size - len(data))
            r = bytearray(size-len(data))
            fp.Read(r)
            data = bytes(r)
            if len(r) == 0 or len(data) == size:
                break
        except io.BlockingIOError:
            pass
    if len(data) != size:
        msg = "EOF: reading %s, expected %d bytes got %d"
        raise ValueError(msg % (error_template, size, len(data)))
    else:
        return data
# npy_io.py

"""
Demonstrates how to use mpi4py to write/read numpy array to/from npy file.

Run this with 2 processes like:
$ mpiexec -n 2 python npy_io.py
"""

import warnings
import numpy as np
import format as fm
from mpi4py import MPI


comm = MPI.COMM_WORLD
rank = comm.Get_rank()

def typemap(dtype):
    """Map a numpy dtype into an MPI_Datatype.

    Parameters
    ----------
    dtype : np.dtype
        The numpy datatype.

    Returns
    -------
    mpitype : MPI.Datatype
        The MPI.Datatype.

    """
    # Need to try both as the name of the typedoct changed in mpi4py 2.0
    try:
        return MPI.__TypeDict__[np.dtype(dtype).char]
    except AttributeError:
        return MPI._typedict[np.dtype(dtype).char]


def parallel_write_array(filename, local_array, axis=0, version=None, comm=None):
    """
    Parallelly write an array distributed in all processes to an NPY file, including a header.

    Parameters
    ----------
    filename : str
        Name of the file to write array into.
    local_array : ndarray
        The subarray local to this process that will be writen to disk.
    axis : int
        The axis that the array is distributed on.
    version : (int, int) or None, optional
        The version number of the format. None means use the oldest
        supported version that is able to store the data.  Default: None
    comm : mpi4py communicator or None.
        A valid mpi4py communicator or None if no MPI.

    """

    # if no MPI, or only 1 MPI process, call np.save directly
    if comm is None or comm.size == 1:
        np.save(filename, local_array)
        return

    if local_array.dtype.hasobject:
        # contain Python objects
        raise RuntimeError('Currently not support array that contains Python objects')
    if local_array.flags.f_contiguous and not local_array.flags.c_contiguous:
        raise RuntimeError('Currently not support Fortran ordered array')

    local_shape = local_array.shape # shape of local_array
    local_axis_len = local_shape[axis]
    local_axis_lens = comm.allgather(local_axis_len)
    global_axis_len = sum(local_axis_lens)
    global_shape = list(local_shape)
    global_shape[axis] = global_axis_len
    global_shape = tuple(global_shape) # shape of global array
    local_start = [0] * len(global_shape)
    local_start[axis] = np.cumsum([0] + local_axis_lens)[comm.rank] # start of local_array in global array

    # open the file in write only mode
    fh = MPI.File.Open(comm, filename, amode=MPI.MODE_CREATE | MPI.MODE_WRONLY)

    # check validity of version
    fm._check_version(version)
    # first write the array header to file by process 0
    if comm.rank == 0:
        # get the header, which is a dict
        header = fm.header_data_from_array_1_0(local_array)
        # update the shape value to shape of the global array
        header['shape'] = global_shape
        # write header to file
        used_ver = fm._write_array_header(fh, header, version)
        # this warning can be removed when 1.9 has aged enough
        if version != (2, 0) and used_ver == (2, 0):
            warnings.warn("Stored array in format 2.0. It can only be"
                        "read by NumPy >= 1.9", UserWarning, stacklevel=2)

        # get the position of the individual file pointer,
        # which is now at the end of the file
        pos = fh.Get_position()
    else:
        pos = 0

    # broadcast the end position of the file to all processes
    pos = comm.bcast(pos, root=0)

    # get the etype
    etype = typemap(local_array.dtype)

    # construct the filetype
    filetype = etype.Create_subarray(global_shape, local_shape, local_start, order=MPI.ORDER_C)
    filetype.Commit()

    # set the file view
    fh.Set_view(pos, etype, filetype, datarep='native')

    # collectively write the array to file
    fh.Write_all(local_array)

    # close the file
    fh.Close()


def parallel_read_array(filename, axis=0, comm=None):
    """
    Parallelly read an array from an NPY file, each process reads its own part.

    Parameters
    ----------
    filename : str
        Name of the file constains the array.
    axis : int
        The axis to distribute the array on each process.
    comm : mpi4py communicator or None.
        A valid mpi4py communicator or None if no MPI.

    Returns
    -------
    local_array : ndarray
        The array local to this process from the data on disk.

    """

    # if no MPI, or only 1 MPI process, call np.load directly
    if comm is None or comm.size == 1:
        return np.load(filename)

    # open the file in read only mode
    fh = MPI.File.Open(comm, filename, amode=MPI.MODE_RDONLY)

    # read and check version of the npy file
    version = fm.read_magic(fh)
    fm._check_version(version)
    # get shape, order, dtype info of the array
    global_shape, fortran_order, dtype = fm._read_array_header(fh, version)

    if dtype.hasobject:
        # contain Python objects
        raise RuntimeError('Currently not support array that contains Python objects')
    if fortran_order:
        raise RuntimeError('Currently not support Fortran ordered array')

    local_shape = list(global_shape)
    axis_len = local_shape[axis]
    base = axis_len / comm.size
    rem = axis_len % comm.size
    part = base * np.ones(comm.size, dtype=np.int) + (np.arange(comm.size) < rem).astype(np.int)
    bound = np.cumsum(np.insert(part, 0, 0))
    local_shape[axis] = part[comm.rank] # shape of local array
    local_start = [0] * len(global_shape)
    local_start[axis] = bound[comm.rank] # start of local_array in global array

    # allocate space for local_array to hold data read from file
    local_array = np.empty(local_shape, dtype=dtype, order='C')

    # get the position of the individual file pointer,
    # which is at the end of the header, the start of array data
    pos = fh.Get_position()

    # get the etype
    etype = typemap(dtype)

    # construct the filetype
    filetype = etype.Create_subarray(global_shape, local_shape, local_start, order=MPI.ORDER_C)
    filetype.Commit()

    # set the file view
    fh.Set_view(pos, etype, filetype, datarep='native')

    # collectively read the array from file
    fh.Read_all(local_array)

    # close the file
    fh.Close()

    return local_array


filename = 'test.npy'
local_array = np.arange(12, dtype='i').reshape(3, 4)

# parallelly write local array to file, assume array is distributed on axis 1, i.e., column
parallel_write_array(filename, local_array, axis=1, comm=comm)

# check data in the file
if rank == 0:
    print 'data in file: %s' % np.load(filename)

# now parallelly read data from file, each process read several row of the array
print 'process %d read: %s' % (rank, parallel_read_array(filename, axis=0, comm=comm))

運(yùn)行結(jié)果如下:

$ mpiexec -n 2 python npy_io.py
data in file: [[ 0  1  2  3  0  1  2  3]
[ 4  5  6  7  4  5  6  7]
[ 8  9 10 11  8  9 10 11]]
process 0 read: [[0 1 2 3 0 1 2 3]
[4 5 6 7 4 5 6 7]]
process 1 read: [[ 8  9 10 11  8  9 10 11]]

以上介紹了 mpi4py 中并行讀/寫 numpy npy 文件的方法,在下一篇中我們將介紹 mpi4py 初始化和運(yùn)行時(shí)設(shè)置。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,741評(píng)論 25 709
  • 來源:NumPy Tutorial - TutorialsPoint 譯者:飛龍 協(xié)議:CC BY-NC-SA 4...
    布客飛龍閱讀 33,509評(píng)論 6 97
  • 在上一篇中我們介紹了 mpi4py 中的文件互操作性,下面我們將介紹 mpi4py 中獲得高性能 I/O 的方法和...
    自可樂閱讀 1,613評(píng)論 0 0
  • 前言 計(jì)算機(jī)編程語言很多,但是適合高性能數(shù)值計(jì)算的語言卻并不多,在高性能計(jì)算的項(xiàng)目中通常會(huì)使用到的語言有 Fort...
    自可樂閱讀 20,296評(píng)論 3 21
  • 去年的冬天,打車去城市西北邊的一家咖啡廳和老陳見面,本想約在家附近的,可老陳那時(shí)在忙著年底工作的總結(jié),經(jīng)常東本西跑...
    低語小邵閱讀 340評(píng)論 0 0

友情鏈接更多精彩內(nèi)容