field_type.py 1.89 KB
Newer Older
theos's avatar
theos committed
1
2
# -*- coding: utf-8 -*-

Jait Dixit's avatar
Jait Dixit committed
3
import pickle
theos's avatar
theos committed
4
import numpy as np
Jait Dixit's avatar
Jait Dixit committed
5
from keepers import Versionable
theos's avatar
theos committed
6
7


Jait Dixit's avatar
Jait Dixit committed
8
class FieldType(Versionable, object):
theos's avatar
theos committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
    def __init__(self, shape, dtype):
        try:
            new_shape = tuple([int(i) for i in shape])
        except TypeError:
            new_shape = (int(shape), )
        self._shape = new_shape

        self._dtype = np.dtype(dtype)

    def __hash__(self):
        # Extract the identifying parts from the vars(self) dict.
        result_hash = 0
        for (key, item) in vars(self).items():
            result_hash ^= item.__hash__() ^ int(hash(key)/117)
        return result_hash

    def __eq__(self, x):
        if isinstance(x, type(self)):
            return hash(self) == hash(x)
        else:
            return False

    @property
    def shape(self):
        return self._shape

    @property
    def dtype(self):
        return self._dtype

    @property
    def dim(self):
        raise NotImplementedError

    def process(self, method_name, array, inplace=True, **kwargs):
        try:
            result_array = self.__getattr__(method_name)(array,
                                                         inplace,
                                                         **kwargs)
        except AttributeError:
            if inplace:
                result_array = array
            else:
                result_array = array.copy()

        return result_array

56
57
58
59
    def pre_cast(self, x, axes=None):
        return x

    def post_cast(self, x, axes=None):
theos's avatar
theos committed
60
        return x
Jait Dixit's avatar
Jait Dixit committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

    # ---Serialization---

    def _to_hdf5(self, hdf5_group):
        hdf5_group['shape'] = self.shape
        hdf5_group['dtype'] = pickle.dumps(self.dtype)

        return None

    @classmethod
    def _from_hdf5(cls, hdf5_group, loopback_get):
        result = cls(
            hdf5_group['shape'][:],
            pickle.loads(hdf5_group['dtype'][()])
            )
        return result