Skip to content

<Class Mat44>

Bases: object

A 4x4 matrix for 3D affine transformation. Args: mat: The matrix, can be a 1D array of length 12 or 16, or a 2D array of shape (3,4) or (4,4). byrow: Whether the matrix is in row-major order (default) or column-major order. space_from: The space from which the matrix is defined, choices are "ras", "voxel", "ras_tkr", "mni305", "mni152".

    * "ras": scanner-RAS space
    * "voxel": voxel indexing space (or IJK space)
    * "ras_tkr": FreeSurfer RAS space, this is the space used internally by the viewer engine in JavaScript
    * "mni305": MNI305 template space
    * "mni152": MNI152 template space

    > threebrainpy does not limit the choices, but the viewer only supports these spaces.

space_to: The space to which the matrix is defined, choices are the same as `space_from`.
modality_from: The imaging modality from which the matrix is defined, choices are "T1" or "CT" other modalities may be 
    added in the future, default is "T1".
modality_to: The imaging modality to which the matrix is defined. If set to `None`, then it will be set
    with the same value as `modality_from` automatically; default choice is `None`.

Examples:

>>> Mat44([1,2,3,4,5,6,7,8,9,10,11,12])
Mat44 (T1.ras -> T1.ras): 
array([[ 1.,  2.,  3.,  4.],
    [ 5.,  6.,  7.,  8.],
    [ 9., 10., 11., 12.],
    [ 0.,  0.,  0.,  1.]])
>>> Mat44([1,2,3,4,5,6,7,8,9,10,11,12], byrow=False)
Mat44 (T1.ras -> T1.ras): 
array([[ 1.,  4.,  7., 10.],
    [ 2.,  5.,  8., 11.],
    [ 3.,  6.,  9., 12.],
    [ 0.,  0.,  0.,  1.]])
>>> Mat44([-1,0,0,128,0,0,1,-128,0,-1,0,128], space_from="voxel", space_to="ras_tkr")
Mat44 (T1.voxel -> T1.ras_tkr): 
array([[  -1.,    0.,    0.,  128.],
    [   0.,    0.,    1., -128.],
    [   0.,   -1.,    0.,  128.],
    [   0.,    0.,    0.,    1.]])
Source code in threebrainpy/core/mat44.py
  5
  6
  7
  8
  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
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
class Mat44(object):
    '''
    A 4x4 matrix for 3D affine transformation.
    Args:
        mat: The matrix, can be a 1D array of length 12 or 16, or a 2D array of shape (3,4) or (4,4).
        byrow: Whether the matrix is in row-major order (default) or column-major order.
        space_from: The space from which the matrix is defined, choices are "ras", "voxel", "ras_tkr", "mni305", "mni152".

            * "ras": scanner-RAS space
            * "voxel": voxel indexing space (or IJK space)
            * "ras_tkr": FreeSurfer RAS space, this is the space used internally by the viewer engine in JavaScript
            * "mni305": MNI305 template space
            * "mni152": MNI152 template space

            > threebrainpy does not limit the choices, but the viewer only supports these spaces.

        space_to: The space to which the matrix is defined, choices are the same as `space_from`.
        modality_from: The imaging modality from which the matrix is defined, choices are "T1" or "CT" other modalities may be 
            added in the future, default is "T1".
        modality_to: The imaging modality to which the matrix is defined. If set to `None`, then it will be set
            with the same value as `modality_from` automatically; default choice is `None`.

    Examples:

        >>> Mat44([1,2,3,4,5,6,7,8,9,10,11,12])
        Mat44 (T1.ras -> T1.ras): 
        array([[ 1.,  2.,  3.,  4.],
            [ 5.,  6.,  7.,  8.],
            [ 9., 10., 11., 12.],
            [ 0.,  0.,  0.,  1.]])
        >>> Mat44([1,2,3,4,5,6,7,8,9,10,11,12], byrow=False)
        Mat44 (T1.ras -> T1.ras): 
        array([[ 1.,  4.,  7., 10.],
            [ 2.,  5.,  8., 11.],
            [ 3.,  6.,  9., 12.],
            [ 0.,  0.,  0.,  1.]])
        >>> Mat44([-1,0,0,128,0,0,1,-128,0,-1,0,128], space_from="voxel", space_to="ras_tkr")
        Mat44 (T1.voxel -> T1.ras_tkr): 
        array([[  -1.,    0.,    0.,  128.],
            [   0.,    0.,    1., -128.],
            [   0.,   -1.,    0.,  128.],
            [   0.,    0.,    0.,    1.]])
    '''
    def __init__(self, mat : Union[np.ndarray, list, tuple, None] = None, byrow : bool = True, 
                 space_from : str = 'ras', space_to : str = 'ras', 
                 modality_from : str = "T1", modality_to : str = "T1"):
        if mat is None:
            self.mat = np.eye(4)
        else:
            mat = np.array(mat, copy = True, dtype=float)
            if mat.size == 12:
                if byrow:
                    mat = mat.reshape(3,4)
                else:
                    mat = mat.reshape(4,3).transpose()
                map = np.append(mat, [[0,0,0,1]], axis=0)
            else:
                map = mat.reshape(4, 4)
                if not byrow:
                    mat = mat.transpose()
            self.mat = map
        self.space_from = space_from
        self.space_to = space_to
        self.modality_from = modality_from
        self.modality_to = modality_from if modality_to is None else modality_to
        self.extra = {}

    def __mul__(self, other):
        if isinstance(other, Mat44):
            # modalities must match
            if self.modality_from != other.modality_to:
                raise ValueError(f"Mat44 multiply: modalities must match, but got {self.modality_from} and {other.modality_to}")
            # spaces must match
            if self.space_from != other.space_to:
                raise ValueError(f"Mat44 multiply: spaces must match, but got {self.space_from} and {other.space_to}")
        return Mat44(np.matmul(self.mat, other.mat), modality_from=other.modality_from, modality_to=self.modality_to, space_from=other.space_from, space_to=self.space_to)

    def __repr__(self):
        re = repr(self.mat)
        return f"Mat44 ({self.modality_from}.{self.space_from} -> {self.modality_to}.{self.space_to}): \n{ re }"

    def __str__(self):
        return str(self.mat)

    def __getitem__(self, key):
        return self.mat[key]

    def __setitem__(self, key, value):
        self.mat[key] = value

    def __eq__(self, other):
        return np.allclose(self.mat, other.mat)

    def __ne__(self, other):
        return not np.allclose(self.mat, other.mat)

    def __hash__(self):
        return hash(str(self.mat))

    def __copy__(self):
        return Mat44(self.mat.copy(), space_from = self.space_from, space_to = self.space_to, modality_from = self.modality_from, modality_to = self.modality_to)

    def __deepcopy__(self, memo):
        return Mat44(self.mat.copy(), space_from = self.space_from, space_to = self.space_to, modality_from = self.modality_from, modality_to = self.modality_to)

    def __iter__(self):
        return iter(self.mat)

    def __len__(self):
        return len(self.mat)

    def __abs__(self):
        return abs(self.mat)

    def __neg__(self):
        return Mat44(-self.mat, space_from = self.space_from, space_to = self.space_to, modality_from = self.modality_from, modality_to = self.modality_to)

    def __pos__(self):
        return Mat44(+self.mat, space_from = self.space_from, space_to = self.space_to, modality_from = self.modality_from, modality_to = self.modality_to)

    def __add__(self, other):
        if isinstance(other, Mat44):
            # modalities must match
            if self.modality_from != other.modality_from:
                raise ValueError(f"Mat44 add: modality_from must match, but got {self.modality_from} and {other.modality_from}")
            if self.modality_to != other.modality_to:
                raise ValueError(f"Mat44 add: modality_from must match, but got {self.modality_to} and {other.modality_to}")
            # spaces must match
            if self.space_from != other.space_from:
                raise ValueError(f"Mat44 add: space_from must match, but got {self.space_from} and {other.space_from}")
            if self.space_to != other.space_to:
                raise ValueError(f"Mat44 add: space_to must match, but got {self.space_to} and {other.space_to}")
        return Mat44(self.mat + other.mat, space_from = self.space_from, space_to = self.space_to, modality_from = self.modality_from, modality_to = self.modality_to)

    def __sub__(self, other):
        if isinstance(other, Mat44):
            # modalities must match
            if self.modality_from != other.modality_from:
                raise ValueError(f"Mat44 add: modality_from must match, but got {self.modality_from} and {other.modality_from}")
            if self.modality_to != other.modality_to:
                raise ValueError(f"Mat44 add: modality_from must match, but got {self.modality_to} and {other.modality_to}")
            # spaces must match
            if self.space_from != other.space_from:
                raise ValueError(f"Mat44 add: space_from must match, but got {self.space_from} and {other.space_from}")
            if self.space_to != other.space_to:
                raise ValueError(f"Mat44 add: space_to must match, but got {self.space_to} and {other.space_to}")
        return Mat44(self.mat - other.mat, space_from = self.space_from, space_to = self.space_to, modality_from = self.modality_from, modality_to = self.modality_to)

    def __floordiv__(self, other):
        if isinstance(other, Mat44):
            # modalities must match
            if self.modality_from != other.modality_from:
                raise ValueError(f"Mat44 add: modality_from must match, but got {self.modality_from} and {other.modality_from}")
            if self.modality_to != other.modality_to:
                raise ValueError(f"Mat44 add: modality_from must match, but got {self.modality_to} and {other.modality_to}")
            # spaces must match
            if self.space_from != other.space_from:
                raise ValueError(f"Mat44 add: space_from must match, but got {self.space_from} and {other.space_from}")
            if self.space_to != other.space_to:
                raise ValueError(f"Mat44 add: space_to must match, but got {self.space_to} and {other.space_to}")
        return Mat44(self.mat // other.mat, space_from = self.space_from, space_to = self.space_to, modality_from = self.modality_from, modality_to = self.modality_to)

    def __mod__(self, other):
        if isinstance(other, Mat44):
            # modalities must match
            if self.modality_from != other.modality_from:
                raise ValueError(f"Mat44 add: modality_from must match, but got {self.modality_from} and {other.modality_from}")
            if self.modality_to != other.modality_to:
                raise ValueError(f"Mat44 add: modality_from must match, but got {self.modality_to} and {other.modality_to}")
            # spaces must match
            if self.space_from != other.space_from:
                raise ValueError(f"Mat44 add: space_from must match, but got {self.space_from} and {other.space_from}")
            if self.space_to != other.space_to:
                raise ValueError(f"Mat44 add: space_to must match, but got {self.space_to} and {other.space_to}")
        return Mat44(self.mat % other.mat, space_from = self.space_from, space_to = self.space_to, modality_from = self.modality_from, modality_to = self.modality_to)

    def __pow__(self, other):
        if isinstance(other, Mat44):
            # modalities must match
            if self.modality_from != other.modality_from:
                raise ValueError(f"Mat44 add: modality_from must match, but got {self.modality_from} and {other.modality_from}")
            if self.modality_to != other.modality_to:
                raise ValueError(f"Mat44 add: modality_from must match, but got {self.modality_to} and {other.modality_to}")
            # spaces must match
            if self.space_from != other.space_from:
                raise ValueError(f"Mat44 add: space_from must match, but got {self.space_from} and {other.space_from}")
            if self.space_to != other.space_to:
                raise ValueError(f"Mat44 add: space_to must match, but got {self.space_to} and {other.space_to}")
        return Mat44(self.mat ** other.mat, space_from = self.space_from, space_to = self.space_to, modality_from = self.modality_from, modality_to = self.modality_to)

    def __invert__(self):
        return Mat44(np.linalg.inv(self.mat), space_from = self.space_to, space_to = self.space_from, modality_from = self.modality_to, modality_to = self.modality_from)

    def to_json(self, **kwargs):
        return json.dumps(np.ndarray.flatten(self.mat).tolist(), **kwargs)