~jtaylor/ubuntu/precise/python-numpy/multiarch-fix-818867

« back to all changes in this revision

Viewing changes to numpy/core/memmap.py

  • Committer: Bazaar Package Importer
  • Author(s): Ondrej Certik, Riku Voipio, Tiziano Zito, Carlos Galisteo, Ondrej Certik
  • Date: 2008-07-08 15:08:16 UTC
  • mfrom: (0.1.21 intrepid)
  • Revision ID: james.westby@ubuntu.com-20080708150816-ekf992jcp2k1eua3
Tags: 1:1.1.0-3
[ Riku Voipio ]
* debian/control: atlas is not available on armel, and after a quick look
  neither on alpha. I'd also suggest dropping
  libatlas-sse-dev|libatlas-sse2-dev|libatlas-3dnow-dev alternative combo
  away, these are potentially dangerous on buildd's. Ondrej: dropped.
  (Closes: #489568)

[ Tiziano Zito ]
* patch: build _dotblas.c when ATLAS is not installed, build-conflict with
  atlas, build-depend on blas+lapack only, as it used to be (Closes: #489726)

[ Carlos Galisteo ]
* debian/control
  - Added Homepage field.

[ Ondrej Certik ]
* Checked the package on i386 and amd64, both with and without atlas, all
  tests run and the numpy package is faster if atlas is around. 

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
__all__ = ['memmap']
2
2
 
3
3
import mmap
 
4
import warnings
4
5
from numeric import uint8, ndarray, dtype
5
6
 
6
7
dtypedescr = dtype
15
16
    }
16
17
 
17
18
class memmap(ndarray):
 
19
    """Create a memory-map to an array stored in a file on disk.
 
20
 
 
21
    Memory-mapped files are used for accessing small segments of large files
 
22
    on disk, without reading the entire file into memory.  Numpy's memmaps are
 
23
    array-like objects.  This differs from python's mmap module which are
 
24
    file-like objects.
 
25
 
 
26
    Parameters
 
27
    ----------
 
28
    filename : string or file-like object
 
29
        The file name or file object to be used as the array data
 
30
        buffer.
 
31
    dtype : data-type, optional
 
32
        The data-type used to interpret the file contents.
 
33
        Default is uint8
 
34
    mode : {'r', 'r+', 'w+', 'c'}, optional
 
35
        The mode to open the file.
 
36
        'r',  open existing file for read-only
 
37
        'r+', open existing file for read-write
 
38
        'w+', create or overwrite existing file and open for read-write
 
39
        'c',  copy-on-write, assignments effect data in memory, but changes
 
40
              are not saved to disk.  File on disk is read-only.
 
41
        Default is 'r+'
 
42
    offset : integer, optional
 
43
        Byte offset into the file to start the array data. Should be a
 
44
        multiple of the data-type of the data.  Requires shape=None.
 
45
        Default is 0
 
46
    shape : tuple, optional
 
47
        The desired shape of the array. If None, the returned array will be 1-D
 
48
        with the number of elements determined by file size and data-type.
 
49
        Default is None
 
50
    order : {'C', 'F'}, optional
 
51
        Specify the order of the N-D array, C or Fortran ordered. This only
 
52
        has an effect if the shape is greater than 2-D.
 
53
        Default is 'C'
 
54
 
 
55
    Methods
 
56
    -------
 
57
    close : close the memmap file
 
58
    flush : flush any changes in memory to file on disk
 
59
        When you delete a memmap object, flush is called first to write
 
60
        changes to disk before removing the object.
 
61
 
 
62
    Returns
 
63
    -------
 
64
    memmap : array-like memmap object
 
65
        The memmap object can be used anywhere an ndarray is accepted.
 
66
        If fp is a memmap, isinstance(fp, numpy.ndarray) will return True.
 
67
 
 
68
    Examples
 
69
    --------
 
70
    >>> import numpy as np
 
71
    >>> data = np.arange(12, dtype='float32')
 
72
    >>> data.resize((3,4))
 
73
 
 
74
    >>> # Using a tempfile so doctest doesn't write files to your directory.
 
75
    >>> # You would use a 'normal' filename.
 
76
    >>> from tempfile import mkdtemp
 
77
    >>> import os.path as path
 
78
    >>> filename = path.join(mkdtemp(), 'newfile.dat')
 
79
 
 
80
    >>> # Create a memmap with dtype and shape that matches our data
 
81
    >>> fp = np.memmap(filename, dtype='float32', mode='w+', shape=(3,4))
 
82
    >>> fp
 
83
    memmap([[ 0.,  0.,  0.,  0.],
 
84
           [ 0.,  0.,  0.,  0.],
 
85
           [ 0.,  0.,  0.,  0.]], dtype=float32)
 
86
 
 
87
    >>> # Write data to memmap array
 
88
    >>> fp[:] = data[:]
 
89
    >>> fp
 
90
    memmap([[  0.,   1.,   2.,   3.],
 
91
           [  4.,   5.,   6.,   7.],
 
92
           [  8.,   9.,  10.,  11.]], dtype=float32)
 
93
 
 
94
    >>> # Deletion flushes memory changes to disk before removing the object.
 
95
    >>> del fp
 
96
    >>> # Load the memmap and verify data was stored
 
97
    >>> newfp = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
 
98
    >>> newfp
 
99
    memmap([[  0.,   1.,   2.,   3.],
 
100
           [  4.,   5.,   6.,   7.],
 
101
           [  8.,   9.,  10.,  11.]], dtype=float32)
 
102
 
 
103
    >>> # read-only memmap
 
104
    >>> fpr = np.memmap(filename, dtype='float32', mode='r', shape=(3,4))
 
105
    >>> fpr.flags.writeable
 
106
    False
 
107
    >>> # Cannot assign to read-only, obviously
 
108
    >>> fpr[0, 3] = 56
 
109
    Traceback (most recent call last):
 
110
        ...
 
111
    RuntimeError: array is not writeable
 
112
 
 
113
    >>> # copy-on-write memmap
 
114
    >>> fpc = np.memmap(filename, dtype='float32', mode='c', shape=(3,4))
 
115
    >>> fpc.flags.writeable
 
116
    True
 
117
    >>> # Can assign to copy-on-write array, but values are only written
 
118
    >>> # into the memory copy of the array, and not written to disk.
 
119
    >>> fpc
 
120
    memmap([[  0.,   1.,   2.,   3.],
 
121
           [  4.,   5.,   6.,   7.],
 
122
           [  8.,   9.,  10.,  11.]], dtype=float32)
 
123
    >>> fpc[0,:] = 0
 
124
    >>> fpc
 
125
    memmap([[  0.,   0.,   0.,   0.],
 
126
           [  4.,   5.,   6.,   7.],
 
127
           [  8.,   9.,  10.,  11.]], dtype=float32)
 
128
    >>> # file on disk is unchanged
 
129
    >>> fpr
 
130
    memmap([[  0.,   1.,   2.,   3.],
 
131
           [  4.,   5.,   6.,   7.],
 
132
           [  8.,   9.,  10.,  11.]], dtype=float32)
 
133
 
 
134
    >>> # offset into a memmap
 
135
    >>> fpo = np.memmap(filename, dtype='float32', mode='r', offset=16)
 
136
    >>> fpo
 
137
    memmap([  4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.], dtype=float32)
 
138
 
 
139
    """
 
140
 
18
141
    __array_priority__ = -100.0
19
 
    def __new__(subtype, name, dtype=uint8, mode='r+', offset=0,
 
142
    def __new__(subtype, filename, dtype=uint8, mode='r+', offset=0,
20
143
                shape=None, order='C'):
21
144
        try:
22
145
            mode = mode_equivalents[mode]
25
148
                raise ValueError("mode must be one of %s" % \
26
149
                                 (valid_filemodes + mode_equivalents.keys()))
27
150
 
28
 
        fid = file(name, (mode == 'c' and 'r' or mode)+'b')
 
151
        if hasattr(filename,'read'):
 
152
            fid = filename
 
153
        else:
 
154
            fid = file(filename, (mode == 'c' and 'r' or mode)+'b')
29
155
 
30
156
        if (mode == 'w+') and shape is None:
31
157
            raise ValueError, "shape must be given"
72
198
        self._offset = offset
73
199
        self._mode = mode
74
200
        self._size = size
75
 
        self._name = name
76
 
        fid.close()
 
201
        self._name = filename
77
202
        return self
78
203
 
79
204
    def __array_finalize__(self, obj):
80
 
        if obj is not None and not isinstance(obj, memmap):
81
 
            raise ValueError, "Cannot create a memmap array that way"
82
 
        self._mmap = None
 
205
        if hasattr(obj, '_mmap'):
 
206
            self._mmap = obj._mmap
 
207
        else:
 
208
            self._mmap = None
 
209
 
 
210
    def flush(self):
 
211
        """Flush any changes in the array to the file on disk."""
 
212
        if self._mmap is not None:
 
213
            self._mmap.flush()
83
214
 
84
215
    def sync(self):
85
 
        self._mmap.flush()
 
216
        """Flush any changes in the array to the file on disk."""
 
217
        warnings.warn("Use ``flush``.", DeprecationWarning)
 
218
        self.flush()
 
219
 
 
220
    def _close(self):
 
221
        """Close the memmap file.  Only do this when deleting the object."""
 
222
        if self.base is self._mmap:
 
223
            self._mmap.close()
 
224
            self._mmap = None
 
225
 
 
226
        # DEV NOTE: This error is raised on the deletion of each row
 
227
        # in a view of this memmap.  Python traps exceptions in
 
228
        # __del__ and prints them to stderr.  Suppressing this for now
 
229
        # until memmap code is cleaned up and and better tested for
 
230
        # numpy v1.1 Objects that do not have a python mmap instance
 
231
        # as their base data array, should not do anything in the
 
232
        # close anyway.
 
233
        #elif self._mmap is not None:
 
234
            #raise ValueError, "Cannot close a memmap that is being used " \
 
235
            #      "by another object."
 
236
 
 
237
    def close(self):
 
238
        """Close the memmap file. Does nothing."""
 
239
        warnings.warn("``close`` is deprecated on memmap arrays.  Use del",
 
240
                      DeprecationWarning)
86
241
 
87
242
    def __del__(self):
88
243
        if self._mmap is not None:
89
 
            self._mmap.flush()
90
 
            del self._mmap
 
244
            try:
 
245
                # First run tell() to see whether file is open
 
246
                self._mmap.tell()
 
247
            except ValueError:
 
248
                pass
 
249
            else:
 
250
                # flush any changes to disk, even if it's a view
 
251
                self.flush()
 
252
                self._close()