| 1 |
""" |
| 2 |
pint.facets.measurement.objects |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
:copyright: 2022 by Pint Authors, see AUTHORS for more details. |
| 6 |
:license: BSD, see LICENSE for more details. |
| 7 |
""" |
| 8 |
|
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import copy |
| 12 |
import re |
| 13 |
from typing import Generic |
| 14 |
|
| 15 |
from ...compat import ufloat |
| 16 |
from ..plain import MagnitudeT, PlainQuantity, PlainUnit |
| 17 |
|
| 18 |
MISSING = object() |
| 19 |
|
| 20 |
|
| 21 |
class MeasurementQuantity(Generic[MagnitudeT], PlainQuantity[MagnitudeT]): |
| 22 |
# Measurement support |
| 23 |
def plus_minus(self, error, relative=False): |
| 24 |
if isinstance(error, self.__class__): |
| 25 |
if relative: |
| 26 |
raise ValueError(f"{error} is not a valid relative error.") |
| 27 |
error = error.to(self._units).magnitude |
| 28 |
else: |
| 29 |
if relative: |
| 30 |
error = error * abs(self.magnitude) |
| 31 |
|
| 32 |
return self._REGISTRY.Measurement(copy.copy(self.magnitude), error, self._units) |
| 33 |
|
| 34 |
|
| 35 |
class MeasurementUnit(PlainUnit): |
| 36 |
pass |
| 37 |
|
| 38 |
|
| 39 |
class Measurement(PlainQuantity): |
| 40 |
"""Implements a class to describe a quantity with uncertainty. |
| 41 |
|
| 42 |
Parameters |
| 43 |
---------- |
| 44 |
value : pint.Quantity or any numeric type |
| 45 |
The expected value of the measurement |
| 46 |
error : pint.Quantity or any numeric type |
| 47 |
The error or uncertainty of the measurement |
| 48 |
|
| 49 |
Returns |
| 50 |
------- |
| 51 |
|
| 52 |
""" |
| 53 |
|
| 54 |
def __new__(cls, value, error=MISSING, units=MISSING): |
| 55 |
if units is MISSING: |
| 56 |
try: |
| 57 |
value, units = value.magnitude, value.units |
| 58 |
except AttributeError: |
| 59 |
# if called with two arguments and the first looks like a ufloat |
| 60 |
# then assume the second argument is the units, keep value intact |
| 61 |
if hasattr(value, "nominal_value"): |
| 62 |
units = error |
| 63 |
error = MISSING # used for check below |
| 64 |
else: |
| 65 |
units = "" |
| 66 |
if error is MISSING: |
| 67 |
# We've already extracted the units from the Quantity above |
| 68 |
mag = value |
| 69 |
else: |
| 70 |
try: |
| 71 |
error = error.to(units).magnitude |
| 72 |
except AttributeError: |
| 73 |
pass |
| 74 |
if error < 0: |
| 75 |
raise ValueError("The magnitude of the error cannot be negative") |
| 76 |
else: |
| 77 |
mag = ufloat(value, error) |
| 78 |
|
| 79 |
inst = super().__new__(cls, mag, units) |
| 80 |
return inst |
| 81 |
|
| 82 |
@property |
| 83 |
def value(self): |
| 84 |
return self._REGISTRY.Quantity(self.magnitude.nominal_value, self.units) |
| 85 |
|
| 86 |
@property |
| 87 |
def error(self): |
| 88 |
return self._REGISTRY.Quantity(self.magnitude.std_dev, self.units) |
| 89 |
|
| 90 |
@property |
| 91 |
def rel(self): |
| 92 |
return abs(self.magnitude.std_dev / self.magnitude.nominal_value) |
| 93 |
|
| 94 |
def __reduce__(self): |
| 95 |
# See notes in Quantity.__reduce__ |
| 96 |
from pint import _unpickle_measurement |
| 97 |
|
| 98 |
return _unpickle_measurement, (Measurement, self.magnitude, self._units) |
| 99 |
|
| 100 |
def __repr__(self): |
| 101 |
return "<Measurement({}, {}, {})>".format( |
| 102 |
self.magnitude.nominal_value, self.magnitude.std_dev, self.units |
| 103 |
) |
| 104 |
|
| 105 |
def __str__(self): |
| 106 |
return f"{self}" |
| 107 |
|
| 108 |
def __format__(self, spec): |
| 109 |
spec = spec or self._REGISTRY.default_format |
| 110 |
return self._REGISTRY.formatter.format_measurement(self, spec) |
| 111 |
|
| 112 |
def old_format(self, spec): |
| 113 |
# TODO: provisional |
| 114 |
from ...formatting import _FORMATS, extract_custom_flags, siunitx_format_unit |
| 115 |
|
| 116 |
# special cases |
| 117 |
if "Lx" in spec: # the LaTeX siunitx code |
| 118 |
# the uncertainties module supports formatting |
| 119 |
# numbers in value(unc) notation (i.e. 1.23(45) instead of 1.23 +/- 0.45), |
| 120 |
# using type code 'S', which siunitx actually accepts as input. |
| 121 |
# However, the implementation is incompatible with siunitx. |
| 122 |
# Uncertainties will do 9.1(1.1), which is invalid, should be 9.1(11). |
| 123 |
# TODO: add support for extracting options |
| 124 |
# |
| 125 |
# Get rid of this code, we'll deal with it here |
| 126 |
spec = spec.replace("Lx", "") |
| 127 |
# The most compatible format from uncertainties is the default format, |
| 128 |
# but even this requires fixups. |
| 129 |
# For one, SIUnitx does not except some formats that unc does, like 'P', |
| 130 |
# and 'S' is broken as stated, so... |
| 131 |
spec = spec.replace("S", "").replace("P", "") |
| 132 |
# get SIunitx options |
| 133 |
# TODO: allow user to set this value, somehow |
| 134 |
opts = _FORMATS["Lx"]["siopts"] |
| 135 |
if opts != "": |
| 136 |
opts = r"[" + opts + r"]" |
| 137 |
# SI requires space between "+-" (or "\pm") and the nominal value |
| 138 |
# and uncertainty, and doesn't accept "+/-", so this setting |
| 139 |
# selects the desired replacement. |
| 140 |
pm_fmt = _FORMATS["Lx"]["pm_fmt"] |
| 141 |
mstr = format(self.magnitude, spec).replace(r"+/-", pm_fmt) |
| 142 |
# Also, SIunitx doesn't accept parentheses, which uncs uses with |
| 143 |
# scientific notation ('e' or 'E' and sometimes 'g' or 'G'). |
| 144 |
mstr = mstr.replace("(", "").replace(")", " ") |
| 145 |
ustr = siunitx_format_unit(self.units._units.items(), self._REGISTRY) |
| 146 |
return rf"\SI{opts}{{{mstr}}}{{{ustr}}}" |
| 147 |
|
| 148 |
# standard cases |
| 149 |
if "L" in spec: |
| 150 |
newpm = pm = r" \pm " |
| 151 |
pars = _FORMATS["L"]["parentheses_fmt"] |
| 152 |
elif "P" in spec: |
| 153 |
newpm = pm = "±" |
| 154 |
pars = _FORMATS["P"]["parentheses_fmt"] |
| 155 |
else: |
| 156 |
newpm = pm = "+/-" |
| 157 |
pars = _FORMATS[""]["parentheses_fmt"] |
| 158 |
|
| 159 |
if "C" in spec: |
| 160 |
sp = "" |
| 161 |
newspec = spec.replace("C", "") |
| 162 |
pars = _FORMATS["C"]["parentheses_fmt"] |
| 163 |
else: |
| 164 |
sp = " " |
| 165 |
newspec = spec |
| 166 |
|
| 167 |
if "H" in spec: |
| 168 |
newpm = "±" |
| 169 |
newspec = spec.replace("H", "") |
| 170 |
pars = _FORMATS["H"]["parentheses_fmt"] |
| 171 |
|
| 172 |
mag = format(self.magnitude, newspec).replace(pm, sp + newpm + sp) |
| 173 |
if "(" in mag: |
| 174 |
# Exponential format has its own parentheses |
| 175 |
pars = "{}" |
| 176 |
|
| 177 |
if "L" in newspec and "S" in newspec: |
| 178 |
mag = mag.replace("(", r"\left(").replace(")", r"\right)") |
| 179 |
|
| 180 |
if "L" in newspec: |
| 181 |
space = r"\ " |
| 182 |
else: |
| 183 |
space = " " |
| 184 |
|
| 185 |
uspec = extract_custom_flags(spec) |
| 186 |
ustr = format(self.units, uspec) |
| 187 |
if not ("uS" in newspec or "ue" in newspec or "u%" in newspec): |
| 188 |
mag = pars.format(mag) |
| 189 |
|
| 190 |
if "H" in spec: |
| 191 |
# Fix exponential format |
| 192 |
mag = re.sub(r"\)e\+0?(\d+)", r")×10<sup>\1</sup>", mag) |
| 193 |
mag = re.sub(r"\)e-0?(\d+)", r")×10<sup>-\1</sup>", mag) |
| 194 |
|
| 195 |
return mag + space + ustr |