-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy path_matrix.py
More file actions
44 lines (27 loc) · 1.37 KB
/
_matrix.py
File metadata and controls
44 lines (27 loc) · 1.37 KB
1
2
3
4
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
from typing import TypeGuard
from torch import Tensor
class GeneralizedMatrix(Tensor):
"""Tensor with a least 1 dimension."""
class Matrix(GeneralizedMatrix):
"""Tensor with exactly 2 dimensions."""
class PSDGeneralizedMatrix(Tensor):
"""
Tensor representing a quadratic form. The first half of its dimensions matches the reversed
second half of its dimensions (e.g. shape=[4, 3, 3, 4]), and its reshaping into a matrix should
be positive semi-definite.
"""
class PSDMatrix(PSDGeneralizedMatrix, Matrix):
"""Positive semi-definite matrix."""
def is_generalized_matrix(t: Tensor) -> TypeGuard[GeneralizedMatrix]:
return t.ndim >= 1
def is_matrix(t: Tensor) -> TypeGuard[Matrix]:
return t.ndim == 2
def is_psd_generalized_matrix(t: Tensor) -> TypeGuard[PSDGeneralizedMatrix]:
half_dim = t.ndim // 2
return t.ndim % 2 == 0 and t.shape[:half_dim] == t.shape[: half_dim - 1 : -1]
# We do not check that t is PSD as it is expensive, but this must be checked in the tests of
# every function that uses this TypeGuard by using `assert_psd_generalized_matrix`.
def is_psd_matrix(t: Tensor) -> TypeGuard[PSDMatrix]:
return t.ndim == 2 and t.shape[0] == t.shape[1]
# We do not check that t is PSD as it is expensive, but this must be checked in the tests of
# every function that uses this TypeGuard, by using `assert_psd_matrix`.