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 | class PhysicalDimension(BaseModel):
"""
Pydantic model adding unit and scale to standard ndarray.
"""
value: NDArray
unit: str = ""
scale: Literal["lin", "dB"] = "lin"
class Config:
arbitrary_types_allowed = True
def dB(self):
"""
Convert the Physical dimension to decibel.
"""
v = self.value
v_db = v if self.scale == "dB" else 10 * np.log10(np.abs(v))
out = self.__class__(value=v_db, scale="dB", unit=self.unit)
return out
def lin(self):
"""
Convert the Physical dimension to linear magnitude.
"""
v = self.value
v_lin = 10 ** (v / 10) if self.scale == "dB" else v
return self.__class__(value=v_lin, scale="lin", unit=self.unit)
def __getitem__(self, item):
return self.__class__(
value=self.value[item],
scale=self.scale,
unit=self.unit,
)
def __setitem__(self, key, value):
self.value[key] = value
@property
def shape(self):
return self.value.shape
def __sub__(self, other):
return self.__operator(other, "-")
def __rsub__(self, other):
return self.__operator(other, "-") * -1
def __add__(self, other):
return self.__operator(other, "+")
def __radd__(self, other):
return self.__operator(other, "+")
def __truediv__(self, other):
return self.__operator(other, "/")
def __mul__(self, other):
return self.__operator(other, "*")
def __rmul__(self, other):
return self.__operator(other, "*")
def __pow__(self, other):
return self.__operator(other, "**")
def __eq__(self, other):
if isinstance(other, PhysicalDimension):
return (
self.unit == other.unit
and self.scale == other.scale
and np.all(self.value == other.value)
)
else:
return np.all(self.value == other)
def __lt__(self, other):
return np.all(self.value < other.value)
def __round__(self, x):
return self.__class__(
value=np.round(self.value, x), scale=self.scale, unit=self.unit
)
def __ceil__(self):
return self.__class__(
value=np.ceil(self.value), scale=self.scale, unit=self.unit
)
def rint(self):
return np.rint(self.value)
def sqrt(self):
return np.sqrt(self.value)
def __operator(self, l_b, op):
b = l_b.value if isinstance(l_b, PhysicalDimension) else l_b
if op == "+":
res = self.value + b
if op == "-":
res = self.value - b
if op == "/":
res = self.value / b
if op == "*":
res = self.value * b
if op == "**":
res = self.value**b
return self.__class__(value=np.array(res), scale=self.scale, unit=self.unit)
|