unitx 0.13.3__tar.gz → 0.13.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. {unitx-0.13.3 → unitx-0.13.4}/CHANGELOG.md +13 -0
  2. {unitx-0.13.3 → unitx-0.13.4}/PKG-INFO +4 -4
  3. {unitx-0.13.3 → unitx-0.13.4}/README.md +3 -3
  4. {unitx-0.13.3 → unitx-0.13.4}/docs/README.md +1 -1
  5. {unitx-0.13.3 → unitx-0.13.4}/docs/display.md +20 -0
  6. {unitx-0.13.3 → unitx-0.13.4}/examples/README.md +4 -3
  7. unitx-0.13.4/examples/arrhenius_fit.ipynb +236 -0
  8. {unitx-0.13.3 → unitx-0.13.4}/pyproject.toml +1 -1
  9. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/_display.py +21 -0
  10. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/affineunit.py +1 -1
  11. {unitx-0.13.3 → unitx-0.13.4}/tests/test_display.py +40 -0
  12. {unitx-0.13.3 → unitx-0.13.4}/tests/test_typing.py +25 -0
  13. {unitx-0.13.3 → unitx-0.13.4}/.github/workflows/ci.yml +0 -0
  14. {unitx-0.13.3 → unitx-0.13.4}/.github/workflows/release.yml +0 -0
  15. {unitx-0.13.3 → unitx-0.13.4}/.gitignore +0 -0
  16. {unitx-0.13.3 → unitx-0.13.4}/CONTRIBUTING.md +0 -0
  17. {unitx-0.13.3 → unitx-0.13.4}/LICENSE +0 -0
  18. {unitx-0.13.3 → unitx-0.13.4}/benchmarks/numpy_writes.py +0 -0
  19. {unitx-0.13.3 → unitx-0.13.4}/conftest.py +0 -0
  20. {unitx-0.13.3 → unitx-0.13.4}/docs/affine.md +0 -0
  21. {unitx-0.13.3 → unitx-0.13.4}/docs/catalogue.md +0 -0
  22. {unitx-0.13.3 → unitx-0.13.4}/docs/custom-units.md +0 -0
  23. {unitx-0.13.3 → unitx-0.13.4}/docs/images/blackbody.svg +0 -0
  24. {unitx-0.13.3 → unitx-0.13.4}/docs/migration.md +0 -0
  25. {unitx-0.13.3 → unitx-0.13.4}/docs/numpy.md +0 -0
  26. {unitx-0.13.3 → unitx-0.13.4}/docs/scalars.md +0 -0
  27. {unitx-0.13.3 → unitx-0.13.4}/docs/serialization.md +0 -0
  28. {unitx-0.13.3 → unitx-0.13.4}/docs/stdlib.md +0 -0
  29. {unitx-0.13.3 → unitx-0.13.4}/docs/typing.md +0 -0
  30. {unitx-0.13.3 → unitx-0.13.4}/docs/units.md +0 -0
  31. {unitx-0.13.3 → unitx-0.13.4}/examples/blackbody.ipynb +0 -0
  32. {unitx-0.13.3 → unitx-0.13.4}/examples/damped_oscillator.ipynb +0 -0
  33. {unitx-0.13.3 → unitx-0.13.4}/examples/gaussian_wavepacket.ipynb +0 -0
  34. {unitx-0.13.3 → unitx-0.13.4}/examples/optical_attenuation.ipynb +0 -0
  35. {unitx-0.13.3 → unitx-0.13.4}/examples/pendulum_uncertainty.ipynb +0 -0
  36. {unitx-0.13.3 → unitx-0.13.4}/pyrightconfig.json +0 -0
  37. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/__init__.py +0 -0
  38. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/_constnamespace.py +0 -0
  39. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/_conversion.py +0 -0
  40. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/_immutable.py +0 -0
  41. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/_numerics.py +0 -0
  42. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/_numpy.py +0 -0
  43. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/_numpy_typing.py +0 -0
  44. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/_unicode.py +0 -0
  45. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/affinequantity.py +0 -0
  46. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/dimension.py +0 -0
  47. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/exceptions.py +0 -0
  48. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/factor.py +0 -0
  49. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/math.py +0 -0
  50. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/monomial.py +0 -0
  51. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/py.typed +0 -0
  52. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/quantity.py +0 -0
  53. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/serialization.py +0 -0
  54. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/si/__init__.py +0 -0
  55. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/si/bases.py +0 -0
  56. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/si/constants.py +0 -0
  57. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/si/units.py +0 -0
  58. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/singleunit.py +0 -0
  59. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/time.py +0 -0
  60. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/unit.py +0 -0
  61. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/unitparser.py +0 -0
  62. {unitx-0.13.3 → unitx-0.13.4}/src/unitx/unitregistry.py +0 -0
  63. {unitx-0.13.3 → unitx-0.13.4}/tests/__init__.py +0 -0
  64. {unitx-0.13.3 → unitx-0.13.4}/tests/_notebooks.py +0 -0
  65. {unitx-0.13.3 → unitx-0.13.4}/tests/example_typing/check_blackbody.py +0 -0
  66. {unitx-0.13.3 → unitx-0.13.4}/tests/numpy_typing/check_math.py +0 -0
  67. {unitx-0.13.3 → unitx-0.13.4}/tests/numpy_typing/check_numpy.py +0 -0
  68. {unitx-0.13.3 → unitx-0.13.4}/tests/test_affine.py +0 -0
  69. {unitx-0.13.3 → unitx-0.13.4}/tests/test_affinequantity.py +0 -0
  70. {unitx-0.13.3 → unitx-0.13.4}/tests/test_builtin_definitions.py +0 -0
  71. {unitx-0.13.3 → unitx-0.13.4}/tests/test_dimension.py +0 -0
  72. {unitx-0.13.3 → unitx-0.13.4}/tests/test_examples.py +0 -0
  73. {unitx-0.13.3 → unitx-0.13.4}/tests/test_factor.py +0 -0
  74. {unitx-0.13.3 → unitx-0.13.4}/tests/test_immutable.py +0 -0
  75. {unitx-0.13.3 → unitx-0.13.4}/tests/test_import.py +0 -0
  76. {unitx-0.13.3 → unitx-0.13.4}/tests/test_math.py +0 -0
  77. {unitx-0.13.3 → unitx-0.13.4}/tests/test_math_numpy.py +0 -0
  78. {unitx-0.13.3 → unitx-0.13.4}/tests/test_monomial.py +0 -0
  79. {unitx-0.13.3 → unitx-0.13.4}/tests/test_numeric.py +0 -0
  80. {unitx-0.13.3 → unitx-0.13.4}/tests/test_numpy.py +0 -0
  81. {unitx-0.13.3 → unitx-0.13.4}/tests/test_numpy_affine.py +0 -0
  82. {unitx-0.13.3 → unitx-0.13.4}/tests/test_numpy_differentiation.py +0 -0
  83. {unitx-0.13.3 → unitx-0.13.4}/tests/test_numpy_integration.py +0 -0
  84. {unitx-0.13.3 → unitx-0.13.4}/tests/test_numpy_multi_outputs.py +0 -0
  85. {unitx-0.13.3 → unitx-0.13.4}/tests/test_numpy_mutation.py +0 -0
  86. {unitx-0.13.3 → unitx-0.13.4}/tests/test_numpy_outputs.py +0 -0
  87. {unitx-0.13.3 → unitx-0.13.4}/tests/test_numpy_products.py +0 -0
  88. {unitx-0.13.3 → unitx-0.13.4}/tests/test_numpy_statistics.py +0 -0
  89. {unitx-0.13.3 → unitx-0.13.4}/tests/test_quantity.py +0 -0
  90. {unitx-0.13.3 → unitx-0.13.4}/tests/test_serialization.py +0 -0
  91. {unitx-0.13.3 → unitx-0.13.4}/tests/test_si.py +0 -0
  92. {unitx-0.13.3 → unitx-0.13.4}/tests/test_singleunit.py +0 -0
  93. {unitx-0.13.3 → unitx-0.13.4}/tests/test_siunitx_display.py +0 -0
  94. {unitx-0.13.3 → unitx-0.13.4}/tests/test_time.py +0 -0
  95. {unitx-0.13.3 → unitx-0.13.4}/tests/test_unicode.py +0 -0
  96. {unitx-0.13.3 → unitx-0.13.4}/tests/test_unicode_units.py +0 -0
  97. {unitx-0.13.3 → unitx-0.13.4}/tests/test_unit.py +0 -0
  98. {unitx-0.13.3 → unitx-0.13.4}/tests/test_unit_definition.py +0 -0
  99. {unitx-0.13.3 → unitx-0.13.4}/tests/test_unitparser.py +0 -0
  100. {unitx-0.13.3 → unitx-0.13.4}/tests/test_unitregistry.py +0 -0
  101. {unitx-0.13.3 → unitx-0.13.4}/tests/test_warnings.py +0 -0
  102. {unitx-0.13.3 → unitx-0.13.4}/tests/typing/check_affine.py +0 -0
  103. {unitx-0.13.3 → unitx-0.13.4}/tests/typing/check_math_time.py +0 -0
  104. {unitx-0.13.3 → unitx-0.13.4}/tests/typing/check_quantity.py +0 -0
  105. {unitx-0.13.3 → unitx-0.13.4}/tests/typing/check_serialization.py +0 -0
  106. {unitx-0.13.3 → unitx-0.13.4}/tests/typing/check_si.py +0 -0
@@ -2,6 +2,19 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.13.4] - 2026-10-23
6
+
7
+ ### Fixed
8
+
9
+ - Preserve exact extra scales and structural unit formatting for affine points
10
+ in anonymous zero-origin linear coordinates across text, LaTeX, HTML and siunitx.
11
+ Stored readings and named coordinate labels are unchanged.
12
+
13
+ ### Added
14
+
15
+ - Add an Arrhenius fitting notebook with absolute temperatures, activation-energy
16
+ estimates and standard errors, a fitted curve and first-order rate predictions.
17
+
5
18
  ## [0.13.3] - 2026-10-22
6
19
 
7
20
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: unitx
3
- Version: 0.13.3
3
+ Version: 0.13.4
4
4
  Summary: Physical units, quantities, and unit conversion with exact unit algebra, type hints, and NumPy integration.
5
5
  Project-URL: Homepage, https://github.com/DaitTHU/unitx
6
6
  Project-URL: Documentation, https://github.com/DaitTHU/unitx/blob/main/docs/README.md
@@ -195,9 +195,9 @@ Use `.value` or `.value_in(unit)` at plotting and external-library boundaries.
195
195
  implicit unit removal. NumPy's type stubs do not describe every wrapped
196
196
  operation; see the [typing guide](https://github.com/DaitTHU/unitx/blob/main/docs/typing.md).
197
197
 
198
- The [physics notebooks](https://github.com/DaitTHU/unitx/blob/main/examples/README.md)
199
- cover blackbody radiation, damped motion, wave-packet spreading, attenuation,
200
- and measurement uncertainty.
198
+ The [scientific examples](https://github.com/DaitTHU/unitx/blob/main/examples/README.md)
199
+ cover reaction-rate fitting, blackbody radiation, damped motion, wave-packet
200
+ spreading, attenuation, and measurement uncertainty.
201
201
 
202
202
  ## Blackbody radiation
203
203
 
@@ -167,9 +167,9 @@ Use `.value` or `.value_in(unit)` at plotting and external-library boundaries.
167
167
  implicit unit removal. NumPy's type stubs do not describe every wrapped
168
168
  operation; see the [typing guide](https://github.com/DaitTHU/unitx/blob/main/docs/typing.md).
169
169
 
170
- The [physics notebooks](https://github.com/DaitTHU/unitx/blob/main/examples/README.md)
171
- cover blackbody radiation, damped motion, wave-packet spreading, attenuation,
172
- and measurement uncertainty.
170
+ The [scientific examples](https://github.com/DaitTHU/unitx/blob/main/examples/README.md)
171
+ cover reaction-rate fitting, blackbody radiation, damped motion, wave-packet
172
+ spreading, attenuation, and measurement uncertainty.
173
173
 
174
174
  ## Blackbody radiation
175
175
 
@@ -19,7 +19,7 @@ reading about an older version.
19
19
  | Save and restore scalar quantities as JSON-compatible records | [Scalar data exchange](serialization.md) |
20
20
  | Understand annotations and NumPy inference limits | [Typing](typing.md) |
21
21
  | Update code written for an earlier release | [Migration notes](migration.md) |
22
- | Run scientific examples | [Physics notebooks](../examples/README.md) |
22
+ | Run scientific examples | [Scientific examples](../examples/README.md) |
23
23
  | Test or contribute a change | [Contributing](../CONTRIBUTING.md) |
24
24
 
25
25
  For a first read, follow units and quantities, then the catalogue. Read the
@@ -17,6 +17,26 @@ markup or raw TeX commands. Unicode symbols remain Unicode and require font
17
17
  support in the renderer. These strings are for presentation, not serialization.
18
18
  `repr()` and `Unit.expression()` keep their existing reconstruction contracts.
19
19
 
20
+ An AffineQuantity in an anonymous zero-origin linear coordinate displays its
21
+ complete difference Unit, including any extra scale and rational powers. The
22
+ stored reading is unchanged. Named coordinates keep their own labels:
23
+
24
+ ```pycon
25
+ >>> from unitx.unit import ScaledUnit
26
+ >>> from unitx.factor import Factor
27
+ >>> point = 3 @ ScaledUnit('m', scale=Factor(2))
28
+ >>> str(point)
29
+ '3⋅2⋅m'
30
+ >>> format(point, '.2f')
31
+ '3.00 (2⋅m)'
32
+ >>> point.to_quantity('m').value
33
+ Fraction(6, 1)
34
+
35
+ ```
36
+
37
+ LaTeX, HTML and siunitx use the same structural unit rendering as a linear
38
+ Quantity with that complete Unit; formatting never converts the reading.
39
+
20
40
  ## Quantity format syntax
21
41
 
22
42
  `format(q, 'numeric_spec;style')`, or `f'{q:numeric_spec;style}'`, selects:
@@ -1,4 +1,4 @@
1
- # Physics notebooks
1
+ # Scientific examples
2
2
 
3
3
  These notebooks use unitx for dimensional calculations and NumPy for numerical
4
4
  work. Each contains a model, assumptions, plots, and numerical checks. The
@@ -11,6 +11,7 @@ material parameters and measurement draws are illustrative, not experimental dat
11
11
  | [Gaussian wave packet](gaussian_wavepacket.ipynb) | Free electron propagation and uncertainty | Probability-density units, quantum constants, unit-aware integration |
12
12
  | [Optical attenuation](optical_attenuation.ipynb) | Transmission through absorbing layers | prod/multiply.reduce, input masks, Quantity initial, fixed-unit out |
13
13
  | [Pendulum uncertainty](pendulum_uncertainty.ipynb) | Correlated input uncertainties and Monte Carlo propagation | Mean/std/var units, mixed measurement units, explicit quantiles |
14
+ | [Arrhenius fit](arrhenius_fit.ipynb) | Estimate activation energy from synthetic reaction rates | Absolute temperatures, regression boundary, parameter units and model-based standard errors |
14
15
 
15
16
  ## Run
16
17
 
@@ -22,8 +23,8 @@ python -m pip install -e '.[numpy]' matplotlib jupyterlab
22
23
  jupyter lab examples/
23
24
  ```
24
25
 
25
- Open a notebook and run all cells from the beginning. These notebooks require
26
- unitx 0.8.4 or newer for product reductions and unit-aware integration.
26
+ Open a notebook and run all cells from the beginning. Use the current checkout
27
+ so that all demonstrated APIs are available.
27
28
  The examples do not download datasets or write files. Keep physical quantities in calculations;
28
29
  plot their `.value` and derive labels from their `.unit`. Convert only to choose
29
30
  a useful display scale or to align units at a numerical boundary. Quantiles use
@@ -0,0 +1,236 @@
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "id": "arrhenius_fit-00",
6
+ "metadata": {},
7
+ "source": [
8
+ "# Estimate an activation energy from reaction-rate data\n",
9
+ "\n",
10
+ "Fit a temperature-dependent first-order rate constant, estimate its molar\n",
11
+ "activation energy, and predict a rate and half-life inside the observed interval.\n",
12
+ "Run the setup in [examples/README.md](README.md) first.\n",
13
+ "\n",
14
+ "The [IUPAC Arrhenius equation](https://goldbook.iupac.org/terms/view/A00446) is\n",
15
+ "$$\n",
16
+ "k(T)=A\\exp\\!\\left(-\\frac{E_a}{RT}\\right).\n",
17
+ "$$\n",
18
+ "Here $T$ is absolute temperature, $R$ is the molar gas constant, $E_a$ is the\n",
19
+ "molar activation energy, and $A$ has the same units as the rate constant $k$.\n",
20
+ "We assume $E_a$ and $A$ remain constant over this temperature interval.\n",
21
+ "\n",
22
+ "These are **synthetic data**, not measurements of a named reaction. They were\n",
23
+ "generated with $E_a=52\\,\\mathrm{kJ/mol}$ and $A=2\\times10^7\\,\\mathrm{s^{-1}}$,\n",
24
+ "with fixed log-rate perturbations $[0.020,-0.025,0.010,-0.015,0.025,-0.015]$,\n",
25
+ "then rounded. The known generating parameters provide a numerical check;\n",
26
+ "they do not validate the model for a real reaction."
27
+ ]
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "id": "arrhenius_fit-01",
32
+ "metadata": {},
33
+ "source": [
34
+ "import numpy as np\n",
35
+ "from matplotlib import pyplot as plt\n",
36
+ "\n",
37
+ "from unitx import math\n",
38
+ "from unitx.si import SI, si\n",
39
+ "\n",
40
+ "# Recorded Celsius temperatures are points, not temperature differences.\n",
41
+ "temperature_readings = np.asarray([15, 25, 35, 45, 55, 65]) @ si.degC\n",
42
+ "temperature = temperature_readings.to_quantity(si.K)\n",
43
+ "rate = np.asarray([0.458888, 0.908486, 1.858462, 3.430419, 6.499562, 10.972105]) / si.min\n",
44
+ "reference_rate = 1 / si.min"
45
+ ],
46
+ "execution_count": null,
47
+ "outputs": []
48
+ },
49
+ {
50
+ "cell_type": "markdown",
51
+ "id": "arrhenius_fit-02",
52
+ "metadata": {},
53
+ "source": [
54
+ "## Fit at an explicit numerical boundary\n",
55
+ "\n",
56
+ "Normalize the rate before taking its logarithm:\n",
57
+ "$$\n",
58
+ "x=\\frac{1}{T},\\qquad y=\\ln\\!\\left(\\frac{k}{k_{\\rm ref}}\\right),\\qquad\n",
59
+ " y=mx+b.\n",
60
+ "$$\n",
61
+ "Thus $m=-E_a/R$ has unit K, $b=\\ln(A/k_{\\rm ref})$ is dimensionless, and\n",
62
+ "$$\n",
63
+ "E_a=-mR,\\qquad A=k_{\\rm ref}\\exp(b).\n",
64
+ "$$\n",
65
+ "\n",
66
+ "The temperatures have already been converted to K, so `(1 / temperature).value`\n",
67
+ "contains inverse temperatures in K$^{-1}$. `np.polyfit` receives these numerical\n",
68
+ "values and the dimensionless log rates. Attach K to its fitted slope before\n",
69
+ "continuing the physical calculation. Keep the fitted scalars in NumPy's\n",
70
+ "floating-point domain; unitx's NumPy adapter evaluates catalogue constants in\n",
71
+ "that domain without changing `SI.R`."
72
+ ]
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "id": "arrhenius_fit-03",
77
+ "metadata": {},
78
+ "source": [
79
+ "log_rate = math.log(rate / reference_rate)\n",
80
+ "coefficients, covariance = np.polyfit(\n",
81
+ " (1 / temperature).value,\n",
82
+ " log_rate.value,\n",
83
+ " deg=1,\n",
84
+ " cov=True,\n",
85
+ ")\n",
86
+ "slope = np.float64(coefficients[0]) * si.K\n",
87
+ "slope_standard_error = np.sqrt(np.float64(covariance[0, 0])) * slope.unit\n",
88
+ "activation_energy = (-slope * SI.R).to('kJ/mol')\n",
89
+ "energy_standard_error = (slope_standard_error * SI.R).to(activation_energy.unit)\n",
90
+ "prefactor = (reference_rate * math.exp(np.float64(coefficients[1]))).to('s^-1')\n",
91
+ "\n",
92
+ "print(f'Activation energy: {activation_energy:.3f}')\n",
93
+ "print(f'Standard error from residual scatter: {energy_standard_error:.3f}')\n",
94
+ "print(f'Prefactor: {prefactor:.4g}')"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "markdown",
101
+ "id": "arrhenius_fit-04",
102
+ "metadata": {},
103
+ "source": [
104
+ "## Interpret and plot the fit\n",
105
+ "\n",
106
+ "Ordinary least squares here assumes negligible temperature error and independent\n",
107
+ "log-rate errors with a common variance. The covariance returned by `polyfit`\n",
108
+ "estimates that variance from residual scatter, using $6-2=4$ residual degrees\n",
109
+ "of freedom. Therefore $R\\sqrt{\\operatorname{Cov}_{00}}$ is a model-based standard\n",
110
+ "error for $E_a$, not a confidence interval or a measure of systematic error.\n",
111
+ "The estimates of $A$ and $E_a$ are correlated; no prediction uncertainty band is\n",
112
+ "computed here.\n",
113
+ "\n",
114
+ "Expect an activation energy near $51.9\\,\\mathrm{kJ/mol}$ with standard error\n",
115
+ "near $0.45\\,\\mathrm{kJ/mol}$. Plot a dimensionless inverse-temperature coordinate,\n",
116
+ "$1000\\,\\mathrm{K}/T$. The label is derived from the same scale used in the plot.\n",
117
+ "The curve spans only the observed temperature range."
118
+ ]
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "id": "arrhenius_fit-05",
123
+ "metadata": {},
124
+ "source": [
125
+ "curve_temperature = (\n",
126
+ " np.linspace(temperature.value.min(), temperature.value.max(), 200, dtype=np.float64) * si.K\n",
127
+ ")\n",
128
+ "curve_rate = prefactor * math.exp(-activation_energy / (SI.R * curve_temperature))\n",
129
+ "temperature_scale = 1000 * si.K\n",
130
+ "plot_temperature = temperature_scale / temperature\n",
131
+ "curve_coordinate = temperature_scale / curve_temperature\n",
132
+ "\n",
133
+ "fig, ax = plt.subplots(figsize=(6, 4), layout='constrained')\n",
134
+ "ax.scatter(plot_temperature.value, log_rate.value, label='Synthetic observations')\n",
135
+ "ax.plot(\n",
136
+ " curve_coordinate.value,\n",
137
+ " math.log(curve_rate / reference_rate).value,\n",
138
+ " label='Arrhenius fit',\n",
139
+ ")\n",
140
+ "ax.set(\n",
141
+ " xlabel=f'{temperature_scale} / T',\n",
142
+ " ylabel='ln(k / k_ref)',\n",
143
+ " title='Activation-energy fit',\n",
144
+ ")\n",
145
+ "ax.legend()\n",
146
+ "ax.grid(True, alpha=0.25)\n",
147
+ "plt.show()"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "markdown",
154
+ "id": "arrhenius_fit-06",
155
+ "metadata": {},
156
+ "source": [
157
+ "## Predict inside the observed interval\n",
158
+ "\n",
159
+ "At a fixed temperature, a first-order decay obeys $c(t)=c(0)\\exp(-kt)$, hence\n",
160
+ "$$\n",
161
+ "t_{1/2}=\\frac{\\ln 2}{k}.\n",
162
+ "$$\n",
163
+ "Use the fitted parameters to predict at $40\\,{}^\\circ\\mathrm C$, inside the\n",
164
+ "15--65 $^\\circ\\mathrm C$ data interval. Convert the temperature point to a Kelvin\n",
165
+ "quantity before evaluating the exponent. This is a prediction under the stated\n",
166
+ "Arrhenius and first-order models, with no allowance for model error."
167
+ ]
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "id": "arrhenius_fit-07",
172
+ "metadata": {},
173
+ "source": [
174
+ "prediction_reading = np.float64(40) @ si.degC\n",
175
+ "prediction_temperature = prediction_reading.to_quantity(si.K)\n",
176
+ "predicted_rate = prefactor * math.exp(-activation_energy / (SI.R * prediction_temperature))\n",
177
+ "half_life = (math.log(2) / predicted_rate).to(si.s)\n",
178
+ "\n",
179
+ "print(f'Predicted rate at {prediction_reading}: {predicted_rate.to(rate.unit):.4f}')\n",
180
+ "print(f'First-order half-life: {half_life:.2f}')"
181
+ ],
182
+ "execution_count": null,
183
+ "outputs": []
184
+ },
185
+ {
186
+ "cell_type": "markdown",
187
+ "id": "arrhenius_fit-08",
188
+ "metadata": {},
189
+ "source": [
190
+ "## Numerical checks\n",
191
+ "\n",
192
+ "Compare the estimates with the known generating parameters. Also check that\n",
193
+ "converting the input rate storage unit does not alter the normalized fit data,\n",
194
+ "and that the reconstructed physical model agrees with the fitted straight line.\n",
195
+ "The half-life identity checks the prediction's time/rate units together."
196
+ ]
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "id": "arrhenius_fit-09",
201
+ "metadata": {},
202
+ "source": [
203
+ "assert activation_energy.isclose(52 * si.kJ / si.mol, rel_tol=0.02)\n",
204
+ "assert prefactor.isclose(2e7 / si.s, rel_tol=0.1)\n",
205
+ "assert (predicted_rate * half_life).isclose(math.log(2), rel_tol=1e-12)\n",
206
+ "np.testing.assert_allclose(\n",
207
+ " math.log(rate.to('s^-1') / reference_rate).value,\n",
208
+ " log_rate.value,\n",
209
+ " rtol=1e-12,\n",
210
+ " atol=1e-12,\n",
211
+ ")\n",
212
+ "fitted_rate = prefactor * math.exp(-activation_energy / (SI.R * temperature))\n",
213
+ "np.testing.assert_allclose(\n",
214
+ " math.log(fitted_rate / reference_rate).value,\n",
215
+ " coefficients[0] * (1 / temperature).value + coefficients[1],\n",
216
+ " rtol=1e-12,\n",
217
+ " atol=1e-12,\n",
218
+ ")"
219
+ ],
220
+ "execution_count": null,
221
+ "outputs": []
222
+ }
223
+ ],
224
+ "metadata": {
225
+ "kernelspec": {
226
+ "display_name": "Python 3",
227
+ "language": "python",
228
+ "name": "python3"
229
+ },
230
+ "language_info": {
231
+ "name": "python"
232
+ }
233
+ },
234
+ "nbformat": 4,
235
+ "nbformat_minor": 5
236
+ }
@@ -4,7 +4,7 @@ build-backend = 'hatchling.build'
4
4
 
5
5
  [project]
6
6
  name = 'unitx'
7
- version = '0.13.3'
7
+ version = '0.13.4'
8
8
  description = 'Physical units, quantities, and unit conversion with exact unit algebra, type hints, and NumPy integration.'
9
9
  readme = 'README.md'
10
10
  requires-python = '>=3.12'
@@ -18,6 +18,21 @@ type Style = Literal['latex', 'html']
18
18
  _DECIMAL_NUMBER = re.compile(r'([+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+))(?:[eE]([+-]?[0-9]+))?')
19
19
 
20
20
 
21
+ def _display_unit(unit: Unit | AffineUnit) -> Unit | AffineUnit:
22
+ """Render an unnamed zero-origin linear coordinate through its complete Unit."""
23
+ from .affineunit import AffineUnit
24
+
25
+ if (
26
+ isinstance(unit, AffineUnit)
27
+ and unit._definition is None
28
+ and unit.kind is None
29
+ and unit.origin.value == 0
30
+ and unit.origin.unit == unit.delta_unit
31
+ ):
32
+ return unit.delta_unit
33
+ return unit
34
+
35
+
21
36
  def latex_text(text: str) -> str:
22
37
  """Escape literal text, including characters that can terminate math mode."""
23
38
  replacements = {
@@ -83,6 +98,7 @@ def unit_body(unit: Unit | AffineUnit, style: Style, *, fraction: bool = True) -
83
98
  from .factor import one
84
99
  from .unit import ScaledUnit
85
100
 
101
+ unit = _display_unit(unit)
86
102
  if isinstance(unit, AffineUnit):
87
103
  return latex_text(unit.symbol) if style == 'latex' else escape(unit.symbol)
88
104
  components = [(str(base), exp) for base, exp in unit._monomial.components()]
@@ -148,6 +164,7 @@ def quantity_body(
148
164
  from .factor import one
149
165
  from .unit import ScaledUnit
150
166
 
167
+ unit = _display_unit(unit)
151
168
  # Delegate formatting without coercing Decimal, Fraction, arrays or custom scalars.
152
169
  text = format_magnitude(value, spec)
153
170
  magnitude = rich_magnitude(value, text, spec, style)
@@ -175,6 +192,7 @@ def siunitx_unit_parts(unit: Unit | AffineUnit) -> tuple[str, bool]:
175
192
  """Return a unit argument and whether siunitx should parse it."""
176
193
  from .affineunit import AffineUnit
177
194
 
195
+ unit = _display_unit(unit)
178
196
  if isinstance(unit, AffineUnit):
179
197
  return '{' + unit.to_latex() + '}', False
180
198
  from .factor import one
@@ -196,6 +214,7 @@ def siunitx_quantity(value: object, unit: Unit | AffineUnit, spec: str) -> str:
196
214
  from .factor import one
197
215
  from .unit import ScaledUnit
198
216
 
217
+ unit = _display_unit(unit)
199
218
  text = format_magnitude(value, spec)
200
219
  options: list[str] = []
201
220
  # Recognize only ordinary ASCII decimal/scientific notation. All other
@@ -217,6 +236,7 @@ def siunitx_quantity(value: object, unit: Unit | AffineUnit, spec: str) -> str:
217
236
 
218
237
 
219
238
  def text_quantity(value: object, unit: Unit | AffineUnit) -> str:
239
+ unit = _display_unit(unit)
220
240
  unit_text = str(unit)
221
241
  if unit_text == '1':
222
242
  return str(value)
@@ -231,6 +251,7 @@ def text_quantity(value: object, unit: Unit | AffineUnit) -> str:
231
251
  def format_quantity(value: object, unit: Unit | AffineUnit, format_spec: str) -> str:
232
252
  from .factor import one
233
253
 
254
+ unit = _display_unit(unit)
234
255
  if not format_spec:
235
256
  return text_quantity(value, unit)
236
257
  # A semicolon used as a Python fill character belongs to the numeric spec.
@@ -153,7 +153,7 @@ class AffineUnit(_Immutable):
153
153
  if self._definition is not None:
154
154
  return self._definition.symbol
155
155
  if self.kind is None and self.origin.value == 0 and self.origin.unit == self.delta_unit:
156
- return self.delta_unit.symbol
156
+ return str(self.delta_unit)
157
157
  return f'affine({self.origin})'
158
158
 
159
159
  @property
@@ -8,8 +8,10 @@ from fractions import Fraction
8
8
 
9
9
  import pytest
10
10
 
11
+ from unitx.affinequantity import AffineQuantity
11
12
  from unitx.factor import Factor
12
13
  from unitx.quantity import Quantity
14
+ from unitx.si import si
13
15
  from unitx.unit import ScaledUnit, Unit
14
16
 
15
17
 
@@ -46,6 +48,44 @@ def test_scaled_unit_keeps_exact_scale():
46
48
  assert ScaledUnit('m', Factor(2) ** Fraction(1, 2)).to_latex() == (r'\text{2}^{1/2}\,\text{m}')
47
49
 
48
50
 
51
+ @pytest.mark.parametrize(
52
+ 'unit',
53
+ [
54
+ Unit(),
55
+ ScaledUnit('m', scale=Factor(2)),
56
+ ScaledUnit('m', scale=Factor(Fraction(2, 3))),
57
+ ScaledUnit('', scale=Factor(2)),
58
+ ScaledUnit('s^(-1/2)', scale=Factor(2) ** Fraction(1, 3)),
59
+ ],
60
+ )
61
+ def test_affine_quantity_zero_origin_display(unit):
62
+ value = Decimal('3.00')
63
+ point = AffineQuantity(value, unit)
64
+ linear = Quantity(value, unit)
65
+ assert point.unit.symbol == str(unit)
66
+ assert str(point) == str(linear)
67
+ for spec in ('', '.2f', ';text', '.2f;latex', ';html', ';siunitx'):
68
+ assert format(point, spec) == format(linear, spec)
69
+ for fraction in (True, False):
70
+ assert point.to_latex(fraction=fraction) == linear.to_latex(fraction=fraction)
71
+ assert point.unit.to_latex(fraction=fraction) == unit.to_latex(fraction=fraction)
72
+ assert point.to_html() == linear.to_html()
73
+ assert point.to_siunitx() == linear.to_siunitx()
74
+ assert point.unit.to_html() == unit.to_html()
75
+ assert point.unit.to_siunitx() == unit.to_siunitx()
76
+ assert point._repr_latex_() == '$' + point.to_latex() + '$'
77
+ assert point._repr_html_() == point.to_html()
78
+ assert point.value is value
79
+ assert point.unit.delta_unit is unit
80
+
81
+
82
+ @pytest.mark.parametrize('coordinate', [si.K, si.degC, si.dBm])
83
+ def test_affine_quantity_named_zero_origin_display(coordinate):
84
+ point = 3 @ coordinate
85
+ assert str(point) == f'3 {coordinate.symbol}'
86
+ assert point.to_latex() == r'\text{3}\,' + coordinate.to_latex()
87
+
88
+
49
89
  @pytest.mark.parametrize('spec', ['', '.2f', '>12.3e', ';text', '.1f;latex', '.1f;html'])
50
90
  def test_format_numeric_delegation(spec):
51
91
  q = Quantity(Decimal('12.345'), 'm/s')
@@ -62,6 +62,31 @@ def test_numpy_example_type_hints(tmp_path: Path) -> None:
62
62
  _check_type_hints(str(tmp_path))
63
63
 
64
64
 
65
+ def test_arrhenius_fit_type_hints(tmp_path: Path) -> None:
66
+ if find_spec('numpy') is None or find_spec('matplotlib') is None:
67
+ pytest.skip('NumPy and Matplotlib are optional')
68
+ example = Path(__file__).resolve().parents[1] / 'examples' / 'arrhenius_fit.ipynb'
69
+ # Check the actual notebook's inferred members. Basic checking alone allows
70
+ # Any/Unknown to hide lost Quantity wrappers and subplot completion.
71
+ assertions = """
72
+ from typing import assert_type
73
+ from matplotlib.axes import Axes
74
+ from matplotlib.figure import Figure
75
+ from unitx import Unit
76
+
77
+ assert_type(curve_temperature.unit, Unit)
78
+ assert_type(curve_temperature.value.dtype, np.dtype[np.float64])
79
+ assert_type(activation_energy.unit, Unit)
80
+ assert_type(predicted_rate.unit, Unit)
81
+ assert_type(fig, Figure)
82
+ assert_type(ax, Axes)
83
+ """
84
+ (tmp_path / f'{example.stem}.py').write_text(
85
+ notebook_source(example) + assertions, encoding='utf-8'
86
+ )
87
+ _check_type_hints(str(tmp_path))
88
+
89
+
65
90
  def test_asarray_type_hints() -> None:
66
91
  if find_spec('numpy') is None:
67
92
  pytest.skip('NumPy is optional')
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes