|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +from __future__ import absolute_import, print_function, division |
| 3 | + |
| 4 | +import numpy as np |
| 5 | + |
| 6 | +from numcodecs.abc import Codec |
| 7 | +from numcodecs.compat import buffer_copy, ndarray_from_buffer |
| 8 | + |
| 9 | + |
| 10 | + |
| 11 | +class AsType(Codec): |
| 12 | + """Filter to convert data between different types. |
| 13 | +
|
| 14 | + Parameters |
| 15 | + ---------- |
| 16 | + encode_dtype : dtype |
| 17 | + Data type to use for encoded data. |
| 18 | + decode_dtype : dtype, optional |
| 19 | + Data type to use for decoded data. |
| 20 | +
|
| 21 | + Notes |
| 22 | + ----- |
| 23 | + If `encode_dtype` is of lower precision than `decode_dtype`, please be |
| 24 | + aware that data loss can occur by writing data to disk using this filter. |
| 25 | + No checks are made to ensure the casting will work in that direction and |
| 26 | + data corruption will occur. |
| 27 | +
|
| 28 | + Examples |
| 29 | + -------- |
| 30 | + >>> import numcodecs |
| 31 | + >>> import numpy as np |
| 32 | + >>> x = np.arange(100, 120, 2, dtype=np.int8) |
| 33 | + >>> x |
| 34 | + array([100, 102, 104, 106, 108, 110, 112, 114, 116, 118], dtype=int8) |
| 35 | + >>> f = numcodecs.AsType(encode_dtype=x.dtype, decode_dtype=np.int64) |
| 36 | + >>> y = f.decode(x) |
| 37 | + >>> y |
| 38 | + array([100, 102, 104, 106, 108, 110, 112, 114, 116, 118]) |
| 39 | + >>> z = f.encode(y) |
| 40 | + >>> z |
| 41 | + array([100, 102, 104, 106, 108, 110, 112, 114, 116, 118], dtype=int8) |
| 42 | +
|
| 43 | + """ # flake8: noqa |
| 44 | + |
| 45 | + codec_id = 'astype' |
| 46 | + |
| 47 | + def __init__(self, encode_dtype, decode_dtype): |
| 48 | + self.encode_dtype = np.dtype(encode_dtype) |
| 49 | + self.decode_dtype = np.dtype(decode_dtype) |
| 50 | + |
| 51 | + def encode(self, buf): |
| 52 | + |
| 53 | + # view input data as 1D array |
| 54 | + arr = ndarray_from_buffer(buf, self.decode_dtype) |
| 55 | + |
| 56 | + # convert and copy |
| 57 | + enc = arr.astype(self.encode_dtype) |
| 58 | + |
| 59 | + return enc |
| 60 | + |
| 61 | + def decode(self, buf, out=None): |
| 62 | + |
| 63 | + # view encoded data as 1D array |
| 64 | + enc = ndarray_from_buffer(buf, self.encode_dtype) |
| 65 | + |
| 66 | + # convert and copy |
| 67 | + dec = enc.astype(self.decode_dtype) |
| 68 | + |
| 69 | + # handle output |
| 70 | + out = buffer_copy(dec, out) |
| 71 | + |
| 72 | + return out |
| 73 | + |
| 74 | + def get_config(self): |
| 75 | + config = dict() |
| 76 | + config['id'] = self.codec_id |
| 77 | + config['encode_dtype'] = self.encode_dtype.str |
| 78 | + config['decode_dtype'] = self.decode_dtype.str |
| 79 | + return config |
| 80 | + |
| 81 | + def __repr__(self): |
| 82 | + return ( |
| 83 | + '%s(encode_dtype=%r, decode_dtype=%r)' % ( |
| 84 | + type(self).__name__, |
| 85 | + self.encode_dtype.str, |
| 86 | + self.decode_dtype.str |
| 87 | + ) |
| 88 | + ) |
0 commit comments