~ubuntu-branches/ubuntu/feisty/python-numpy/feisty

« back to all changes in this revision

Viewing changes to numpy/core/defchararray.py

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2006-07-12 10:00:24 UTC
  • Revision ID: james.westby@ubuntu.com-20060712100024-5lw9q2yczlisqcrt
Tags: upstream-0.9.8
ImportĀ upstreamĀ versionĀ 0.9.8

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from numerictypes import string, unicode_, integer, object_
 
2
from numeric import ndarray, broadcast, empty
 
3
from numeric import array as narray
 
4
import sys
 
5
 
 
6
__all__ = ['chararray']
 
7
 
 
8
_globalvar = 0
 
9
_unicode = unicode
 
10
 
 
11
# special sub-class for character arrays (string and unicode_)
 
12
# This adds equality testing and methods of str and unicode types
 
13
#  which operate on an element-by-element basis
 
14
 
 
15
 
 
16
class chararray(ndarray):
 
17
    def __new__(subtype, shape, itemsize=1, unicode=False, buffer=None,
 
18
                offset=0, strides=None, order=None):
 
19
        global _globalvar
 
20
 
 
21
        if unicode:
 
22
            dtype = unicode_
 
23
        else:
 
24
            dtype = string
 
25
 
 
26
        _globalvar = 1
 
27
        if buffer is None:
 
28
            self = ndarray.__new__(subtype, shape, (dtype, itemsize),
 
29
                                   order=order)
 
30
        else:
 
31
            self = ndarray.__new__(subtype, shape, (dtype, itemsize),
 
32
                                   buffer=buffer,
 
33
                                   offset=offset, strides=strides,
 
34
                                   order=order)
 
35
        _globalvar = 0
 
36
        return self
 
37
 
 
38
    def __array_finalize__(self, obj):
 
39
        # The b is a special case because it is used for reconstructing. 
 
40
        if not _globalvar and self.dtype.char not in 'SUb':
 
41
            raise ValueError, "Can only create a chararray from string data."
 
42
 
 
43
 
 
44
##    def _richcmpfunc(self, other, op):
 
45
##        b = broadcast(self, other)
 
46
##        result = empty(b.shape, dtype=bool)
 
47
##        res = result.flat
 
48
##        for k, val in enumerate(b):
 
49
##            r1 = val[0].rstrip('\x00')
 
50
##            r2 = val[1]
 
51
##            res[k] = eval("r1 %s r2" % op, {'r1':r1,'r2':r2})
 
52
##        return result
 
53
 
 
54
    # these have been moved to C
 
55
##    def __eq__(self, other):
 
56
##        return self._richcmpfunc(other, '==')
 
57
 
 
58
##    def __ne__(self, other):
 
59
##        return self._richcmpfunc(other, '!=')
 
60
 
 
61
##    def __ge__(self, other):
 
62
##        return self._richcmpfunc(other, '>=')
 
63
 
 
64
##    def __le__(self, other):
 
65
##        return self._richcmpfunc(other, '<=')
 
66
 
 
67
##    def __gt__(self, other):
 
68
##        return self._richcmpfunc(other, '>')
 
69
 
 
70
##    def __lt__(self, other):
 
71
##        return self._richcmpfunc(other, '<')
 
72
 
 
73
    def __add__(self, other):
 
74
        b = broadcast(self, other)
 
75
        arr = b.iters[1].base
 
76
        outitem = self.itemsize + arr.itemsize
 
77
        result = chararray(b.shape, outitem, self.dtype is unicode_)
 
78
        res = result.flat
 
79
        for k, val in enumerate(b):
 
80
            res[k] = (val[0] + val[1])
 
81
        return result
 
82
 
 
83
    def __radd__(self, other):
 
84
        b = broadcast(other, self)
 
85
        outitem = b.iters[0].base.itemsize + \
 
86
                  b.iters[1].base.itemsize
 
87
        result = chararray(b.shape, outitem, self.dtype is unicode_)
 
88
        res = result.flat
 
89
        for k, val in enumerate(b):
 
90
            res[k] = (val[0] + val[1])
 
91
        return result
 
92
 
 
93
    def __mul__(self, other):
 
94
        b = broadcast(self, other)
 
95
        arr = b.iters[1].base
 
96
        if not issubclass(arr.dtype.type, integer):
 
97
            raise ValueError, "Can only multiply by integers"
 
98
        outitem = b.iters[0].base.itemsize * arr.max()
 
99
        result = chararray(b.shape, outitem, self.dtype is unicode_)
 
100
        res = result.flat
 
101
        for k, val in enumerate(b):
 
102
            res[k] = val[0]*val[1]
 
103
        return result
 
104
 
 
105
    def __rmul__(self, other):
 
106
        b = broadcast(self, other)
 
107
        arr = b.iters[1].base
 
108
        if not issubclass(arr.dtype.type, integer):
 
109
            raise ValueError, "Can only multiply by integers"
 
110
        outitem = b.iters[0].base.itemsize * arr.max()
 
111
        result = chararray(b.shape, outitem, self.dtype is unicode_)
 
112
        res = result.flat
 
113
        for k, val in enumerate(b):
 
114
            res[k] = val[0]*val[1]
 
115
        return result
 
116
 
 
117
    def __mod__(self, other):
 
118
        b = broadcast(self, other)
 
119
        res = [None]*b.size
 
120
        maxsize = -1
 
121
        for k,val in enumerate(b):
 
122
            newval = val[0] % val[1]
 
123
            maxsize = max(len(newval), maxsize)
 
124
            res[k] = newval
 
125
        newarr = chararray(b.shape, maxsize, self.dtype is unicode_)
 
126
        newarr[:] = res
 
127
        return newarr
 
128
 
 
129
    def __rmod__(self, other):
 
130
        return NotImplemented
 
131
 
 
132
    def _generalmethod(self, name, myiter):
 
133
        res = [None]*myiter.size
 
134
        maxsize = -1
 
135
        for k, val in enumerate(myiter):
 
136
            newval = []
 
137
            for chk in val[1:]:
 
138
                if chk.dtype is object_ and chk.item() is None:
 
139
                    break
 
140
                newval.append(chk)
 
141
            newitem = getattr(val[0],name)(*newval)
 
142
            maxsize = max(len(newitem), maxsize)
 
143
            res[k] = newitem
 
144
        newarr = chararray(myiter.shape, maxsize, self.dtype is unicode_)
 
145
        print res, maxsize
 
146
        newarr[:] = res
 
147
        return newarr
 
148
 
 
149
    def _typedmethod(self, name, myiter, dtype):
 
150
        result = empty(myiter.shape, dtype=dtype)
 
151
        res = result.flat
 
152
        for k, val in enumerate(myiter):
 
153
            newval = []
 
154
            for chk in val[1:]:
 
155
                if chk.dtype is object_ and chk.item() is None:
 
156
                    break
 
157
                newval.append(chk)
 
158
            this_str = val[0].rstrip('\x00')
 
159
            newitem = getattr(this_str,name)(*newval)
 
160
            res[k] = newitem
 
161
        return result
 
162
 
 
163
    def _samemethod(self, name):
 
164
        result = self.copy()
 
165
        res = result.flat
 
166
        for k, val in enumerate(self.flat):
 
167
            res[k] = getattr(val, name)()
 
168
        return result
 
169
 
 
170
    def capitalize(self):
 
171
        return self._samemethod('capitalize')
 
172
 
 
173
    if sys.version[:3] >= '2.4':
 
174
        def center(self, width, fillchar=' '):
 
175
            return self._generalmethod('center',
 
176
                                       broadcast(self, width, fillchar))
 
177
        def ljust(self, width, fillchar=' '):
 
178
            return self._generalmethod('ljust',
 
179
                                       broadcast(self, width, fillchar))
 
180
        def rjust(self, width, fillchar=' '):
 
181
            return self._generalmethod('rjust',
 
182
                                       broadcast(self, width, fillchar))
 
183
        def rsplit(self, sep=None, maxsplit=None):
 
184
            return self._typedmethod('rsplit', broadcast(self, sep, maxsplit),
 
185
                                     object)
 
186
    else:
 
187
        def ljust(self, width):
 
188
            return self._generalmethod('ljust', broadcast(self, width))
 
189
        def rjust(self, width):
 
190
            return self._generalmethod('rjust', broadcast(self, width))
 
191
        def center(self, width):
 
192
            return self._generalmethod('center', broadcast(self, width))
 
193
 
 
194
    def count(self, sub, start=None, end=None):
 
195
        return self._typedmethod('count', broadcast(self, sub, start, end), int)
 
196
 
 
197
    def decode(self,encoding=None,errors=None):
 
198
        return self._generalmethod('decode', broadcast(self, encoding, errors))
 
199
 
 
200
    def encode(self,encoding=None,errors=None):
 
201
        return self._generalmethod('encode', broadcast(self, encoding, errors))
 
202
 
 
203
    def endswith(self, suffix, start=None, end=None):
 
204
        return self._typedmethod('endswith', broadcast(self, suffix, start, end), bool)
 
205
 
 
206
    def expandtabs(self, tabsize=None):
 
207
        return self._generalmethod('endswith', broadcast(self, tabsize))
 
208
 
 
209
    def find(self, sub, start=None, end=None):
 
210
        return self._typedmethod('find', broadcast(self, sub, start, end), int)
 
211
 
 
212
    def index(self, sub, start=None, end=None):
 
213
        return self._typedmethod('index', broadcast(self, sub, start, end), int)
 
214
 
 
215
    def _ismethod(self, name):
 
216
        result = empty(self.shape, dtype=bool)
 
217
        res = result.flat
 
218
        for k, val in enumerate(self.flat):
 
219
            item = val.rstrip('\x00')
 
220
            res[k] = getattr(item, name)()
 
221
        return result
 
222
 
 
223
    def isalnum(self):
 
224
        return self._ismethod('isalnum')
 
225
 
 
226
    def isalpha(self):
 
227
        return self._ismethod('isalpha')
 
228
 
 
229
    def isdigit(self):
 
230
        return self._ismethod('isdigit')
 
231
 
 
232
    def islower(self):
 
233
        return self._ismethod('islower')
 
234
 
 
235
    def isspace(self):
 
236
        return self._ismethod('isspace')
 
237
 
 
238
    def istitle(self):
 
239
        return self._ismethod('istitle')
 
240
 
 
241
    def isupper(self):
 
242
        return self._ismethod('isupper')
 
243
 
 
244
    def join(self, seq):
 
245
        return self._generalmethod('join', broadcast(self, seq))
 
246
 
 
247
    def lower(self):
 
248
        return self._samemethod('lower')
 
249
 
 
250
    def lstrip(self, chars):
 
251
        return self._generalmethod('lstrip', broadcast(self, chars))
 
252
 
 
253
    def replace(self, old, new, count=None):
 
254
        return self._generalmethod('replace', broadcast(self, old, new, count))
 
255
 
 
256
    def rfind(self, sub, start=None, end=None):
 
257
        return self._typedmethod('rfind', broadcast(self, sub, start, end), int)
 
258
 
 
259
    def rindex(self, sub, start=None, end=None):
 
260
        return self._typedmethod('rindex', broadcast(self, sub, start, end), int)
 
261
 
 
262
    def rstrip(self, chars=None):
 
263
        return self._generalmethod('rstrip', broadcast(self, chars))
 
264
 
 
265
    def split(self, sep=None, maxsplit=None):
 
266
        return self._typedmethod('split', broadcast(self, sep, maxsplit), object)
 
267
 
 
268
    def splitlines(self, keepends=None):
 
269
        return self._typedmethod('splitlines', broadcast(self, keepends), object)
 
270
 
 
271
    def startswith(self, prefix, start=None, end=None):
 
272
        return self._typedmethod('startswith', broadcast(self, prefix, start, end), bool)
 
273
 
 
274
    def strip(self, chars=None):
 
275
        return self._generalmethod('strip', broadcast(self, chars))
 
276
 
 
277
    def swapcase(self):
 
278
        return self._samemethod('swapcase')
 
279
 
 
280
    def title(self):
 
281
        return self._samemethod('title')
 
282
 
 
283
    def translate(self, table, deletechars=None):
 
284
        if self.dtype is unicode_:
 
285
            return self._generalmethod('translate', broadcast(self, table))
 
286
        else:
 
287
            return self._generalmethod('translate', broadcast(self, table, deletechars))
 
288
 
 
289
    def upper(self):
 
290
        return self._samemethod('upper')
 
291
 
 
292
    def zfill(self, width):
 
293
        return self._generalmethod('zfill', broadcast(self, width))
 
294
 
 
295
 
 
296
def array(obj, itemsize=None, copy=True, unicode=False, order=None):
 
297
 
 
298
    if isinstance(obj, chararray):
 
299
        if itemsize is None:
 
300
            itemsize = obj.itemsize
 
301
        if copy or (itemsize != obj.itemsize) \
 
302
           or (not unicode and obj.dtype == unicode_) \
 
303
           or (unicode and obj.dtype == string):
 
304
            return obj.astype("%s%d" % (obj.dtype.char, itemsize))
 
305
        else:
 
306
            return obj
 
307
 
 
308
    if isinstance(obj, ndarray) and (obj.dtype in [unicode_, string]):
 
309
        new = obj.view(chararray)
 
310
        if unicode and obj.dtype == string:
 
311
            return new.astype((unicode_, obj.itemsize))
 
312
        elif obj.dtype == unicode_:
 
313
            return new.astype((string, obj.itemsize))
 
314
 
 
315
        if copy: return new.copy()
 
316
        else: return new
 
317
 
 
318
    if unicode: dtype = "U"
 
319
    else: dtype = "S"
 
320
 
 
321
    if itemsize is not None:
 
322
        dtype += str(itemsize)
 
323
 
 
324
    if isinstance(obj, (str, _unicode)):
 
325
        if itemsize is None:
 
326
            itemsize = len(obj)
 
327
        shape = len(obj) / itemsize
 
328
        return chararray(shape, itemsize=itemsize, unicode=unicode,
 
329
                         buffer=obj)
 
330
 
 
331
    # default
 
332
    val = narray(obj, dtype=dtype, order=order, subok=1)
 
333
 
 
334
    return val.view(chararray)
 
335
 
 
336
def asarray(obj, itemsize=None, unicode=False, order=None):
 
337
    return array(obj, itemsize, copy=False,
 
338
                 unicode=unicode, order=order)