Skip to content

Commit fff3ffc

Browse files
Merge pull request #27 from quantumlib/format
Format files and fix some typos
2 parents c451c27 + ca8c775 commit fff3ffc

File tree

10 files changed

+81
-71
lines changed

10 files changed

+81
-71
lines changed

test/test_protos.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from typing import cast
1516
import itertools
1617
import pytest
1718
import numpy as np
@@ -75,7 +76,9 @@ def test_valuearray_conversion_trip(unit: Value) -> None:
7576
def test_complex_valuearray_conversion_trip(unit: Value) -> None:
7677
rs = np.random.RandomState(0)
7778
for real, imag in zip(rs.random((4, 2, 4, 3)), rs.random((4, 2, 4, 3))):
78-
v = (real + 1j * imag) * unit
79+
real_ = cast(np.typing.NDArray[np.float64], real)
80+
value = real_ + 1j * imag
81+
v = unit * value
7982
got = ValueArray.from_proto(v.to_proto())
8083
assert got.unit == unit
8184
np.testing.assert_allclose(got.value, real + 1j * imag)

test/test_value.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -208,12 +208,12 @@ def test_hash() -> None:
208208
def test_numpy_sqrt() -> None:
209209
from tunits.units import m, km, cm
210210

211-
u = np.sqrt(8 * km * m) - cm
211+
u: Value = np.sqrt(8 * km * m) - cm
212212
v = 8943.27191 * cm
213213
assert np.isclose(u / v, 1)
214214

215-
u = np.sqrt(8 * km / m)
215+
u = np.sqrt(8 * km / m) # type: ignore[assignment]
216216
assert np.isclose(u, 89.4427191)
217217

218-
u = np.sqrt((8 * km / m).in_base_units())
218+
u = np.sqrt((8 * km / m).in_base_units()) # type: ignore[assignment]
219219
assert np.isclose(u, 89.4427191)

test/test_value_array.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from packaging.version import Version
1516
import numpy as np
1617
import pytest
1718
from tunits.core import raw_WithUnit, raw_UnitArray
@@ -92,9 +93,16 @@ def test_repr() -> None:
9293
assert repr(km ** (2 / 3.0) * [-1] / kg**3 * s) == "ValueArray(array([-1.]), 'km^(2/3)*s/kg^3')"
9394

9495
# Numpy abbreviation is allowed.
95-
assert repr(list(range(50000)) * km) == (
96-
"LengthArray(array([ 0, 1, " "2, ..., 49997, 49998, 49999]), 'km')"
97-
)
96+
if Version(np.__version__) >= Version('2.2'):
97+
expected_repr = (
98+
"LengthArray(array([ 0, 1, "
99+
"2, ..., 49997, 49998, 49999], shape=(50000,)), 'km')"
100+
)
101+
else:
102+
expected_repr = (
103+
"LengthArray(array([ 0, 1, " "2, ..., 49997, 49998, 49999]), 'km')"
104+
)
105+
assert repr(list(range(50000)) * km) == expected_repr
98106

99107
# Fallback case.
100108
v: ValueArray = raw_WithUnit(

tunits/core/__init__.pyi

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,10 @@ class WithUnit:
219219
class Value(WithUnit):
220220
"""A floating-point value with associated units."""
221221

222+
value: float | complex
223+
real: 'Value'
224+
imag: 'Value'
225+
222226
@classmethod
223227
def from_proto(cls: type[T], msg: tunits_pb2.Value) -> T: ...
224228
def to_proto(self, msg: tunits_pb2.Value | None = None) -> tunits_pb2.Value: ...
@@ -302,9 +306,13 @@ class Value(WithUnit):
302306
def __getitem__(self, key: Any) -> float: ...
303307

304308
class ValueArray(WithUnit):
309+
value: NDArray[Any]
310+
real: 'ValueArray'
311+
imag: 'ValueArray'
312+
305313
@classmethod
306314
def from_proto(cls: type[T], msg: tunits_pb2.ValueArray) -> T: ...
307-
def to_proto(self, msg: tunits_pb2.ValueArray | None) -> tunits_pb2.ValueArray: ...
315+
def to_proto(self, msg: tunits_pb2.ValueArray | None = None) -> tunits_pb2.ValueArray: ...
308316
def __init__(self, data: Any, unit: Any = None) -> None: ...
309317
def allclose(self, other: ValueArray, *args: Any, **kwargs: dict[str, Any]) -> bool: ...
310318
def __array__(self, dtype: DTypeLike = None) -> NDArray[Any]: ...

tunits/core/cython/dimension.pyx

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import abc
3131

3232
from functools import cache
3333

34+
3435
class Dimension(abc.ABC):
3536
"""Dimension abstraction.
3637
@@ -62,8 +63,7 @@ class _Acceleration(Dimension):
6263
@cache
6364
def valid_base_units() -> tuple[Value, ...]:
6465
return (
65-
default_unit_database.known_units['m']
66-
/ default_unit_database.known_units['s'] ** 2,
66+
default_unit_database.known_units['m'] / default_unit_database.known_units['s'] ** 2,
6767
)
6868

6969
def _value_class(self) -> type[Value]:
@@ -74,13 +74,14 @@ class _Acceleration(Dimension):
7474

7575

7676
class ValueWithDimension(Dimension, Value):
77-
def __init__(self, val, unit=None, validate:bool=True):
77+
def __init__(self, val, unit=None, validate: bool = True):
7878
super().__init__(val, unit=unit)
7979
if validate and not type(self).is_valid(self):
8080
raise ValueError(f'{self.unit} is not a valid unit for dimension {type(self)}')
8181

82+
8283
class ArrayWithDimension(Dimension, ValueArray):
83-
def __init__(self, val, unit=None, validate:bool=True):
84+
def __init__(self, val, unit=None, validate: bool = True):
8485
super().__init__(val, unit=unit)
8586
if validate and not type(self).is_valid(self):
8687
raise ValueError(f'{self.unit} is not a valid unit for dimension {type(self)}')
@@ -121,9 +122,7 @@ class _AngularFrequency(Dimension):
121122
@cache
122123
def valid_base_units() -> tuple[Value, ...]:
123124
return (
124-
default_unit_database.known_units['rad']
125-
* default_unit_database.known_units['Hz']
126-
* 2,
125+
default_unit_database.known_units['rad'] * default_unit_database.known_units['Hz'] * 2,
127126
)
128127

129128
def _value_class(self) -> type[Value]:
@@ -228,8 +227,7 @@ class _Density(Dimension):
228227
@cache
229228
def valid_base_units() -> tuple[Value, ...]:
230229
return (
231-
default_unit_database.known_units['kg']
232-
/ default_unit_database.known_units['m'] ** 3,
230+
default_unit_database.known_units['kg'] / default_unit_database.known_units['m'] ** 3,
233231
)
234232

235233
def _value_class(self) -> type[Value]:
@@ -554,10 +552,8 @@ class _Noise(Dimension):
554552
@cache
555553
def valid_base_units() -> tuple[Value, ...]:
556554
return (
557-
default_unit_database.known_units['V']
558-
/ default_unit_database.known_units['Hz'] ** 0.5,
559-
default_unit_database.known_units['watt']
560-
/ default_unit_database.known_units['Hz'],
555+
default_unit_database.known_units['V'] / default_unit_database.known_units['Hz'] ** 0.5,
556+
default_unit_database.known_units['watt'] / default_unit_database.known_units['Hz'],
561557
)
562558

563559
def _value_class(self) -> type[Value]:
@@ -658,10 +654,7 @@ class _Speed(Dimension):
658654
@staticmethod
659655
@cache
660656
def valid_base_units() -> tuple[Value, ...]:
661-
return (
662-
default_unit_database.known_units['m']
663-
/ default_unit_database.known_units['s'],
664-
)
657+
return (default_unit_database.known_units['m'] / default_unit_database.known_units['s'],)
665658

666659
def _value_class(self) -> type[Value]:
667660
return Speed
@@ -682,8 +675,7 @@ class _SurfaceDensity(Dimension):
682675
@cache
683676
def valid_base_units() -> tuple[Value, ...]:
684677
return (
685-
default_unit_database.known_units['kg']
686-
/ default_unit_database.known_units['m'] ** 2,
678+
default_unit_database.known_units['kg'] / default_unit_database.known_units['m'] ** 2,
687679
)
688680

689681
def _value_class(self) -> type[Value]:
@@ -745,8 +737,7 @@ class _Torque(Dimension):
745737
@cache
746738
def valid_base_units() -> tuple[Value, ...]:
747739
return (
748-
default_unit_database.known_units['newton']
749-
* default_unit_database.known_units['m'],
740+
default_unit_database.known_units['newton'] * default_unit_database.known_units['m'],
750741
)
751742

752743
def _value_class(self) -> type[Value]:

tunits/core/cython/proto.pyx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ _SERIALIZATION_ERROR_MESSAGE = (
6666
@functools.cache
6767
def _construct_unit(unit_enum: int, scale_enum: Optional[int] = None) -> 'Value':
6868
from tunits.proto import tunits_pb2
69+
6970
unit_name = _PROTO_TO_UNIT_STRING.get(tunits_pb2.UnitEnum.Name(unit_enum), None)
7071
scale = '' if scale_enum is None else _ENUM_TO_SCALE_SYMBOL[scale_enum]
7172
return _try_interpret_as_with_unit(scale + unit_name)

tunits/core/cython/unit_database.pyx

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,7 @@ class UnitDatabase:
5151
self.add_root_unit(unit_name)
5252
return self.known_units[unit_name]
5353

54-
def parse_unit_formula(
55-
self, formula: str, auto_create: Optional[bool] = None
56-
) -> Value:
54+
def parse_unit_formula(self, formula: str, auto_create: Optional[bool] = None) -> Value:
5755
"""
5856
:param str formula: Describes a combination of units.
5957
:param None|bool auto_create: If this is set, missing unit strings will
@@ -109,7 +107,12 @@ class UnitDatabase:
109107
"""
110108
ua = UnitArray(unit_name)
111109
unit: Value = raw_WithUnit(
112-
1, {'factor': 1.0, 'ratio': {'numer': 1, 'denom': 1}, 'exp10': 0}, ua, ua, Value, ValueArray
110+
1,
111+
{'factor': 1.0, 'ratio': {'numer': 1, 'denom': 1}, 'exp10': 0},
112+
ua,
113+
ua,
114+
Value,
115+
ValueArray,
113116
)
114117
self.add_unit(unit_name, unit)
115118

@@ -152,7 +155,8 @@ class UnitDatabase:
152155
},
153156
parent.base_units,
154157
UnitArray(unit_name),
155-
Value, ValueArray
158+
Value,
159+
ValueArray,
156160
)
157161

158162
self.add_unit(unit_name, unit)

tunits/core/cython/unit_mismatch_error.pyx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,4 @@ class UnitMismatchError(Exception):
2222

2323

2424
class NotTUnitsLikeError(Exception):
25-
"""The value is not a tunits object and can't be converted to one."""
25+
"""The value is not a tunits object and can't be converted to one."""

tunits/core/cython/with_unit_value.pyx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,10 @@ class Value(WithUnit):
3030
else:
3131
raise ValueError(f"{msg=} doesn't have a value.")
3232
return cls(v, _proto_to_units(msg.units))
33-
33+
3434
def to_proto(self, msg: Optional['tunits_pb2.Value'] = None) -> 'tunits_pb2.Value':
3535
from tunits.proto import tunits_pb2
36+
3637
if msg is None:
3738
msg = tunits_pb2.Value()
3839
if isinstance(self.value, (complex, np.complexfloating)):

tunits/proto/tunits.proto

Lines changed: 29 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -20,37 +20,37 @@ option java_multiple_files = true;
2020

2121
// Units supported for serialization.
2222
enum UnitEnum {
23-
DECIBEL = 1; // Power unit (dB).
24-
DECIBEL_MILLIWATTS = 2; // Decibel-milliwatts (dBm).
25-
RADIANS = 3; // Radians (rad).
26-
HERTZ = 4; // Frequency unit (Hz).
27-
VOLT = 5; // Electric potential Unit (V).
28-
SECOND = 6; // Time unit (s).
23+
DECIBEL = 1; // Power unit (dB).
24+
DECIBEL_MILLIWATTS = 2; // Decibel-milliwatts (dBm).
25+
RADIANS = 3; // Radians (rad).
26+
HERTZ = 4; // Frequency unit (Hz).
27+
VOLT = 5; // Electric potential Unit (V).
28+
SECOND = 6; // Time unit (s).
2929
}
3030

3131
enum Scale {
3232
// Enum value should be the associated exponent.
33-
YOTTA = 24; // 10^24
34-
ZETTA = 21; // 10^21
35-
EXA = 18; // 10^18
36-
PETA = 15; // 10^15
37-
TERA = 12; // 10^12
38-
GIGA = 9; // 10^9
39-
MEGA = 6; // 10^6
40-
KILO = 3; // 10^3
41-
HECTO = 2; // 10^2
42-
DECAD = 1; // 10^1
43-
UNITY = 0; // 1
44-
DECI = -1; // 10^-1
45-
CENTI = -2; // 10^-2
46-
MILLI = -3; // 10^-3
47-
MICRO = -6; // 10^-6
48-
NANO = -9; // 10^-9
49-
PICO = -12; // 10^-12
50-
FEMTO = -15; // 10^-15
51-
ATTO = -18; // 10^-18
52-
ZEPTO = -21; // 10^-21
53-
YOCTO = -24; // 10^-24
33+
YOTTA = 24; // 10^24
34+
ZETTA = 21; // 10^21
35+
EXA = 18; // 10^18
36+
PETA = 15; // 10^15
37+
TERA = 12; // 10^12
38+
GIGA = 9; // 10^9
39+
MEGA = 6; // 10^6
40+
KILO = 3; // 10^3
41+
HECTO = 2; // 10^2
42+
DECAD = 1; // 10^1
43+
UNITY = 0; // 1
44+
DECI = -1; // 10^-1
45+
CENTI = -2; // 10^-2
46+
MILLI = -3; // 10^-3
47+
MICRO = -6; // 10^-6
48+
NANO = -9; // 10^-9
49+
PICO = -12; // 10^-12
50+
FEMTO = -15; // 10^-15
51+
ATTO = -18; // 10^-18
52+
ZEPTO = -21; // 10^-21
53+
YOCTO = -24; // 10^-24
5454
}
5555

5656
// The exponent of a unit e.g.
@@ -79,17 +79,14 @@ message Value {
7979
// Units are repeated to represent combinations of units (e.g. V*s and mV/us).
8080
// Units are combined through multiplication.
8181
repeated Unit units = 1;
82-
8382
oneof value {
8483
double real_value = 2;
8584
Complex complex_value = 3;
8685
}
8786
}
8887

8988
message DoubleArray {
90-
repeated double values = 1 [
91-
packed = true
92-
];
89+
repeated double values = 1 [packed = true];
9390
}
9491

9592
message ComplexArray {
@@ -102,14 +99,11 @@ message ValueArray {
10299
// Units are repeated to represent combinations of units (e.g. V*s and mV/us).
103100
// Units are combined through multiplication.
104101
repeated Unit units = 1;
105-
106102
oneof values {
107103
// The flattened array.
108104
DoubleArray reals = 2;
109105
ComplexArray complexes = 3;
110106
}
111107

112-
repeated uint32 shape = 4 [
113-
packed = true
114-
]; // The shape of the array.
108+
repeated uint32 shape = 4 [packed = true]; // The shape of the array.
115109
}

0 commit comments

Comments
 (0)