Repository navigation
Releases: DaitTHU/unitx
Release list
v0.8.5
Adds unit-aware numpy.modf and numpy.frexp, including controlled writes to both outputs, partial None outputs, boolean masks, and conversion to fixed target units. All outputs are staged before writing; overlapping output buffers are rejected. Decomposition uses the input's stored coordinates, and frexp returns a unit-bearing mantissa and a bare integer exponent.
The release also consolidates NumPy function dispatch and fixes README links for PyPI. Reconstruction examples use numpy.ldexp to avoid intermediate overflow for extreme finite floating values.
Validation: Python 3.12 with NumPy 2.5.3 (2960 passed, 2 skipped), NumPy 2.1.0 (2959 passed, 3 skipped), and no NumPy (2577 passed, 20 skipped). Ruff, Pyright, executable documentation, wheel/sdist metadata, and installed-package runtime and typing checks passed. Each NumPy version passed 278 installed-package regressions.
v0.8.4
NumPy calculations
- Add
np.prodandnp.multiply.reducewith exact product units, scalarinitialvalues (including Quantities), boolean input masks, and stagedoutwrites. Dimensional results require the same selected element count in every output slice; dimensionless inputs normalize before reduction. - Add
np.trapezoidwith Quantity ordinates, coordinates, or scalar spacing. The result combines ordinate and coordinate units while preserving NumPy's coordinate order and axis behavior. - Keep comparison-to-ufunc mapping in the optional NumPy adapter and remove redundant Fractionable guards.
Physics notebooks
Convert the blackbody example to a notebook and add damped oscillations, a free Gaussian wave packet, absorbing optical layers, and correlated pendulum measurement uncertainties. Calculations retain Quantities and plot labels follow their units. Notebook sources are committed without outputs or embedded figures.
Browse the five notebooks and setup instructions.
Validated with NumPy 2.1 and 2.5 and with NumPy absent, including installed-wheel runtime and type consumers. Python >= 3.12; NumPy remains optional (unitx[numpy], NumPy >= 2.1). See the support matrix for the precise boundaries.
v0.8.3
Added
- Support unit-aware
outfor sum, mean, median, std, var, cumsum,
concatenate, stack, and add.reduce/accumulate. Require the exact result shape,
preserve target identity, unit, and dtype, and stage computation, conversion,
and casting before writing. Argmin/argmax accept bare integer ndarray outputs. - Document function/reduction output casting and add regressions for scaled
units, positional outputs, overlapping/strided buffers, and unchanged outputs
on failure, plus installed-consumer type checks.
v0.8.2
Fix NumPy scalar interoperability and improve editor type inference without recursive Scalar arithmetic constraints.
- Decimal and Fraction operands, including SI.h and SI.kB, enter NumPy calculations as floats while stored constants and Python scalar behavior remain unchanged. Dimensional powers retain exact rational unit exponents.
- Array results expose concrete ndarray/NumPy-scalar types and native
.valuemethods; transpose preserves the magnitude type. Add strict checks for NumPy consumers and scalar consumers without NumPy. - Rewrite the README and add a runnable, illustrated blackbody example using
np.asarray([3000, 4000, 5000]) * si.Kwithout specifying dtype. Automatic inference for this construction is verified with NumPy 2.5 stubs; older stubs can still infer Any, although runtime support remains NumPy >= 2.1.
Validation: complete local suites on Python 3.12 and 3.13; minimum NumPy 2.1 runtime/typing checks; strict installed-wheel consumers with and without NumPy; Ruff, documentation examples, wheel/sdist build, and strict Twine metadata checks.
This patch does not add item assignment, true in-place operations, reduction outputs, or additional array backends.
v0.8.1
Added
- Support
outfor covered single-output NumPy ufunc calls. Numeric results
write to compatible Quantity ndarray buffers after unit conversion; boolean
comparisons and predicates write to bare boolean ndarrays. Preserve target
identity, dtype, unit, and masked-out values, including overlapping views. - Stage computation, unit conversion, and casting before writing; validation
and temporary computation failures leave the target unchanged. Function and
reduction outputs, item assignment, and multi-output ufuncs remain unsupported.
v0.8.0
Added
- Add optional NumPy >= 2.1 support through
unitx[numpy], with one Quantity
wrapping an entire plain numeric ndarray or NumPy numeric scalar. Preserve
input objects in botharray * unitandunit * arrayconstruction. - Support unit-aware conversion, broadcasting arithmetic and comparisons,
matrix multiplication, indexing, iteration, array metadata, transpose, and
flattening. Preserve NumPy scalar indexing and view/copy behavior. - Implement a documented set of NumPy ufuncs and functions, including roots,
dimensionless transcendental functions, concatenation, statistics, predicates,
and position queries. Keep exact unit exponents and ScaledUnit factors. - Extend Quantity.isclose with symmetric array comparisons and broadcasting
tolerances; implement NumPy isclose/allclose with their own defaults and
asymmetric formula. Validate tolerance dimensions, finiteness, and signs. - Add runtime and installed-consumer typing coverage, import-order and optional
dependency checks, and CI jobs for minimum and current NumPy versions.
Changed
- Define
Scalar,Array, andMagnitude = Scalar | Arrayin_numerics.
Preserve concrete magnitude types at construction and in unit-only operations;
use conservative result types for array numerical operations. - Keep Python scalar arithmetic, Decimal behavior, and exact scalar comparisons
independent of the optional NumPy adapter. Array conversion follows the
documented NumPy promotion, rounding, and overflow rules.
NumPy scope
- Document the supported function/keyword matrix and precision/storage rules in
docs/numpy.md. Other array backends, ndarray subclasses, object/boolean
magnitudes, and implicit list/tuple conversion are unsupported. - Reject implicit unit removal by
np.asarray(q)ornp.array(q); use.value
or.value_in(unit)explicitly. NumPy magnitudes produce unhashable Quantities. - Reject writable out, item assignment, and operations that would require
heterogeneous units. Python augmented assignment creates and rebinds a result.
v0.7.1
Added
- Accept a single exact spelling string for
prefixable, equivalent to a
one-element tuple, with the same spelling validation before registration. - Expand the
sinamespace's prefixed shortcuts and common units, including
percent, permille, permyriad, rotational frequency (rpm), speed of light
(c), gram-force, volt-ampere, ampere-hour, mho, and nit. Enable Torr prefixes. - Add
SI.kappaand the wavelength and frequency Wien displacement constants,
SI.bandSI.b_.
Changed
- Use fixed Decimal approximations with about 50 significant digits for pi and
the positive roots in the Wien displacement laws. Derived constants still use
the Decimal context active at import. - Treat
uandDaas spellings of one formal unit, with prefixes enabled only
onDa. Rebuild stored units when migrating from the separateuidentity;
the mass conversion scale is unchanged. UsekDarather thankilodalton. - Keep ASCII micro spellings such as
umandusconvenient to type without
warnings. The explicit productu mretains its separate mass-times-length
meaning.
Full changelog: v0.7.0...v0.7.1
v0.7.0
unitx 0.7.0 adds clearer unit spelling policies and richer unit-expression syntax, and shares the SI definitions used by units and physical constants.
Highlights
prefixable: PrefixPolicy = Trueaccepts a bool or tuple of registered unit spellings, such as('arcsec', 'arcsecond'). Only listed spellings accept prefixes. The existing True/False behavior remains available.- Use
[registered name]inside products, reciprocals, and powers. Standalone hyphenated names and adjacent Unicode integer superscripts such asm²ands⁻¹²are supported. - Unit definitions, spelling resolution, and registration validation now share
unitx.unitregistry, including the publicPrefixPolicytype alias. - SI units and constants share coherent base definitions.
lyderives from the speed of light and Julian year;eVderives from the elementary charge and volt. - The catalog includes are, hectare, Julian year, fixed month interval, light year, unified atomic mass unit, reactive power, and additional common prefixed attributes.
mHgis the registered prefixable unit;mmHguses its milli prefix. The existing pressure conversion scale is preserved, and stacked prefixes are rejected.
Migration
- Square brackets and integer superscripts are reserved syntax and cannot occur in custom registered spellings. Rename affected definitions before rebuilding stored objects.
mmHghas the formal identity of milli-prefixedmHg; rebuild stored units when upgrading. Its conversion scale is unchanged.- Registering
uintroduces ambiguity warnings for ASCII micro spellings such asum. Their meaning is unchanged; useµm,μm, ormicrometreto avoid the warning. ktremains a knot alias; tonne remains unprefixable.yrremains 365 days, whilea_jis exactly 365.25 days.mois one twelfth of a Julian year, not a calendar month.
Validation
- Python 3.12 with the built-in factorization backend: 2528 passed, 2 skipped, including Pyright.
- Python 3.13 with SymPy: 2529 passed (type checks run separately under Python 3.12).
- Ruff, README examples, fresh-process imports, and 2685 spelling/expression round trips passed.
- Wheel/sdist metadata, installed-wheel runtime checks, py.typed packaging, installed README examples, and a strict external Pyright consumer passed.
v0.6.3
Added
- Add
Quantity.value_in(unit)to return the same magnitude and concrete type as.to(unit).valuewithout constructing a temporary quantity. The target unit is required and accepts a string or Unit, including ScaledUnit. - Add
Quantity.isclose()for symmetric real scalar comparisons with relative and absolute tolerances in coherent SI units. Nonzero absolute tolerances for dimensional quantities must carry matching units. Rational coefficients remain exact; residual irrational factors are approximated. Zero tolerances use exact equality. - Make quantity truth values follow their magnitudes, so zero quantities are false regardless of unit.
Changed
- Apply native magnitude operators in operand order for arithmetic, unary operations, and numerical powers, preserving numerical promotion, Decimal contexts, signals, and exceptions. Support the scalar operand types accepted by the magnitude, including complex values and custom scalars.
- Keep Decimal conversions and arithmetic in Decimal. Rational conversions combine the magnitude and scale exactly before rounding once in the active context; identity conversions preserve the original magnitude. Addition and subtraction align integer operands in the Decimal domain when paired with Decimal magnitudes. Derived SI constants use Decimal arithmetic and
Decimal(str(math.pi))where an approximate pi is required, with evaluation in the context active at import. - Interpret float formal exponents by their shortest decimal text, without a denominator limit, consistently across Monomial, Dimension, Factor, SymbolicConstant, Unit, and Quantity. For example,
0.1represents1/10and1e-10remains nonzero. Numeric scale inputs to Factor retain their existing denominator-limit and warning rules. - Cache rationalized Factor decompositions lazily, independently of numerical value evaluation, while preserving equality, hashing, copying, and serialization.
- Update public type hints, examples, and regression coverage for conversion, native arithmetic, comparisons, and formal exponents.
Fixed
- Preserve native comparisons, including independent
!=, Decimal signals, and complex ordering errors, when unit factors agree. Across different factors, compare builtin real values and complex components using exact coefficients, retaining consistent hashes for equal quantities and native unhashability for custom magnitudes.
Migration
- Decimal arithmetic no longer converts operands to Fraction automatically. Mixing Decimal with float or Fraction in arithmetic now raises the native TypeError; explicitly choose a common numerical type when needed. Decimal conversion and derived SI constants can therefore have different result types and rounding from earlier releases.
- Quantity numerical powers use the original exponent object; for example, an integer magnitude raised to
2.0produces a float. UseFraction(1, 3)for an exactly one-third formal exponent: the float1 / 3now represents the decimal0.3333333333333333and does not simplify as exactly one third.
v0.6.2
Added
- Support multiplication and division between Quantity and Factor or SymbolicConstant in both operand orders. Multiplication and right-hand division preserve the magnitude and its type, combining the exact factor with the unit's scale; left-hand division takes the reciprocal magnitude and scales the reciprocal unit. Ordinary numeric operands continue to operate on the magnitude.
- Preserve generic magnitude types in the corresponding public type hints, with runtime and static regression coverage for exact scaling and reciprocal operations.
Changed
- Combine the compact exact scale and formal units in ScaledUnit string output, grouping denominator factors into one product, such as
J⋅s/(2⋅π). - Display quantities with scaled units using the combined product and multiplication dots between adjacent numeric factors, such as
3⋅60⋅s, without evaluating the exact scale. String output remains readable display rather than parser input;repr()retains reconstructible state. - Document exact-factor quantity arithmetic and the distinction between a symbolic expression such as
SI.h / (2 * PI)and predefinedSI.hbar, which continues to expose its numerical value in ordinaryJ*sunits.