pqu package¶
Submodules¶
pqu.NumberDict module¶
Dictionary storing numerical values.
-
class
pqu.NumberDict.
NumberDict
[source]¶ Bases:
dict
An instance of this class acts like an array of numbers with generalized (non-integer) indices. A value of zero is assumed for undefined entries. NumberDict instances support addition, and subtraction with other NumberDict instances, and multiplication and division by scalars.
This class is used by the PhysicalUnit class to track units and their power. For example, for the unit ‘m**2 / kg**3’, the dictionary items are [(‘kg’, -3), (‘m’, 2)].
pqu.PQU module¶
Introduction¶
This module contains classes and functions for representing and manipulating a value with units and uncertainty, herein called a “Physical Quantity with Uncertainty” or PQU. For example, if the distance between start and finish lines is measured to be ‘100.1 m’ with an uncertainty of ‘0.4 m’, it can be inputted to PQU as the string ‘100.1(4) m’ or ‘100.1 +/- 0.4 m’ (both are allowed input forms as well as several others - see `PQU`_).
From this module, most users should only need the PQU class which stores a PQU object and supports common math operations (e.g., addition, subtraction, multiplication) including the operation on the units and uncertainty. For example, if a person races between the start and finish lines in a time of ‘16.3 +/- 0.1 s’, the PQU class can be used to determine the person’s speed as:
>>> from pqu import PQU
>>> distance = PQU.PQU( '100.1(4) m' )
>>> time = PQU.PQU( '16.3 +/- 0.1 s' )
>>> speed = distance / time
>>> print speed
6.14 +/- 0.04 m/s
>>> print speed.copyToUnit( 'mi/h' )
13.7 +/- 0.1 mi/h
In addition to calculating the speed and unit, the PQU class has also propagated the significant digits and the uncertainty. In this example the uncertainty was propagated using Goodman’s expression for uncorrelated values (see Uncertainty propagation). The propagation of significant digits explains why the printed speed has only 3 digits. The following Python code illustrates significant digits for the speed calculation:
>>> print 100.1 / 16.3
6.14110429448
>>> print float( speed )
6.14110429448
>>> print speed.info( )
value = 6.14110429447852724e+00, significantDigits = 3, order = 0, isPercent = False, unit = "m/s"
uncertainty = value = 4.49629906071862956e-02, significantDigits = 1, order = -2, isPercent = False
As can be seen, the internal speed value is as expected. However, since the PQU class (with the help of the pqu_float class) tracks a value’s significant digits, when a PQU instance is printed (via the __str__ method), only at most ‘significantDigits’ are displayed. The allowed range for ‘significantDigits’ is 1 to sys.float_info.dig + 1 inclusive. For addition and subtraction, the member ‘order’ is also required and is why the following output is the same for both print statements:
>>> print distance
100.1(4) m
>>> print distance + '100.1(4) mum' # note 'mum' is micrometer
100.1 +/- 0.4 m
How is ‘significantDigits’ determined? That depends on how PQU is called. If a string without uncertainty is entered as the only argument then ‘significantDigits’ is the number of digits in the string (ignoring leading ‘0’). Some examples are:
>>> print PQU.PQU( '12.345' ).info( )
value = 1.23450000000000006e+01, significantDigits = 5, order = 1, isPercent = False, unit = ""
uncertainty =
>>> print PQU.PQU( '12.34500' ).info( )
value = 1.23450000000000006e+01, significantDigits = 7, order = 1, isPercent = False, unit = ""
uncertainty =
>>> print PQU.PQU( '12.34500e-12' ).info( )
value = 1.23450000000000004e-11, significantDigits = 7, order = -11, isPercent = False, unit = ""
uncertainty =
>>> print PQU.PQU( '0012.34500e-12' ).info( )
value = 1.23450000000000004e-11, significantDigits = 7, order = -11, isPercent = False, unit = ""
uncertainty =
>>> print PQU.PQU( '00.0012' ).info( )
value = 1.19999999999999989e-03, significantDigits = 2, order = -3, isPercent = False, unit = ""
uncertainty =
If the string has an uncertainty, then it is also used in calculating ‘significantDigits’. Some examples are (note - these are the same as the last examples, with uncertainties added):
>>> print PQU.PQU( '12.345 +/- 1e-8' ).info( )
value = 1.23450000000000006e+01, significantDigits = 10, order = 1, isPercent = False, unit = ""
uncertainty = value = 1.00000000000000002e-08, significantDigits = 1, order = -8, isPercent = False
>>> print PQU.PQU( '12.345 +/- 1e-8' )
12.34500000 +/- 1.e-8
>>> print PQU.PQU( '12.34500 +/- 0.12' ).info( )
value = 1.23450000000000006e+01, significantDigits = 4, order = 1, isPercent = False, unit = ""
uncertainty = value = 1.19999999999999996e-01, significantDigits = 2, order = -1, isPercent = False
>>> print PQU.PQU( '12.34500 +/- 0.12' )
12.35 +/- 0.12
>>> print PQU.PQU( '12.34500e-12(32)' ).info( )
value = 1.23450000000000004e-11, significantDigits = 7, order = -11, isPercent = False, unit = ""
uncertainty = value = 3.20000000000000023e-16, significantDigits = 2, order = -16, isPercent = False
>>> print PQU.PQU( '12.34500e-12(32)' )
1.234500e-11(32)
>>> print PQU.PQU( '0012.34500e-12 +/- 32e-15' ).info( )
value = 1.23450000000000004e-11, significantDigits = 5, order = -11, isPercent = False, unit = ""
uncertainty = value = 3.20000000000000025e-14, significantDigits = 2, order = -14, isPercent = False
>>> print PQU.PQU( '0012.34500e-12 +/- 32e-15' )
1.2345e-11 +/- 3.2e-14
>>> print PQU.PQU( '00.0012 +/- 0.000002' ).info( )
value = 1.19999999999999989e-03, significantDigits = 4, order = -3, isPercent = False, unit = ""
uncertainty = value = 1.99999999999999991e-06, significantDigits = 1, order = -6, isPercent = False
>>> print PQU.PQU( '00.0012 +/- 0.000002' )
1.200e-3 +/- 2.e-6
The PQU constructor (i.e., its __init__ method) allows various input options for creating an instance (see `PQU`_).
Each PQU has three main members. They are a value stored as a pqu_float
instance, an uncertainty stored
as a pqu_uncertainty
instance and a unit stored as a PhysicalUnit
instance.
Units and conversions¶
This module uses the SI units along with units for angle and solid angle as its base units. The base units are:
Unit symbol Measure meter ‘m’ length kilogram ‘kg’ mass second ‘s’ time Ampere ‘A’ electrical current Kelvin ‘K’ thermodynamic temperature mole ‘mol’ amount of substance candela ‘cd’ luminous intensity radian ‘rad’ angle steradian ‘sr’ solid angle
Any PQU can be represented as a combination of each of these units with an associated power for each unit. As example, a force has the base units ‘kg’ and ‘m’ to power 1 as well as ‘s’ to power -2 (represented as the string ‘kg * m / s**2’). All other units are stored with these units as a base and a conversion factor. For example, the unit for foot (‘ft’) is stored as a meter with the conversion factor of 0.3048. Two units are said to be compatible if they have the same power for each base unit. Hence, ‘ft’ is compatible with ‘m’ but not ‘kg’ or ‘s’. Furthermore, the electron-Volt (‘eV’) is compatible with Joule (‘J’) and Watt-second (‘W * s’) but not Watt (‘W’).
The PQU package has many defined units with prefixes (see Defined prefixes and units). In general, the PQU methods that operate on PQU objects do not attempt to simplify the units, even if the result is dimensionless. For example, consider the division of ‘3.2 m’ by 11.2 km:
>>> from pqu import PQU
>>> x = PQU.PQU( '3.2 m' )
>>> y = PQU.PQU( '11.2 km' )
>>> slope = x / y
>>> print slope
0.29 m/km
>>> dl = slope.copyToUnit( "" )
>>> print dl
2.9e-4
Here the method PQU.copyToUnit()
is used to convert the units into a dimensionless form. Here is another
example showing the use of the PQU.copyToUnit()
method:
>>> mass = PQU.PQU( "4.321 g" )
>>> speed = PQU.PQU( "1.234 inch / mus" )
>>> energy = mass * speed**2
>>> print energy
6.580 inch**2*g/mus**2
>>> energy_joules = energy.copyToUnit( "J" )
>>> print energy_joules
4.245e6 J
The method PQU.inUnitsOf()
is useful for returning a physical quantity in units of descending compatible units.
For example, PQU.inUnitsOf()
will convert ‘3123452.12 s’ into days, hours, minutes and seconds, or just hours and seconds as:
>>> t = PQU.PQU( '3123452.12 s' )
>>> t.inUnitsOf( 'd', 'h', 'min', 's' )
(PQU( "36.0000000 d" ), PQU( "3.000000 h" ), PQU( "37.0000 min" ), PQU( "32.12 s" ))
>>> t.inUnitsOf( 'h', 's' )
(PQU( "867.000000 h" ), PQU( "2252.12 s" ))
Also see the methods PQU.convertToUnit()
and PQU.getValueAs()
.
Changing non-hardwired constants¶
PQU has a set of defined constants that are hardwired and a set that are not hardwired. The non-hardwired constants reside in the module pqu_constants.py and are import by PQU when it is first loaded. It is possible to change a non-hardwired constant by loading the pqu_constants.py module before PQU is imported, redefining the constant and then importing PQU. For example, as of this writing the elementary charge is defined as ‘1.60217653e-19 * C’:
>>> from pqu import PQU
>>> eV = PQU.PQU( 1, 'eV' )
>>> print eV
1. eV
>>> print eV.copyToUnit( 'J' )
1.60217653e-19 J
The following lines change the elementary charge to ‘1.6 * C’:
>>> from pqu import pqu_constants
>>> pqu_constants.e = '1.6 * C'
>>> from pqu import PQU # This import does not work with doctest as PQU was previously imported.
>>> my_eV = PQU.PQU( 1, 'eV' )
>>> print my_eV
1. eV
>>> print my_eV.copyToUnit( 'J' )
1.6 J
The python ‘reload’ function can also be used as:
>>> from pqu import PQU
>>> eV = PQU.PQU( 1, 'eV' )
>>> print eV
1. eV
>>> print eV.copyToUnit( 'J' )
1.60217653e-19 J
>>> from pqu import pqu_constants
>>> pqu_constants.e = '1.6 * C'
>>> reload( PQU )
<module 'pqu.PQU' from 'pqu/PQU.pyc'>
>>> my_eV = PQU.PQU( 1, 'eV' )
>>> print my_eV
1. eV
>>> print my_eV.copyToUnit( 'J' )
1.6 J
>>> pqu_constants.e = '1.60217653e-19 * C' # Needs to be the same as in the module pqu_constants.py for stuff below to pass doctest.
>>> reload( PQU )
<module 'pqu.PQU' from 'pqu/PQU.pyc'>
Uncertainty propagation¶
This section describes the propagation of uncertainties for the binary operators ‘+’, ‘-‘, ‘*’ and ‘/’ as well as the power operator (i.e., ‘**’). Firstly, a comment on the limits of uncertainty propagation. Uncertainties were added mainly to support the inputting and outputting (i.e., converting to and from a string) of a physical quantity with an associated uncertainty. As can be seen from the documentation below, the supported propagations of uncertainties are limited to simple propagation rules.
In the following discussion, Q1, Q2 and Q3 will be PQU instances with values V1, V2 and V3 respectively and uncertainties dQ1, dQ2 and dQ3 respectively. In addition, n1 will be a number (i.e., 1.23).
For the binary operators, all numbers are converted to a PQU instance with uncertainty of 0. For example, the following are all equivalent:
>>> from pqu import PQU
>>> Q1 = PQU.PQU( '12.3 +/- .2 m' )
>>> print Q1 * 0.6
7.4 +/- 0.1 m
>>> print Q1 * PQU.PQU( '0.6' )
7.4 +/- 0.1 m
>>> print PQU.PQU( '0.6' ) * Q1
7.4 +/- 0.1 m
All binary operators assume that the two operands are uncorrelated except when they are the same instance. When the two operands are the same instance, 100% correlation is assumed. For example,
>>> print Q1 - Q1 # Operands are the same instance
0. m
>>> print Q1 - PQU.PQU( '12.3 +/- .2 m' ) # Operands are not the same instance
0.0 +/- 0.3 m
>>> print Q1 + Q1 # Operands are the same instance
24.6 +/- 0.4 m
>>> print Q1 + PQU.PQU( '12.3 +/- .2 m' ) # Operands are not the same instance
24.6 +/- 0.3 m
>>> print Q1 * Q1 # Operands are the same instance
151. +/- 5. m**2
>>> print Q1 * PQU.PQU( '12.3 +/- .2 m' ) # Operands are not the same instance
151. +/- 3. m**2
>>> print Q1 / Q1 # Operands are the same instance
1.
>>> print Q1 / PQU.PQU( '12.3 +/- .2 m' ) # Operands are not the same instance
1.00 +/- 0.02
There is one exception (depending on your divide-by-zero belief) to this rule of same instance and that happens when the value of the operand is 0. Divide-by-zero always executes a raise of ‘ZeroDivisionError’, even for ‘a / a’.
>>> Q2 = PQU.PQU( "0.00 +/- 0.02" )
>>> print Q2 / "2 +/- 0.5"
0.00 +/- 0.01
>>> print Q2 / Q2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "PQU.py", line 1189, in __div__
extraFactor = uncertaintySelf * uncertaintyOther
ZeroDivisionError: float division by zero
For the rest of this discussion, the two binary operands will be assumed to not be the same instance. For addition and subtraction with PQU instances Q1 and Q2 as operands the uncertainty is propagated as dQ3 = sqrt( dQ1**2 + dQ2**2 ). For multiplication with PQU instances Q1 and Q2 as operands the uncertainty is propagated using Goodman’s expression with uncorrelated values (i.e., as dQ3 = sqrt( ( V2 * dQ1 )**2 + ( V1 * dQ2) **2 + ( dQ1 * dQ2 )**2 )). For division, the expression ‘Q1 / Q2’ is converted to ‘Q1 * Q3’ with ‘Q3 = PQU( 1 / V2, unit = 1 / U2, uncertainty = dQ2 / ( V2 * V2 ) )’ where U2 is the unit of Q2.
For the power method, simple propagation is perform which is only valid if the uncertainty is small relative to the value. This is, for ‘Q2 = pow( Q1, n1 )’ the uncertainty for Q2 is ‘dQ2 = n1 * V1**(n1-1) * dQ1’. Note, the ‘sqrt’ method is equivalent to the ‘pow’ method with power of 0.5.
For the trigonometry methods, no propagation of uncertainty is performed.
PQU methods by functionality¶
This section classifies some of the methods in the PQU class by their function.
For PQU methods that require a second operand (e.g., ‘+’, ‘/’), the second operand will be passed to the
staticmethod PQU._getOtherAsPQU()
to determine if it is a suitable object. A suitable object includes any string that
is a valid PQU. For example: PQU.toString()
>>> print PQU.PQU( '12.345' ) + "3.23"
15.58
>>> print PQU.PQU( '12.345 mm' ) + "3.23m"
3242. mm
isCompatible
Returns True if self’s unit is compatible with the units of the argument and False otherwise.
isPercent, isDimensionless, isLength, isMass, isTime, isCurrent, isTemperature, isMoles, isLuminousIntensity, isAngle, isSolidAngle, isEnergy, isSpin, isCharge
These methods return True if self is compatible with the unit implied by the method name.
__float__
This method is called when the a PQU is the argument to the ‘float’ function (e.g., float( pqu )). This method returns a python float for the value of the PQU instance. As example:
>>> pqu = PQU.PQU( '13.7 +/- 0.1 mi/h' )
>>> value = float( pqu )
>>> print type( value ), value
<type 'float'> 13.7
The PQU class has methods for the following arithmetic operations. Unless stated, a new PQU instance is returned.
__abs__, __neg__
These are the standard unitary operators that only operate on the PQU’s value.
__add__, __radd__, __iadd__, __sub__, __rsub__, __isub__
These are the standard binary operators for addition and subtraction. For these operators, the other operand is passed toPQU._getOtherAsPQU()
. The other operand must have units compatible with self. As expected, the __iadd__ and __isub__ methods modify self and return it.
__mul__, __rmul__, __imul__, __div__, __rdiv__, __idiv__
These are the standard binary operators for multiplication and division. For these operators, the other operand is passed to
PQU._getOtherAsPQU()
. As expected, the __imul__ and __idiv__ methods modify self and return it. All these methods call the __mul__ method; except, when a division happens, and ‘self is other’ and the denominator is not 0. That is, the expression ‘a / a’ is handled as a special case when float( a ) != 0. In this case, a dimensionless PQU is returned with value 1 and no uncertainty.If self is not other, the uncertainty is propagated using Goodman’s expression for uncorrelated values. Otherwise, 100% correlated uncertainty is assumed.
__pow__
This method raises - not in the python sense but in the mathematical sense (i.e., x**y) - self to a power. Standard uncertainty propagation is performed which is only valid when the uncertainty is small compared to the value. A quantity can be raised to a non-integer power only if the result can be represented by integer powers of the base units.
__eq__, __ne__, __lt__, __le__, __gt__, __ge__, compare, equivalent
These methods compare self to another object. For these operators, the other object is passed toPQU._getOtherAsPQU()
. The first 6 methods all call thecompare()
method with epsilonFactor = 5. All methods except ‘equivalent’ compare self’s and other’s values only. The ‘equivalent’ method also considers self’s and other’s uncertainty.
__deepcopy__, convertToUnit, copyToUnit, inUnitsOf, getUnitAsString, getValueAs, getUncertaintyValueAs
These methods change a PQU’s unit or return a new instance.
truncate
This method changes a PQU’s value and uncertainty to agree with its printed value as defined by its significant digits.
changeUncertaintyStyle, changeUncertaintyPercent
These methods allow for the changing of a PQU instance uncertainty.
# BRB: need more detail here.
Supporting classes¶
In addition to the PQU
class, the following classes are a part the the PQU module:
parsers
, pqu_float
, pqu_uncertainty
, PhysicalUnit
and NumberDict.
These classes are only intended as helper classes for the PQU class; hence, they have limited functionality and
are only intended for internal use.
History¶
This module is based on the Scientific/Physics/PhysicalQuantities.py module (Last revision: 2007-5-25) written by Konrad Hinsen <hinsen@cnrs-orleans.fr> with contributions from Greg Ward and Berthold Hoellmann.
Most of the additions to Hinsen’s version were done by Nidhi R. Patel and Bret R. Beck <beck6@llnl.gov> with feedback from Caleb M. Mattoon, Neil Summers and David Brown.
The values of physical constants are taken from the 2010 recommended values from CODATA. Other conversion factors (e.g. for British units) come from various sources. I can’t guarantee for the correctness of all entries in the unit table, so use this at your own risk.
Issues or features to be aware of¶
This section describes several oddities about PQU.
- Units ‘oz’, ‘lb’ and ‘ton’ (i.e., ounce, pound and ton respectively) are units of mass and not force. As example, the unit ‘psi’ (i.e., pounds per square inch) is equivalent to about ‘32.174 ft / s**2 * lb / inch**2’.
- In the following, the first line products a significantDigits that is small but correct per PQU rules as the number of significant digits is determined by the ‘1’.
>>> from pqu import PQU
>>> b1 = PQU.PQU( '1 Bohr' )
>>> b2 = b1.inBaseUnits( )
>>> print b2
5.e-11 m
>>> print b2.value.info( )
value = 5.29177208114537818e-11, significantDigits = 1, order = -11, isPercent = False
>>>
>>> b3 = PQU.PQU( 1, 'Bohr' ) # this yields significantDigits = 16.
>>> b4 = b3.inBaseUnits( )
>>> print b4
5.291772081145378e-11 m
>>> print b4.value.info( )
value = 5.29177208114537818e-11, significantDigits = 16, order = -11, isPercent = False
- The temperature units are Kelvin (i.e., ‘K’), Celsius (‘degC’), Rankine (‘degR’) and Fahrenheit (‘degF’). Two of these units (i.e., ‘degC’ and ‘degF’) cannot be used with any other unit including itself. That is, PQU( value, ‘degC’ ) and PQU( value, ‘degF’ ) are the only allowed forms when ‘degF’ or ‘degC’ are present. The two absolute temperature units (i.e., ‘K’ and ‘degR’) have no such restriction. As an example, heat capacity can be expressed in units of ‘W/(m * K)’ or ‘BTU/(hr * ft * degR)’ but cannot be expressed in units of ‘W/(m * degC)’ or ‘BTU/(hr * ft * degF)’. Any temperature unit can be converted to another temperature unit. For example,
>>> from pqu import PQU
>>> t1 = PQU.PQU( '40 degC' )
>>> print t1.convertToUnit( 'degF' )
104. degF
>>> print t1.getValueAs( 'K' )
313.15
>>> print t1.convertToUnit( 'degR' )
564. degR
- PQU, actually PhysicalUnit, allows the unit to have values. For example ‘m/s/25**3’ is currently a valid unit and stored that way. This should probably not be allowed and will probably be deprecated (i.e., do not rely on it). The following illustrates the issue:
>>> from pqu import PQU
>>> c1 = PQU.PQU( '2.23 c' )
>>> print c1
2.23 c
>>> print c1.getValueAs( 'm/s' )
668537181.34
>>> print c1.convertToUnit( 'km / s' )
6.69e5 km/s
>>> print c1.getValue( )
668537.18134
>>>
>>> c2 = PQU.PQU( '2.23 c' ) / 3
>>> print c2
0.743 c
>>> print c2.getValueAs( 'm/s' )
222845727.113
>>> print c2.convertToUnit( 'km / s' )
2.23e5 km/s
>>> print c2.getValue( )
222845.727113
>>>
>>> c3 = PQU.PQU( '2.23 c / 3' )
>>> print c3
2.23 c/3
>>> print c3.getValueAs( 'm/s' )
222845727.113
>>> print c3.convertToUnit( 'km / s' )
2.23e5 km/s
>>> print c3.getValue( )
222845.727113
>>>
>>> print c1 == c2, c1 == c3, c2 == c3
False False True
>>>
>>> print PQU.PQU( '2.23 2. * c / 3**2 / pi' )
2.23 c*2.0/9/3.14159265359
Future plans¶
- Use fractions.Fraction in units.
- Added uncertainty to data in pqu_constants.py and supporting logic.
Defined prefixes and units¶
This section outlines the prefixes and unit defined by the PQU module as well as the values used for the physical constant.
Prefixes¶
---- ------ ------
name factor symbol
---- ------ ------
yotta 1e+24 Y
zetta 1e+21 Z
exa 1e+18 E
peta 1e+15 P
tera 1e+12 T
giga 1e+09 G
mega 1e+06 M
kilo 1e+03 k
hecto 1e+02 h
deka 1e+01 da
deci 1e-01 d
centi 1e-02 c
milli 1e-03 m
micro 1e-06 mu
nano 1e-09 n
pico 1e-12 p
femto 1e-15 f
atto 1e-18 a
zepto 1e-21 z
yocto 1e-24 y
Derived SI units¶
These automatically get prefixes.
-------------------------- -------------------------------- ------
name value symbol
-------------------------- -------------------------------- ------
Hertz 1/s Hz
Newton m*kg/s**2 N
Pascal N/m**2 Pa
Joule N*m J
Watt J/s W
Coulomb s*A C
Volt W/A V
Farad C/V F
Ohm V/A ohm
Siemens A/V S
Weber V*s Wb
Tesla Wb/m**2 T
Henry Wb/A H
Lumen cd*sr lm
Lux lm/m**2 lx
Becquerel 1/s Bq
Gray J/kg Gy
Sievert J/kg Sv
Fundamental constants¶
Fundamental constants ............................................
speed of light 299792458. * m / s c
permeability of vacuum 4.e-7 * pi * N / A**2 mu0
permittivity of vacuum 1 / mu0 / c**2 eps0
gravitational constant 6.67408e-11 * m**3 / kg / s**2 Grav
Planck constant 6.626070040e-34 * J * s hplanck
Planck constant / 2pi hplanck / ( 2 * pi ) hbar
elementary charge 1.6021766208e-19 * C e
electron mass 9.10938356e-31 * kg me
proton mass 1.672621898e-27 * kg mp
Avogadro number 6.022140857e23 / mol Nav
Boltzmann constant 1.38064852e-23 * J / K k
More units¶
Time units .......................................................
minute 60.*s min
hour 60.*min h
day 24.*h d
week 7.*d wk
year 365.25*d yr
Length units .....................................................
inch 2.54 * cm inch
foot 12. * inch ft
yard 3. * ft yd
(British) mile 5280. * ft mi
Nautical mile 1852. * m nmi
Angstrom 1.e-10 * m Ang
light year c * yr lyr
Astronomical unit 149597870700. * m au
Bohr radius 4. * pi * eps0 * hbar**2/me/e**2 Bohr
Area units .......................................................
hectare 10000*m**2 ha
acre mi**2/640 acres
barn 1.e-28*m**2 b
Volume units .....................................................
liter dm**3 l
deci liter 0.1 * l dl
centi liter 0.01 * l cl
milli liter 0.001 * l ml
teaspoon 4.92892159375 * ml tsp
tablespoon 3. * tsp tbsp
fluid ounce 2. * tbsp floz
cup 8. * floz cup
pint 16. * floz pt
quart 2. * pt qt
US gallon 4. * qt galUS
British gallon 4.54609 * l galUK
Mass units .......................................................
atomic mass units 1.660539040e-27 * kg amu
ounce 28.349523125 * g oz
pound 16. * oz lb
ton 2000. * lb ton
Force units ......................................................
dyne (cgs unit) 1.e-5 * N dyn
Energy units .....................................................
erg (cgs unit) 1.e-7*J erg
electron volt e*V eV
Wavenumbers/inverse cm me*e**4/16/pi**2/eps0**2/hbar**2 Hartree
Kelvin as energy unit k*K Ken
thermochemical calorie 4.184 * J cal
thermochemical kilocalorie 1000.*cal kcal
international calorie 4.1868 * J cali
international kilocalorie 1000.*cali kcali
British thermal unit 1055.05585262 * J Btu
Power units ......................................................
horsepower 745.699872 * W hp
Pressure units ...................................................
bar (cgs unit) 1.e5*Pa bar
standard atmosphere 101325. * Pa atm
torr = mm of mercury atm/760 torr
pounds per square inch 6894.75729317 * Pa psi
Angle units ......................................................
degrees pi*rad/180. deg
Temperature units ................................................
degrees Rankine (5./9.)*K degR
degrees Celsius degC degC
degrees Fahrenheit degF degF
Prefixed units¶
------------- ------ --------------
name symbol prefixed units
------------- ------ --------------
Hertz Hz YHz, ZHz, EHz, PHz, THz, GHz, MHz, kHz, hHz, daHz
dHz, cHz, mHz, muHz, nHz, pHz, fHz, aHz, zHz, yHz
Newton N YN, ZN, EN, PN, TN, GN, MN, kN, hN, daN
dN, cN, mN, muN, nN, pN, fN, aN, zN, yN
Pascal Pa YPa, ZPa, EPa, PPa, TPa, GPa, MPa, kPa, hPa, daPa
dPa, cPa, mPa, muPa, nPa, pPa, fPa, aPa, zPa, yPa
Joule J YJ, ZJ, EJ, PJ, TJ, GJ, MJ, kJ, hJ, daJ
dJ, cJ, mJ, muJ, nJ, pJ, fJ, aJ, zJ, yJ
Watt W YW, ZW, EW, PW, TW, GW, MW, kW, hW, daW
dW, cW, mW, muW, nW, pW, fW, aW, zW, yW
Coulomb C YC, ZC, EC, PC, TC, GC, MC, kC, hC, daC
dC, cC, mC, muC, nC, pC, fC, aC, zC, yC
Volt V YV, ZV, EV, PV, TV, GV, MV, kV, hV, daV
dV, cV, mV, muV, nV, pV, fV, aV, zV, yV
Farad F YF, ZF, EF, PF, TF, GF, MF, kF, hF, daF
dF, cF, mF, muF, nF, pF, fF, aF, zF, yF
Ohm ohm Yohm, Zohm, Eohm, Pohm, Tohm, Gohm, Mohm, kohm, hohm, daohm
dohm, cohm, mohm, muohm, nohm, pohm, fohm, aohm, zohm, yohm
Siemens S YS, ZS, ES, PS, TS, GS, MS, kS, hS, daS
dS, cS, mS, muS, nS, pS, fS, aS, zS, yS
Weber Wb YWb, ZWb, EWb, PWb, TWb, GWb, MWb, kWb, hWb, daWb
dWb, cWb, mWb, muWb, nWb, pWb, fWb, aWb, zWb, yWb
Tesla T YT, ZT, ET, PT, TT, GT, MT, kT, hT, daT
dT, cT, mT, muT, nT, pT, fT, aT, zT, yT
Henry H YH, ZH, EH, PH, TH, GH, MH, kH, hH, daH
dH, cH, mH, muH, nH, pH, fH, aH, zH, yH
Lumen lm Ylm, Zlm, Elm, Plm, Tlm, Glm, Mlm, klm, hlm, dalm
dlm, clm, mlm, mulm, nlm, plm, flm, alm, zlm, ylm
Lux lx Ylx, Zlx, Elx, Plx, Tlx, Glx, Mlx, klx, hlx, dalx
dlx, clx, mlx, mulx, nlx, plx, flx, alx, zlx, ylx
Becquerel Bq YBq, ZBq, EBq, PBq, TBq, GBq, MBq, kBq, hBq, daBq
dBq, cBq, mBq, muBq, nBq, pBq, fBq, aBq, zBq, yBq
Gray Gy YGy, ZGy, EGy, PGy, TGy, GGy, MGy, kGy, hGy, daGy
dGy, cGy, mGy, muGy, nGy, pGy, fGy, aGy, zGy, yGy
Sievert Sv YSv, ZSv, ESv, PSv, TSv, GSv, MSv, kSv, hSv, daSv
dSv, cSv, mSv, muSv, nSv, pSv, fSv, aSv, zSv, ySv
barn b Yb, Zb, Eb, Pb, Tb, Gb, Mb, kb, hb, dab
db, cb, mb, mub, nb, pb, fb, ab, zb, yb
electron volt eV YeV, ZeV, EeV, PeV, TeV, GeV, MeV, keV, heV, daeV
deV, ceV, meV, mueV, neV, peV, feV, aeV, zeV, yeV
-
class
pqu.PQU.
PQU
(value, unit=None, uncertainty=None, checkOrder=True)[source]¶ Bases:
object
This class supports a float value with an optional uncertainty and unit. Many basic math operations are supported (e.g., +, -, * /). A PQU is anything that the staticmethod parsers.parsePQUString can parse.
In this section the following notations are used:
Notation Denote pqu The argument is a pqu instance. [], The argument is optional. int A python int (e.g., 23). float A python float (e.g., 1.23e-12). number Any of the following, int, float, pqu_float, a string representing a float (i.e., the python float function must be able to convert the string - e.g., ‘12.3e3’ but not ‘12.3 eV’) or any object having a __float__ method (hence, a numpy float will work). uncertainty = number_unc The uncertainty argument must be a valid number or a pqu_uncertainty object. If number, uncertainty is of style ‘+/-‘. unit = string_pu The unit argument must be a valid unit string (e.g., “MeV”, “MeV/m” but not “1 MeV”) or a PhysicalUnit object. string String can be anything that the method parsers.parsePQUString is capable of parsing (e.g., ‘1.23’, ‘1.23 m’, ‘1.23%’, ‘1.23(12) m’, ‘1.23 +/- 0.12m’). If it contains a unit (uncertainty) then the unit (uncertainty) argument must be None. Calling options are:
- PQU( pqu ) # The new PQU gets all data from pqu. Unit and uncertainty must be None.
- PQU( number, [ unit = string_pu ], [ uncertainty = number_unc ] )
- PQU( string )
- PQU( string, unit = string_pu ) # If string does not contain a unit.
- PQU( string, uncertainty = uncertainty ) # If string does not contain an uncertainty.
- PQU( string, unit = string_pu, uncertainty = number ) # If string does not contain a unit or an uncertainty.
- For example, the following are allowed and are the same:
- PQU( “1.23”, “m”, “12%” )
- PQU( “1.23 m”, uncertainty = “12%” )
- PQU( “1.23 +/- 12%”, “m” )
- PQU( “1.23 +/- 12%”, “m”, None ) # Same as above as None is the default.
- PQU( “1.23+/-12% m” )
- While the following are not allowed:
- PQU( “1.23+/-12% m”, “m” ) # Unit already given in value.
- PQU( “1.23+/-12% m”, uncertainty = “12%” ) # Uncertainty already given in value.
- PQU( “1.23+/-12% m”, “m”, “12%” ) # Unit and uncertainty already given in value.
-
changeUncertaintyPercent
(toPercent)[source]¶ If self’s style is not pqu_uncertaintyStylePlusMinus a raise is executed. Otherwise, if toPercent is True (False) self’s uncertainty will be converted to a percent (non-percent) if not already a percent (non-percent).
Parameters: toPercent (bool) – Specifies whether self’s uncertainty should be percent or not
-
changeUncertaintyStyle
(style)[source]¶ Changes self.uncertainty’s style. If style is the same as self.uncertainty’s style nothing is done. If style or self.uncertainty’s style is pqu_uncertainty.pqu_uncertaintyStyleNone as raise is executed.
Parameters: style – One of the three pqu_uncertainty styles
-
compare
(other, epsilonFactor=0)[source]¶ Compares self’s value to other’s value (other’s value is first converted to unit of self) using the
compare()
function.Also see method
PQU.equivalent()
.Parameters: - other (A PQU equivalent instance) – The PQU instance to compare to self
- epsilonFactor – See the
compare()
function
Returns: See the
compare()
function
-
convertToUnit
(unit)[source]¶ Changes self’s unit to unit and adjusts the value such that the new value/unit is equivalent to the original value/unit. The new unit must be compatible with the original unit of self.
Parameters: unit (str) – a unit equivalent Raises: TypeError – if the unit string is not a known unit or is a unit incompatible with self’s unit
-
copyToUnit
(unit)[source]¶ Like convertToUnit except a copy is made and returned. The copy unit is changed to unit. Self is left unchanged.
Parameters: unit (str) – a unit equivalent Return type: PQU
-
equivalent
(other, factor=1.0)[source]¶ This method compares self to other and returns True if they are equivalent and False otherwise. The two are considered equivalent if their bands overlap. The band for self (or other) is all values within ‘factor times uncertainty’ of its value. That is, the band for self is the ranges from ‘value - factor * uncertainty’ to ‘value + factor * uncertainty’.
Note, this is different than the
compare()
method which compares the values using sys.float_info.epsilon to calculate a ‘band’ and not their uncertainties.Parameters: - other (a PQU equivalent) – The object to compare to self
- factor (float) – the 1/2 width in standard deviations of the band
Returns: 1 if self is deemed greater than other, 0 if equal and -1 otherwise
-
getSignificantDigits
()[source]¶ Returns the number of significant digits for self’s value.
Return type: int
-
getUncertaintyValueAs
(unit=None, asPQU=False)[source]¶ Returns a python float representing self’s uncertainty value. If the uncertainty is a percent, the returned float is self’s value times self’s uncertainty value.
Return type: float
-
getUnitSymbol
()¶ Returns a string representation of self’s unit.
Return type: str
-
getValue
()[source]¶ Returns a python float representing self’s value. This is equivalent to ‘float( self )’.
-
getValueAs
(unit, asPQU=False)[source]¶ Returns self’s value in units of unit. Unit must be compatible with self’s unit.
Parameters: unit – The unit to return self’s value in Return type: float
-
inBaseUnits
()[source]¶ Returns: A copy of self converted to base units, i.e. SI units in most cases Return type: PQU
-
inUnitsOf
(*units)[source]¶ Express the quantity in different units. If one unit is specified, a new PQU object is returned that expresses the quantity in that unit. If several units are specified, the return value is a tuple of PhysicalObject instances with one element per unit such that the sum of all quantities in the tuple equals the the original quantity and all the values except for the last one are integers. This is used to convert to irregular unit systems like hour/minute/second.
Parameters: units (str or sequence of str) – one or several units Returns: one or more physical quantities Return type: PQU or tuple of PQU Raises: TypeError – if any of the specified units are not compatible with the original unit
-
info
(significantDigits=17)[source]¶ Returns a detailed string of self. Mainly for debugging.
Return type: str
-
isCompatible
(unit)[source]¶ Returns True if self’s unit is compatible with unit.
Parameters: unit (str) – a unit Return type: bool
-
isDimensionless
()[source]¶ Returns True if self is dimensionless and False otherwise.
Return type: bool
-
isLuminousIntensity
()[source]¶ Returns True if self has unit of luminous intensity and False otherwise.
Return type: bool
-
static
isPhysicalUnitOf
(elf, unit)[source]¶ Returns True if elf has the same unit as the argument unit and False otherwise. Elf and unit can be an instance of string, PhysicalUnit or PQU.
Parameters: - elf (a unit equivalent) – The instance to compare to unit
- unit (a unit equivalent) – The desired unit
Return type: bool
-
isSolidAngle
()[source]¶ Returns True if self has unit of solid angle and False otherwise.
Return type: bool
-
isSpin
()[source]¶ Returns True if self has unit of spin (i.e., same as ‘hbar’) and False otherwise.
Return type: bool
-
isTemperature
()[source]¶ Returns True if self has unit of temperature and False otherwise.
Return type: bool
-
setPercentFlag
(isPercent, scaleValue=False)[source]¶ Changes the percent flag only when self is dimensionless and isPercent != self.isPercent( ). Otherwise, a raise is executed. For scaleValue argument see
pqu_float.setPercentFlag()
.Parameters: - isPercent – See
pqu_float.setPercentFlag()
- scaleValue – See
pqu_float.setPercentFlag()
- isPercent – See
-
simplify
()[source]¶ This method returns a PQU instance that is the same as self but with its units simplified. This is, units that have the same base units are reduce to one of those units. For example, if self is equivalent to ‘1.2 km/m**3’ then the returned instance will be equivalent to ‘1.2e3 / m**2’ or ‘1.2e9 / km**2’ (the actual units returned are not guaranteed). As another example, if self is equivalent to ‘1.2 ft**3 / lb / s / ( m**2 / kg )’ then one returned outcome is ‘0.2457793723470261 ft/s’. That is, the ‘ft’ and ‘m’ units have the same base units and are all converted to ‘ft’ (in this case) and the ‘lb’ and ‘kg’ are all converted to ‘lb’ (or ‘kg’).
-
toString
(significantDigits=None, keepPeriod=True)[source]¶ Returns a string representation of self (e.g., ‘35 +/- 1.2% J’).
Return type: str
-
truncate
(value=False, uncertainty=True)[source]¶ If value is True, calls self.value’s truncate method. If uncertainty is True, calls self.uncertainty’s truncate method. See
pqu_float.truncate()
Parameters: - value (bool) – If True self’s value is truncated
- uncertainty (bool) – If True self’s uncertainty is truncated
-
class
pqu.PQU.
PhysicalUnit
(symbols, factor, powers, offset=0)[source]¶ Bases:
object
PHYSICAL UNIT
A physical unit is defined by a symbol (possibly composite), a scaling factor, and the powers of each of the SI base units that enter into it. Units can be multiplied, divided, and raised to integer powers.
Parameters: - symbols (dict or str) – a dictionary mapping each symbol component to its associated integer
power (e.g.,
{'m': 1, 's': -1}
) for m/s). As a shorthand, a string may be passed which is assigned an implicit power 1. - factor (float) – a scaling factor
- offset (float) – an additive offset to the base unit (used only for temperatures)
- powers (list of int) – the integer powers for each of the nine base units
-
conversionFactorTo
(other)[source]¶ Parameters: other (PhysicalUnit) – another unit Returns: the conversion factor from this unit to another unit Return type: float Raises: TypeError – if the units are not compatible
-
conversionTupleTo
(other)[source]¶ Parameters: other (PhysicalUnit) – another unit Returns: the conversion factor and offset from this unit to another unit Return type: (float, float) Raises: TypeError – if the units are not compatible
-
isCompatible
(other)[source]¶ Returns True if self is compatible with other and False otherwise.
Parameters: other (PhysicalUnit) – another unit Returns: True if the units are compatible, i.e. if the powers of the base units are the same Return type: bool
-
isDimensionless
()[source]¶ Returns True if self is dimensionless and False otherwise.
Return type: bool
- symbols (dict or str) – a dictionary mapping each symbol component to its associated integer
power (e.g.,
-
pqu.PQU.
compare
(value1, value2, epsilonFactor=0)[source]¶ This function compares two floats (or objects that can be converted to floats) in a fuzzy way where the fuzz factor is epsilonFactor * sys.float_info.epsilon. This function returns
0 if the floats are comparable as given by epsilonFactor (see below), otherwise, it returns 1 (-1) if value1 is greater (less) than value2.Two floats are comparable if the magnitude of the ‘relative difference’ between them is less than or equal to epsilonFactor * sys.float_info.epsilon. The relative difference is defined as
( value1 - value2 ) / max( abs( value1 ), abs( value2 ) )Hence, two floats are comparable if
( value1 - value2 ) <= epsilonFactor * sys.float_info.epsilon * max( abs( value1 ), abs( value2 ) )For the default epsilonFactor = 0, a 0 is return (i.e., the two floats are ‘equal’) only if they have the same value
Parameters: - value1 (any object which float() accepts) – value to compare to value2
- value2 (any object which float() accepts) – value to compare to value1
- epsilonFactor (any object which float() accepts) – The factor to scale sys.float_info.epsilon to determine the fuzz factor.
Returns: 1 if value1 is deemed greater than value2, 0 if equal and -1 otherwise
Return type: int
-
pqu.PQU.
floatToShortestString
(value, significantDigits=15, trimZeros=True, keepPeriod=False, favorEFormBy=0, includeSign=False)[source]¶ This function returns the shortest string representation of the float ‘value’ that is accurate to ‘significantDigits’ digits when converted back to a float.
The float is converted to both the E-form (i.e., ‘%e’) and F-form (i.e., ‘%f’) with significantDigits. Then, after ‘trimZeros’ and ‘keepPeriod’ options are implemented, if the length of the E-form minus favorEFormBy is less than or equal to the length of the F-form, the E-form is returned. Otherwise the F-form is returned.
For example, for significantDigits = 12 the returned string for the float 1.234 will be “1.234”, and not “1.234000000000” or “1.23400000000e+00” while the string for the float 1.234e-9 will be “1.234-9”, and not “0.00000000123400000000” or “1.23400000000e-09”.
Parameters: - value (float) – The float to convert.
- significantDigits (integer) – The number of significant digits desired. Restricted to the range 0 to 24 inclusive.
- trimZeros (bool) – If True, unneeded zeros to the right of ‘.’ are removed.
- keepPeriod (bool) – If False, ‘.’ is removed if there is no digit to its right.
- favorEFormBy (integer) – The integer subtracted from the length of the E-form before the form with the shortest representation is determined.
- includeSign (bool) – If True, the returned string will always start with a sign character (i.e., ‘+’ or ‘-‘). Otherwise, only negative values will have a sign.
Return type: str
-
class
pqu.PQU.
parsers
[source]¶ Bases:
object
Regular Expression Matching
-
static
parseFloat
(str1, fullStr)[source]¶ This method parses the beginning of str1 for a valid float. An arbitrary number of white spaces can exists before the float characters. This method returns a tuple of length 3. The first item of the tuple is the float value returned as a pqu_float instance with significantDigits determined from the string. The second item is significantDigitsForZero which, if the string represents a 0 value, gives the number of significant digits for the zero; otherwise None is returned. As example, the string ‘000.000’ has 4 significant digits (i.e., it is considered equivalent to the representation ‘0.000’). The last object is the string of all characters after the last one used for converting the float. For example, with str1 = ‘ 12.345e3ABCD XYS’ the returned tuple is:
( pqu_float( 1.2345e4, 5 ), None, ‘ABCD XYS’ ).
Parameters: - str1 – String to parse.
- fullStr – String which str1 is a part of.
Return type: ( pqu_float, integer | None, string )
-
static
parsePQUString
(str1)[source]¶ Parses the string str1 and returns the tuple ( value, unit, uncertainty ) where value is an instance of pqu_float, unit is an instance of PhysicalUnit and uncertainty is an instance of pqu_uncertainty.
The string can be one of the following PQU forms. Here, F represents a valid float string, () represents the string ‘(#)’ where ‘#’ is a 1 or 2 digit number, +/- represents the string ‘+/- F’, % is itself and u is a unit.
# Form Example Value Value - uncertainty Value + uncertainty Unit 0 F ‘234’ N/A N/A N/A 1 F% ‘234%’ 2.34 N/A N/A N/A 2 F u ‘234 m’ N/A N/A ‘m’ 3 F() ‘234(5)’ N/A 4 F()% ‘234(5)%’ 2.34 2.29 2.39 N/A 5 F() u ‘234(5) m’ ‘m’ 6 F +/- ‘234 +/- 5’ N/A 7 F +/-% ‘234 +/- 5%’ N/A 8 F +/- u ‘234 +/- 5 m’ ‘m’ 9 F +/-% u ‘234 +/- 5% m’ ‘m’ 10 (F +/-)% ‘(234 +/- 5)%’ 2.34 2.29 2.39 N/A Note 1) 5% of 234 is 11.7 rounded to 12.
Parameters: str1 – String to parse. Return type: ( pqu_float, PhysicalUnit, pqu_uncertainty )
-
static
parseParenthesisUncertainty
(str1, fullStr)[source]¶ This method parses the beginning of str1 for the sub-string ‘(#)’ where ‘#’ is a 1 or 2 digit number. This method returns a tuple of length 2. The first item of the tuple is the number returned as a pqu_uncertainty of style pqu_uncertaintyStyleParenthesis. Characters after the ‘)’ are returned as the second item. For example, with str1 = ‘(34) ABCD XYS’ the returned tuple is:
( pqu_uncertainty( pqu_uncertainty.pqu_uncertaintyStyleParenthesis, 34, significantDigits = 2 ), ‘ ABCD XYS’ ).
Parameters: - str1 – String to parse.
- fullStr – String which str1 is a part of.
Return type: ( pqu_uncertainty, string )
-
static
parsePlusMinusUncertainty
(str1, fullStr)[source]¶ This method parses the beginning of str1 for the sub-string ‘+/-‘ followed by a float string. An arbitrary number of white spaces can exists before the ‘+/-‘ sub-string and between it and the float string. This method returns a tuple of length 2. The first item of the tuple is float value returned as a pqu_uncertainty of style pqu_uncertaintyStylePlusMinus. Characters after the last one used for converting the float are returned as the second item. For example, with str1 = ‘ +/- 12. ABCD XYS’ the returned tuple is:
( pqu_uncertainty( pqu_uncertainty.pqu_uncertaintyStylePlusMinus, 12. ), ‘ ABCD XYS’ )
Parameters: - str1 – String to parse.
- fullStr – String which str1 is a part of.
Return type: ( pqu_uncertainty, string )
-
static
-
class
pqu.PQU.
pqu_float
(value, significantDigits, isPercent=False, checkOrder=True)[source]¶ Bases:
object
This class is used by PQU and pqu_uncertainty to store more information about a float than is provided by the python float class as well as methods to operator on this information. The main members are:
- value — The python value of the float.
- significantDigits — The number of significant digits the value possess as defined by the creator of self.
- order — An integer that represents the order of the most significant digit of self.
- Calculated internally equivalent to int( log10( value ) ) and stored for convenience.
- _isPercent — True if self represents a percent and False otherwise. Note, the value is always stored as
- the non-percent value (e.g., 1% and 12% are stored as 0.01 and 0.12 respectively).
-
static
calculateOrder
(value)[source]¶ Returns the order of value. Value must be convertible to a float. A float’s order is the exponent in the representation ‘m * 10**o’ where ‘m’ is the mantissa and ‘o’ is the exponent. For example, 1.234e43 has order 43.
Parameters: value – any object convertible to a float. Return type: integer
-
static
fixFloatsOrder
(value)[source]¶ Many numbers are not represented in IEEE floating point by there true value. For example, ‘1e-12’ is stored as the float 9.9999999999999998e-13. The order of the true value is -12 while the order of the floating point representation is -13. This function is implemented to help with this issue. For example, for PQU the string “2.300000000003 (1)” was originally being reprinted as “2.300000000003 (10)” because of this issue. To check for this, the value is multiplied by a small (of order sys.float_info.epsilon) factor to see if order changes. If it does, value is set to the smallest multiplier greater than 1 for which order is changed. The fixed value and its order are returned.
Parameters: value – any object convertible to a float. Return type: tuple of float and integer
-
info
(significantDigits=17)[source]¶ Returns a detailed string of self. Mainly for debugging.
Return type: str
-
setPercentFlag
(isPercent, scaleValue=False)[source]¶ If argument isPercent is True and self is not a percent, self is converted to a percent. If argument isPercent is False and self is a percent, self is converted to non-percent. Otherwise, a raise is executed.
If scaleValue is False, the value is not changed; otherwise, value is scale by 0.01 (100) if isPercent is True (False).
Parameters: isPercent (bool) – param scaleValue: :type scaleValue: bool
-
setSignificantDigits
(significantDigits)[source]¶ Sets self’s significant digits to significantDigits.
Parameters: significantDigits (int) –
-
static
surmiseSignificantDigits
(value)[source]¶ This factory function returns a pqu_float instance given a float value and set its significantDigits to something “reasonable”. The significantDigits are determined by using PQU.floatToShortestString with trimZeros = True.
-
toString
(trimZeros=True, keepPeriod=True, includePercent=True, favorEFormBy=0, significantDigits=None)[source]¶ Returns a string representation of self (i.e., ‘1.234e6’ or ‘12%’) using function
floatToShortestString()
.Parameters: - trimZeros (bool) – See function
floatToShortestString()
- keepPeriod (bool) – See function
floatToShortestString()
- favorEFormBy (int) – See function
floatToShortestString()
- significantDigits – (int or None) Used to override self’s default significantDigits
Return type: str
- trimZeros (bool) – See function
-
truncate
(significantDigits=None)[source]¶ Adjusts self’s value so that only significantDigits are non-zero. For example, if value is 3.453983207834109 and significantDigits = 4 then the value is set to 3.454. If significantDigits is None, self’s significantDigits is used.
Parameters: significantDigits (None or int) –
-
class
pqu.PQU.
pqu_uncertainty
(uncertaintyStyle, value=None, significantDigits=2, isPercent=False, checkOrder=True)[source]¶ Bases:
object
This class is used by PQU to store the style of uncertainty and information about its value. The members are:
- style — One of the three following uncertainty styles supported by PQU:
- pqu_uncertaintyStyleNone - No uncertainty was given for the PQU instance.
- pqu_uncertaintyStylePlusMinus - The uncertainty was given as ‘+/- value’ (e.g., ‘123 +/- 32’).
- pqu_uncertaintyStyleParenthesis - The uncertainty was given as ‘(value)’ (e.g., ‘123(32)’.
- value — The value stored as a pqu_float.
-
getProperValue
(v)[source]¶ Returns self’s value. If value is a percent, returned result is multiplied by argument v first, where v is expected to be the number associated the the percent value.
Return type: float
-
info
(significantDigits=17)[source]¶ Returns a detailed string of self. Mainly for debugging.
Return type: str
-
isUncertainty
()[source]¶ Returns False is style is pqu_uncertaintyStyleNone and True otherwise.
Return type: bool
-
pqu_uncertaintyStyleNone
= None¶
-
pqu_uncertaintyStyleParenthesis
= 'parenthesis'¶
-
pqu_uncertaintyStylePlusMinus
= 'plusMinus'¶
-
toString
(prefix=' ', significantDigits=None)[source]¶ Returns a string representation of self (i.e., ‘+/- 1.2%’).
Parameters: - prefix (str) – A prefix for the ‘+/-‘ style
- significantDigits – Passed onto method
pqu_float.toString()
Return type: str
-
truncate
()[source]¶ Adjusts self’s value so that only the significant digits are non-zero. This is most useful when a PQU instance is calculated from other PQU instance which can create an uncertainty with many non-zero digits. As example, adding two PQUs with uncertainties 1.3 and 3.2 each with two significant digits, produces the uncertainty sqrt( 1.3**2 + 3.2**2 ) = 3.453983207834109. This uncertainty also only has two significant digits. After calling truncate the uncertainty become 3.5 which is the value that the method toString would return.
-
pqu.PQU.
toShortestString
(value, significantDigits=15, trimZeros=True, keepPeriod=False, favorEFormBy=0, includeSign=False)¶ This function returns the shortest string representation of the float ‘value’ that is accurate to ‘significantDigits’ digits when converted back to a float.
The float is converted to both the E-form (i.e., ‘%e’) and F-form (i.e., ‘%f’) with significantDigits. Then, after ‘trimZeros’ and ‘keepPeriod’ options are implemented, if the length of the E-form minus favorEFormBy is less than or equal to the length of the F-form, the E-form is returned. Otherwise the F-form is returned.
For example, for significantDigits = 12 the returned string for the float 1.234 will be “1.234”, and not “1.234000000000” or “1.23400000000e+00” while the string for the float 1.234e-9 will be “1.234-9”, and not “0.00000000123400000000” or “1.23400000000e-09”.
Parameters: - value (float) – The float to convert.
- significantDigits (integer) – The number of significant digits desired. Restricted to the range 0 to 24 inclusive.
- trimZeros (bool) – If True, unneeded zeros to the right of ‘.’ are removed.
- keepPeriod (bool) – If False, ‘.’ is removed if there is no digit to its right.
- favorEFormBy (integer) – The integer subtracted from the length of the E-form before the form with the shortest representation is determined.
- includeSign (bool) – If True, the returned string will always start with a sign character (i.e., ‘+’ or ‘-‘). Otherwise, only negative values will have a sign.
Return type: str
-
pqu.PQU.
valueOrPQ
(value, unitFrom=None, unitTo=None, asPQU=False, checkOrder=True)[source]¶ This function is designed as a convenience function for working with PQU and float instances. That is, instead of checking the type of value, let valueOrPQ handle some of the details. The first argument can be either a PQU or something that is a valid argument for the python ‘float’ function (e.g., 1.23, “1.23”). The returned instance is a PQU if asPQU is True and a float otherwise. The unitFrom and unitTo arguments can be either None, a PhysicalUnit or a string that represents a PhysicalUnit (e.g., “m”, “”, “MeV * b”). If unitTo is not None, the returned instance will be in units of unitTo. If unitFrom is not None and the first argument (i.e., value) is a PQU instance, they must have the same units.
Note, this function was originally written when PQU did not support dimensionless units. As it now supports dimensionless units, this function may not be of much value but should be kept anyway.
- Options for input are:
from _getUnit returned value asPQU value unitFrom unitTo unitFrom unitTo False True float None None None None float float float None string or PU None PU float in unitTo PQ in unitTo float string or PU None PU None float in unitFrom PQ in unitFrom float string or PU string or PU PU PU float in unitTo PQ in unitTo PQU None None PU None float PQ PQU string or PU None PU None float in unitFrom PQU (need to check that PQ and unitFrom are the same) PQU string or PU string or PU PU PU float in unitTo PQU in unitTo (ditto) PQU None string or PU PU PU float in unitTo PQU in unitTo
Parameters: - value (PQU instance or any object which float() accepts) – The number object convert if requested
- unitFrom (None or instance from which units can be determined) – If not None, the unit for value
- unitTo (None or instance from which units can be determined) – If not None, the unit the returned value is in
- asPQU (bool) – If True returned instance is a PQU; otherwise, it is a float
Returns: value - in units of unitTo if unitTo is not None
Return type: float or PQU instance