Non-SI units, such as mile, foot etc. can be found in the module additional_units, along with some physical constants. For the names of all pre-defined units see Quantity.all_unit_names at runtime.
NOTES:
This module, along with additional_units and quantity_parser can be used outside Sage, but some functionality will not be available then. In particular, trigonometric and exponential functions won’t work and it will not be possible to set a BaseUnitSet.
Warning
Be aware that temperature conversions only work for temperature intervals.
AUTHORS:
- Dan Goodman (2008): initial version, as module units in the piquant package; see http://sourceforge.net/projects/piquant/
- David Bate (2008): modifications, added Flydims
- Miriam Backens (2009): removed Unit class, added BaseUnitSet, LaTeX formatting, support for mathematical functions, various things to do with Sage, extended documentation
EXAMPLES:
To use the Quantity class, define new quantities in terms of existing ones:
sage: from sage.dimpy import *
sage: v = 5 * meter / second
sage: t = 7 * second
sage: v * t
35 m
sage: V = 3 * volt
sage: I = 2 * amp
sage: V/I
1.5 ohm
Use the in_unit() method or the operator % to display quantities in other units:
sage: R = 2 * ohm
sage: (I*R).in_unit('mV')
4000.0 mV
sage: 50 * kilometer % mile
31.0685596119 mi
Quantities can only be added or subtracted if they have the same dimensions; attempts to do dimensionally invalid operations will cause DimensionMismatchError:
sage: 3 * minute + 2 * second
3.03333333333 min
sage: 3 * minute + 2 * kilogram
...
DimensionMismatchError: Addition, dimensions were (s, ) (kg, )
It is possible to use quantities in mathematical functions such as exp, log and trigonometric functions, but only if the Quantity in question is dimensionless:
sage: exp(-2 * eV / (k * 0.4 * kelvin))
1.36855127326495e-25199
sage: sin(0.5 * pi * radian)
1.00000000000000
sage: arctan(4 * joule)
...
DimensionMismatchError: Argument of 'arctan' must be dimensionless, dimensions were (m^2 kg s^-2, )
All classes defined in this module have _latex_() methods which return a string representation of the object for use in LaTeX. Various class attributes of Quantity can be used to modify the way in which Quantities are typeset (see documentation for Quantity).
sage: (42*meter/second)._latex_()
'42 \, \mathrm{m} \, \mathrm{s}^{-1}'
Stores the indices of the 7 basic SI unit dimensions (length, mass, etc.).
Initialise Dimension object with a vector or keywords, i.e. call as Dimension(list), Dimension(keywords) or Dimension(dim).
NOTES:
A general user of DimPy will not need to use this class or its methods.
The 7 SI dimensions are (in order):
Length, Mass, Time, Electric Current, Temperature, Quantity of Substance, Luminosity
and can be referred to either by these names or their SI unit names, e.g. length, metre and m all refer to the same thing here.
A dimensionless dimension (i.e. all exponents are 0) prints as .
The arithmetic methods do not check the input types, so unexpected things may happen with the wrong input.
EXAMPLES:
The following are all definitions of the dimensions of force:
sage: a = Dimension(length=1, mass=1, time=-2)
sage: b = Dimension(m=1, kg=1, s=-2)
sage: c = Dimension([1,1,-2,0,0,0,0])
sage: a == b and b == c
True
Return the power of d in self.
OUTPUT: an integer, the exponent of d
EXAMPLES:
sage: dim = joule.get_dimensions()
sage: dim.get_dimension('meter')
2
sage: dim.get_dimension('Length') == dim.get_dimension('m')
True
sage: dim.get_dimension('second')
-2
sage: dim.get_dimension('Temperature')
0
Return True if self is dimensionless, i.e. if the powers of all the SI base units are equal to 0.
OUTPUT: a bool
EXAMPLE:
sage: Dimension().is_dimensionless()
True
sage: Dimension(m=1).is_dimensionless()
False
Set the power of d in self to value.
EXAMPLE:
sage: a = Dimension(meter=1)
sage: a
m
sage: a.set_dimension('s', -1)
sage: a
m s^-1
A unit with virtual dimensions that are created on-the-fly.
Use this to do calculations with dimensions outside the scope of normal physics, e.g. ‘person’, ‘euro’...
NOTES:
The dictionary self.dims of dimension_name:exponent pairs may be modified directly (see examples).
A dimensionless Flydim will print as the empty string.
If dimension names contain special characters, i.e. ones other than letters, numbers and .+-/(), there may be problems with LaTeX printing.
EXAMPLES:
Define the initial Flydim by a string, for example a has dimension “person = 1”:
sage: a = Flydim('person')
sage: b = Flydim('euro')
Multiplication and division combine the dimensions:
sage: a*b
person euro
Can define an empty Flydim for later use:
sage: c = Flydim()
Can then modify the contents directly:
sage: c.dims['garage'] = 2
sage: print c
garage^2
Can copy Flydims:
sage: c = a.copy()
sage: print c
person
Arithmetic: products of Flydims return Flydims, products with scalars or Quantities return Quantities:
sage: a.invert()
person^-1
sage: b/a
person^-1 euro
sage: a/meter**2
1.0 m^-2 person
sage: a/2
0.5 person
sage: 2/a
2 person^-1
Return a copy of self.
EXAMPLE:
sage: a = Flydim('orange')
sage: b = a.copy()
sage: a == b
True
sage: a is b
False
Return 1 if this Flydim is dimensionless, otherwise return the Flydim.
This is unlike the string representation which returns the empty string if the Flydim is dimensionless.
EXAMPLES:
sage: Flydim('coconut').get_dimensions()
coconut
sage: Flydim().get_dimensions()
1
Return the inverse of this Flydim.
Makes a copy of self and multiplies all exponents by .
EXAMPLES:
sage: a = Flydim('apple') * Flydim('banana')**2
sage: a.invert()
apple^-1 banana^-2
Return True if this Flydim is dimensionless.
EXAMPLES:
sage: Flydim('coconut').is_dimensionless()
False
sage: Flydim().is_dimensionless()
True
Exception class for attempted operations with inconsistent dimensions.
NOTES:
Raise as DimensionMismatchError(desc, dim1, dim2,...).
For example, 3*volt + 2*amp raises this exception. The purpose of this class is to help catch errors based on incorrect units. The exception will print a representation of the dimensions of the two inconsistent objects that were operated on. If you want to check for inconsistent units in your code, do something like:
try:
...
your code here
...
except DimensionMismatchError, inst:
...
cleanup code here, e.g.
print "Found dimension mismatch, details:", inst
...
EXAMPLE:
sage: 1 * meter + 0 * candela
...
DimensionMismatchError: Addition, dimensions were (m, ) (cd, )
A number with an associated physical dimension and flydim.
NOTES:
For a list of all pre-defined Quantities see Quantity.all_unit_names.
It is not necessary to deal with this class directly. Instead define new quantities using arithmetic and existing quantities. A DimensionMismatchError exception is raised if dimensions are inconsistent.
The most important methods are in_unit() and set_preferred() which allow the user to change the way the quantity prints. The method set_preferred() permanently specifies the units in terms of which the Quantity is printed, whereas in_unit() only changes the units temporarily.
Quantity(value) creates a new dimensionless Quantity with the given numerical value (default 1). For more customizable Quantity creation use Quantity.with_dimensions(). In each case the argument registered=True automatically registers the unit (see also register_new_units() and UnitRegistry)
CLASS ATTRIBUTES:
These can be set directly, for base_unit_set there is also a helper function. Some type checking is done before the values are used.
- base_unit_set - a BaseUnitSet that can be used to express any physical quantity, or [] to use the SI units as the base set (see documentation for set_base_units() and BaseUnitSet)
- engineering - whether to use the engineering convention rather than scientific notation in LaTeX output (default: False; the engineering convention uses only powers of 10 with an exponent divisible by 3)
- imaginary_unit - a string determining what the square root of
prints as in LaTeX output (default: ‘i’)
- precision - an integer, how many decimal places to print in LaTeX output (default: 2)
- interval - a tuple of two positive numbers, any number outside that range is printed using scientific notation when in LaTeX mode (default: (0.01, 1000) )
NOTES on LaTeX typesetting:
The program automatically makes sure that exponents, indices and all pre-defined variable names print correctly in LaTeX mode.
The names e_ and h_ are stripped of their trailing underscores and h_bar is replaced by the proper LaTeX code. ohm is replaced by \Omega and epsilon, mu and sigma are turned into proper Greek letters.
EXAMPLES:
sage: from sage.dimpy import *
sage: g = 9.81 * meter / second**2
sage: t = 2*second
sage: g * t**2 / 2
19.6200000000000 m
sage: Quantity(0.0005)._latex_()
'5.00 \times 10^{-4}'
sage: Quantity.engineering = True
sage: Quantity(0.0005)._latex_()
'500.0 \times 10^{-6}'
sage: Quantity.engineering = False # go back to default to not break any later doctests
Return the arccos of this Quantity if it is dimensionless.
EXAMPLES:
sage: from additional_units import eV
sage: arccos(10**11 * eV / joule)
1.5707963107731313
sage: arccos(0.7 * celsius)
...
DimensionMismatchError: Argument of 'arccos' must be dimensionless, dimensions were (K, )
Return the arccot of this Quantity if it is dimensionless.
EXAMPLES:
sage: arccot(metre**3/(4.54609*10**-3*metre**3))
arccot(219.969248299088)
sage: arccot(metre**3)
...
DimensionMismatchError: Argument of 'arccot' must be dimensionless, dimensions were (m^3, )
Return the arccsc of this Quantity if it is dimensionless.
EXAMPLES:
sage: arccsc(kilogram/(0.45359237*kilogram))
arccsc(2.20462262184878)
sage: arccsc(kilogram)
...
DimensionMismatchError: Argument of 'arccsc' must be dimensionless, dimensions were (kg, )
Return the arcsec of this Quantity if it is dimensionless.
EXAMPLES:
sage: from additional_units import hour, minute
sage: arcsec(hour/minute)
1.5541288884268252
sage: arcsec(hour)
...
DimensionMismatchError: Argument of 'arcsec' must be dimensionless, dimensions were (s, )
Return the arcsin of this Quantity if it is dimensionless.
EXAMPLES:
sage: from additional_units import AU
sage: arcsin(10**9 * meter/AU)
0.0066846369056914661
sage: arcsin(AU)
...
DimensionMismatchError: Argument of 'arcsin' must be dimensionless, dimensions were (m, )
Return the arctan of this Quantity if it is dimensionless.
EXAMPLES:
sage: from additional_units import usGal, impGal
sage: arctan(usGal/impGal)
0.69434914427813477
sage: arctan(usGal)
...
DimensionMismatchError: Argument of 'arctan' must be dimensionless, dimensions were (m^3, )
Return the cosine of this Quantity if it is dimensionless.
EXAMPLES:
sage: cos(2 * pi * radian)
1.0
sage: cos(3 * meter)
...
DimensionMismatchError: Argument of 'cos' must be dimensionless, dimensions were (m, )
Return the cot of this Quantity if it is dimensionless.
EXAMPLES:
sage: cot(1*radian)
cot(1)
sage: cot(4*newton/kilogram)
...
DimensionMismatchError: Argument of 'cot' must be dimensionless, dimensions were (m s^-2, )
Return the csc of this Quantity if it is dimensionless.
EXAMPLES:
sage: csc(0.5*radian)
2.08582964293349
sage: csc(pi*meter)
...
DimensionMismatchError: Argument of 'csc' must be dimensionless, dimensions were (m, )
Return the exponential of this Quantity if it is dimensionless.
EXAMPLES:
sage: from additional_units import amu, k
sage: exp(-amu*100*meter**2/second**2 / (k*2*kelvin))
0.99400443494374546
sage: exp(-amu*100*meter/second / (k*2*kelvin))
...
DimensionMismatchError: Argument of 'exp' must be dimensionless, dimensions were (m^-1 s, )
Return the physical dimensions of this object.
EXAMPLE:
sage: ohm.get_dimensions()
m^2 kg s^-3 A^-2
Return the display name of this object.
EXAMPLES:
sage: meter.get_dispname()
'm'
sage: ohm.get_dispname()
'ohm'
Return the flydims of this object.
EXAMPLE:
sage: ampere.get_flydims()
<BLANKLINE>
sage: (ampere / Flydim('person')).get_flydims()
person^-1
Return the preferred unit of this object.
EXAMPLE:
sage: meter.get_preferred()
'self'
sage: (3 * kilogram).get_preferred()
''
Test if this object has the same dimensions and Flydims as another.
EXAMPLES:
sage: metre.has_same_dimensions(Dimension(m=1))
True
sage: metre.has_same_dimensions(kelvin)
False
Return a copy of the object in the ‘best unit’, do not change the original.
INPUT:
- *regs - the registries to check, defaults to user unit register, standard unit register, additional unit register in this order
OUTPUT: a Quantity with preferred_unit set to the best unit found
NOTES:
For more information, see the documentation for the UnitRegistry class. Essentially, this looks at the value of the quantity for all ‘known’ matching units and returns the one with the most compactrepresentation. Standard units are built in, but new units can be registered or old ones unregistered.
If no matching unit is found, the object will be printed in terms of the base units specified in Quantity.base_units or the 7 SI base units.
If no preferred unit is specified, the in_unit() function or the print functions automatically look for the best unit. What is different about using in_best_unit() directly is that registries and their order can be specified so that only those will be checked.
EXAMPLE:
Normally joule prints as J because it is a pre-defined unit. Looking for the best unit in all registers finds J, but now the numerical value is printed too. The only suitable unit in the additional unit register is eV.
sage: joule
J
sage: joule.in_best_unit()
1.0 J
sage: joule.in_best_unit(additional_unit_register)
6.24150947961e+18 eV
Representation of the object in unit unit.
OUTPUT: a Quantity with the preferred unit set to unit
NOTES:
Returns a copy of the object with preferred_unit set to unit; does not change the original. The operator % has the same effect.
EXAMPLE:
sage: d = 15 * meter
sage: d
15 m
sage: d.in_unit('cm')
1500.0 cm
sage: d
15 m
sage: d % 'cm'
1500.0 cm
Test whether this is a dimensionless object.
EXAMPLES:
sage: Quantity().is_dimensionless()
True
sage: metre.is_dimensionless()
False
Return the natural logarithm of this Quantity if it is dimensionless.
EXAMPLES:
sage: log(30*0.514444444444*meter/second / (10*meter/second))
0.433944579429169
sage: log(30*meter/second)
...
DimensionMismatchError: Argument of 'log' must be dimensionless, dimensions were (m s^-1, )
Return the sec of this Quantity if it is dimensionless.
EXAMPLES:
sage: sec(0.4*metre/(1000 * metre))
1.00000008000001
sage: sec(99 * joule)
...
DimensionMismatchError: Argument of 'sec' must be dimensionless, dimensions were (m^2 kg s^-2, )
Set the physical dimensions of this object.
For the accepted input see documentation for Dimension.
EXAMPLES:
sage: a = Quantity(2)
sage: a.set_dimensions(m=1)
sage: a
2 m
sage: a.set_dimensions(J=1)
...
KeyError: 'J'
Set the display name of this object.
EXAMPLE:
sage: from additional_units import m_J
sage: mass_of_earth = 5.9736 * 10**24 * kilogram
sage: mass_of_earth.set_dispname('m_E')
sage: m_J % mass_of_earth
317.831793223517 m_E
Set the flydims of this object.
Can be used either with a Flydim or with keywords. See documentation for Flydim.
EXAMPLE:
sage: a = Quantity(2)
sage: a.set_flydims(pineapple=1)
sage: a
2 pineapple
Set the preferred unit of this object.
NOTES:
The different types of input for unit are:
- '' - self is printed using the best unit found in the registries (this is the default for new Quantities)
- 'self' - self is printed using its own dispname, no numerical value is printed (this is useful for Quantities which are primarily used as units, it is the default setting for all pre-defined units)
- 'base' – self is printed using the base units specified in Quantity.base_unit_set or the SI base units if there is no specified set
- a Quantity - self is printed in terms of that object. The two Quantities must have the same dimensions.
- a parseable string - a new quantity object will be created from the results of parsing, the string itself will become the dispname of that object. If any self-defined Quantities or Flydims are used in the string, the corresponding objects have to be made known to the function as keyword arguments of the form name_used_in_string=name_of_quantity. See also documentation for quantity_parser.set_preferred_product()
EXAMPLES:
There is no pre-defined unit for velocity, so a velocity is printed in terms of the base units unless otherwise specified:
sage: v = 10 * meter / second
sage: v
10 m s^-1
sage: v.set_preferred('m/s')
sage: v
10.0 m/s
There is a pre-defined unit of force, so that is used by default for any force:
sage: F = 3 * newton
sage: F
3 N
sage: F.set_preferred('base')
sage: F
3 m kg s^-2
Before setting the preferred unit to ‘self’, a display name must be specified for the Quantity, but just setting the display name will not influence how the Quantity itself prints.
sage: calorie = 4186.8 * joule
sage: calorie.set_dispname('kcal')
sage: calorie
4186.80000000000 J
sage: calorie.set_preferred('self')
sage: calorie
kcal
Return the sine of this Quantity if it is dimensionless.
EXAMPLES:
sage: sin(pi*500*metre/(1000*metre))
1.0
sage: sin(-67 * kelvin)
...
DimensionMismatchError: Argument of 'sin' must be dimensionless, dimensions were (K, )
Return the square root of this object.
EXAMPLES:
sage: sqrt(4 * joule/kilogram)
2.0 m s^-1.0
Return the tan of this Quantity if it is dimensionless.
EXAMPLES:
sage: tan(-0.2*newton*metre/joule)
-0.202710035508673
sage: tan(2/3 * coulomb)
...
DimensionMismatchError: Argument of 'tan' must be dimensionless, dimensions were (s A, )
Static method for creating a Quantity object with dimensions and other attributes.
OUTPUT: a Quantity with the given attributes
NOTES:
The user will not need to use this method as new quantities can be created simply through arithmetic.
EXAMPLES:
sage: x = Quantity.with_dimensions(2, Dimension(length=1))
sage: y = 2 * metre
sage: x == y
True
Test whether the object is a 1d number type including rationals and complex numbers.
OUTPUT: a bool
NOTES:
This function is mostly used internally by the module for argument type checking. A scalar type can be considered a dimensionless quantity (see the documentation for Quantity for more information). Returns True also if obj is a symbolic Expression that can be converted into a complex number.
EXAMPLES:
These are scalar types:
sage: is_scalar_type(pi)
True
sage: is_scalar_type(2 + I)
True
sage: is_scalar_type(2/3)
True
These aren’t:
sage: is_scalar_type(3*meter)
False
sage: is_scalar_type(Flydim())
False
Return the dimensions of an object.
OUTPUT: a tuple (physical dimensions, flydims)
NOTES:
More general than obj.get_dimensions() because it works on scalar types as well as Dimension, Flydim and Quantity. Returns both physical dimension and flydims. Will raise an error if obj is neither one of the dimensional types nor a scalar type.
EXAMPLES:
sage: person = Flydim('person')
sage: energy_usage = 125 * 3.6 * 10**6 * joule / person
sage: get_dimensions(energy_usage)
(m^2 kg s^-2, person^-1)
sage: get_dimensions(energy_usage)[1]
person^-1
sage: get_dimensions('meter')
...
TypeError: Cannot get dimensions for 'str'
Register a new unit for automatic displaying of quantities.
EXAMPLE:
sage: 2*farad/metre**2
2 m^-4 kg^-1 s^4 A^2
sage: register_new_unit('pF/mm^2')
sage: 2*farad/metre**2
2000000.0 pF/mm^2
Test if two objects have the same dimensions.
OUTPUT: a bool
EXAMPLES:
sage: have_same_dimensions(4, 2*radian)
True
sage: have_same_dimensions(3.5*meter, 4*second)
False
Test whether an object is dimensionless, returns a bool.
OUTPUT: a bool
EXAMPLES:
sage: is_dimensionless(CDF((-1)**(1/2)))
True
sage: is_dimensionless(6*meter/metre)
True
sage: is_dimensionless(Dimension(s=1))
False
Return the value of an object.
OUTPUT: a number, obj._value for a Quantity and obj for a number
NOTES:
Will return 1 for a Flydim and 0 for input None. The latter behaviour is used by the quant_matrix.qmatrix() function.
EXAMPLES:
sage: get_value(2/3)
2/3
sage: get_value(9*meter/(2*second))
4.5
sage: get_value(None)
0
sage: get_value('meter')
...
TypeError: Cannot get value for 'str'
sage: get_value(Flydim())
1
Remove all occurrences of a unit from the registries.
EXAMPLE:
sage: 5 * joule
5 J
sage: unregister_unit(joule)
sage: 5 * joule
3.1207547398e+19 eV
sage: register_new_unit(joule) # so this doesn't break other tests
Set the BaseUnitSet that determines how Quantities print for which there are no suitable units in the registers .
NOTES:
It must be possible to express any Quantity in terms of these 7 reference Quantities and they must all have display names.
By default Quantities for which there are no suitable units in the registers will be displayed in the SI base units (metre, kilogram, second, ampere, kelvin, mole, candela). To customize the base unit set, use this function.
EXAMPLE:
sage: from sage.dimpy import *
sage: set_base_units(l_P, m_P, t_P, u4=T_P)
sage: 2 * meter / second
6.67128640831e-09 l_P t_P^-1
A set of base units for displaying Quantities.
OUTPUT: a BaseUnitSet that can be used to express any Quantity
NOTES:
The user will not need to interact with this class directly, use set_base_units().
EXAMPLE:
sage: from sage.dimpy import *
sage: set_base_units(meter, kWh, day)
sage: 15 * meter / second
1296000.0 m d^-1
sage: 100 * kilogram % 'base'
3.72108862978e-15 m^-2 kWh d^2
sage: 5 * kelvin
5 K
Stores known units for printing in best units
NOTES:
All a user needs to do is to use the register_new_unit() function. Units can be deleted from all registries using unregister_unit(). A quantity can be expressed in its best units using the method in_best_unit().
Default registries:
The units module defines three registries, the standard units, user units, and additional units. Finding best units is done by first checking user, then standard, then additional. New user units are added by using the register_new_unit() function.
Standard units includes all the basic non-compound unit names built in to the module, including volt, amp, etc. Additional units includes the non-SI units accepted for use with the SI system like hour, eV etc.
EXAMPLES:
sage: from sage.dimpy import *
sage: additional_unit_register
Additional Unit Register
sage: additional_unit_register[20*meter]
[AU, km, km]
sage: standard_unit_register[20*meter]
[m, m]
sage: standard_unit_register._latex_()
'\text{Standard Unit Register}'
Add a unit to the registry.
Use register_new_unit() to add elements to the user unit register.
Remove a unit from the registry.
Use unregister_unit() to remove a unit from all registers.