Fixed some typos in the documentation; removed trailing slashes; broke some lines to make diffs easier; changed some hanging indentation according to PEP8

This commit is contained in:
Martin Thoma
2015-04-04 09:48:39 +02:00
parent ff3bf58f7f
commit f4ed37f39c
12 changed files with 200 additions and 115 deletions

View File

@@ -3,11 +3,11 @@
Contexts
========
If you work frequently on certain topics, you will probably find the need
to convert between dimensions based on some pre-established (physical) relationships.
For example, in spectroscopy you need to transform from wavelength to frequency.
These are incompatible units and therefore Pint will raise an error if your do
this directly:
If you work frequently on certain topics, you will probably find the need to
convert between dimensions based on some pre-established (physical)
relationships. For example, in spectroscopy you need to transform from
wavelength to frequency. These are incompatible units and therefore Pint will
raise an error if your do this directly:
.. doctest::
@@ -29,10 +29,11 @@ You probably want to use the relation `frequency = speed_of_light / wavelength`:
<Quantity(5.99584916e+14, 'hertz')>
To make this task easy, Pint has the concept of `contexts` which provides conversion
rules between dimensions. For example, the relation between wavelength and frequency is
defined in the `spectroscopy` context (abbreviated `sp`). You can tell pint to use
this context when you convert a quantity to different units.
To make this task easy, Pint has the concept of `contexts` which provides
conversion rules between dimensions. For example, the relation between
wavelength and frequency is defined in the `spectroscopy` context (abbreviated
`sp`). You can tell pint to use this context when you convert a quantity to
different units.
.. doctest::
@@ -85,8 +86,8 @@ or in the registry:
<Quantity(5.99584916e+14, 'hertz')>
If a conversion rule between two dimensions appears in more than one context,
the one in the last context has precedence. This is easy to remember if you think
that the previous syntax is equivalent to nest contexts:
the one in the last context has precedence. This is easy to remember if you
think that the previous syntax is equivalent to nest contexts:
>>> with ureg.context('sp'):
... with ureg.context('boltzmann') :
@@ -108,9 +109,10 @@ calculate, for example, the wavelength in water of a laser which on air is 530 n
>>> f.to('nm', 'sp', n=1.33)
<Quantity(398.496240602, 'nanometer')>
Contexts can also accept Pint Quantity objects as parameters. For example, the 'chemistry'
context accepts the molecular weight of a substance (as a Quantity with dimensions of
[mass]/[substance]) to allow conversion between moles and mass.
Contexts can also accept Pint Quantity objects as parameters. For example, the
'chemistry' context accepts the molecular weight of a substance (as a Quantity
with dimensions of [mass]/[substance]) to allow conversion between moles and
mass.
.. doctest::
@@ -133,31 +135,33 @@ context is::
[energy] -> [frequency]: value / planck_constant
@end
The `@context` directive indicates the beginning of the transformations which are finished by the
`@end` statement. You can optionally specify parameters for the context in parenthesis.
All parameters are named and default values are mandatory. Multiple parameters
are separated by commas (like in a python function definition). Finally, you provide the name
of the context (e.g. spectroscopy) and, optionally, a short version of the name (e.g. sp)
separated by an equal sign. See the definition of the 'chemistry' context in default_en.txt
for an example of a multiple-parameter context.
The `@context` directive indicates the beginning of the transformations which
are finished by the `@end` statement. You can optionally specify parameters for
the context in parenthesis. All parameters are named and default values are
mandatory. Multiple parameters are separated by commas (like in a python
function definition). Finally, you provide the name of the context (e.g.
spectroscopy) and, optionally, a short version of the name (e.g. sp) separated
by an equal sign. See the definition of the 'chemistry' context in
default_en.txt for an example of a multiple-parameter context.
Conversions rules are specified by providing source and destination dimensions separated
using a colon (`:`) from the equation. A special variable named `value` will be replaced
by the source quantity. Other names will be looked first in the context arguments and
then in registry.
Conversions rules are specified by providing source and destination dimensions
separated using a colon (`:`) from the equation. A special variable named
`value` will be replaced by the source quantity. Other names will be looked
first in the context arguments and then in registry.
A single forward arrow (`->`) indicates that the equations is used to transform
from the first dimension to the second one. A double arrow (`<->`) is used to
indicate that the transformation operates both ways.
Context definitions are stored and imported exactly like custom units definition file
(and can be included in the same file as unit definitions). See "Defining units" for details.
Context definitions are stored and imported exactly like custom units
definition file (and can be included in the same file as unit definitions). See
"Defining units" for details.
Defining contexts programmatically
----------------------------------
You can create `Context` object, and populate the conversion rules using python functions.
For example:
You can create `Context` object, and populate the conversion rules using python
functions. For example:
.. doctest::

View File

@@ -7,25 +7,40 @@ Defining units
In a definition file
--------------------
To define units in a persistent way you need to create a unit definition file. Such files are simple text files in which the units are defined as function of other units. For example this is how the minute and the hour are defined in `default_en.txt`::
To define units in a persistent way you need to create a unit definition file.
Such files are simple text files in which the units are defined as function of
other units. For example this is how the minute and the hour are defined in
`default_en.txt`::
hour = 60 * minute = h = hr
minute = 60 * second = min
It is quite straightforward, isn't it? We are saying that `minute` is `60 seconds` and is also known as `min`. The first word is always the canonical name. Next comes the definition (based on other units). Finally, a list of aliases, separated by equal signs.
It is quite straightforward, isn't it? We are saying that `minute` is
`60 seconds` and is also known as `min`. The first word is always the canonical
name. Next comes the definition (based on other units). Finally, a list of
aliases, separated by equal signs.
The order in which units are defined does not matter, Pint will resolve the dependencies to define them in the right order. What is important is that if you transverse all definitions, a reference unit is reached. A reference unit is not defined as a function of another units but of a dimension. For the time in `default_en.txt`, this is the `second`::
The order in which units are defined does not matter, Pint will resolve the
dependencies to define them in the right order. What is important is that if
you transverse all definitions, a reference unit is reached. A reference unit
is not defined as a function of another units but of a dimension. For the time
in `default_en.txt`, this is the `second`::
second = [time] = s = sec
By defining `second` as equal to a string `time` in square brackets we indicate that:
By defining `second` as equal to a string `time` in square brackets we indicate
that:
* `time` is a physical dimension.
* `second` is a reference unit.
The ability to define basic physical dimensions as well as reference units allows to construct arbitrary units systems.
The ability to define basic physical dimensions as well as reference units
allows to construct arbitrary units systems.
Pint is shipped with a default definition file named `default_en.txt` where `en` stands for english. You can add your own definitions to the end of this file but you will have to be careful to merge when you update Pint. An easier way is to create a new file (e.g. `mydef.txt`) with your definitions::
Pint is shipped with a default definition file named `default_en.txt` where
`en` stands for English. You can add your own definitions to the end of this
file but you will have to be careful to merge when you update Pint. An easier
way is to create a new file (e.g. `mydef.txt`) with your definitions::
dog_year = 52 * day = dy
@@ -37,7 +52,9 @@ and then in Python, you can load it as:
>>> # Then we append the new definitions
>>> ureg.load_definitions('/your/path/to/my_def.txt') # doctest: +SKIP
If you make a translation of the default units or define a completely new set, you don't want to append the translated definitions so you just give the filename to the constructor::
If you make a translation of the default units or define a completely new set,
you don't want to append the translated definitions so you just give the
filename to the constructor::
>>> from pint import UnitRegistry
>>> ureg = UnitRegistry('/your/path/to/default_es.txt')
@@ -46,13 +63,17 @@ In the definition file, prefixes are identified by a trailing dash::
yocto- = 10.0**-24 = y-
It is important to note that prefixed defined in this way can be used with any unit, including non-metric ones (e.g. kiloinch is valid for Pint). This simplifies definitions files enormously without introducing major problems. Pint, like Python, believes that we are all consenting adults.
It is important to note that prefixed defined in this way can be used with any
unit, including non-metric ones (e.g. kiloinch is valid for Pint). This
simplifies definitions files enormously without introducing major problems.
Pint, like Python, believes that we are all consenting adults.
Programmatically
----------------
You can easily add units to the registry programmatically. Let's add a dog_year (sometimes writen as dy) equivalent to 52 (human) days:
You can easily add units to the registry programmatically. Let's add a dog_year
(sometimes written as dy) equivalent to 52 (human) days:
.. doctest::
@@ -70,7 +91,8 @@ You can easily add units to the registry programmatically. Let's add a dog_year
>>> print(lassie_lifespan.to('dog_years'))
70.23888438100961 dog_year
Note that we have used the name `dog_years` even though we have not defined the plural form as an alias. Pint takes care of that, so you don't have to.
Note that we have used the name `dog_years` even though we have not defined the
plural form as an alias. Pint takes care of that, so you don't have to.
You can also add prefixes programmatically:

View File

@@ -7,41 +7,61 @@ Pint: a Python units library
:alt: Pint: **physical quantities**
:class: floatingflask
Pint is Python package to define, operate and manipulate **physical quantities**: the product of a numerical value and a unit of measurement. It allows arithmetic operations between them and conversions from and to different units.
Pint is Python package to define, operate and manipulate **physical quantities**:
the product of a numerical value and a unit of measurement. It allows
arithmetic operations between them and conversions from and to different units.
It is distributed with a `comprehensive list of physical units, prefixes and constants`_. Due to its modular design, you can extend (or even rewrite!) the complete list without changing the source code. It supports a lot of numpy mathematical operations **without monkey patching or wrapping numpy**.
It is distributed with a `comprehensive list of physical units, prefixes and constants`_.
Due to its modular design, you can extend (or even rewrite!) the complete list
without changing the source code. It supports a lot of numpy mathematical
operations **without monkey patching or wrapping numpy**.
It has a complete test coverage. It runs in Python 2.6+ and 3.2+ with no other dependency. It licensed under BSD.
It has a complete test coverage. It runs in Python 2.6+ and 3.2+ with no other
dependency. It licensed under BSD.
Design principles
-----------------
Although there are already a few very good Python packages to handle physical quantities, no one was really fitting my needs. Like most developers, I programed Pint to scratch my own itches.
Although there are already a few very good Python packages to handle physical
quantities, no one was really fitting my needs. Like most developers, I
programmed Pint to scratch my own itches.
**Unit parsing**: prefixed and pluralized forms of units are recognized without explicitly defining them.
In other words: as the prefix *kilo* and the unit *meter* are defined, Pint understands *kilometers*.
This results in a much shorter and maintainable unit definition list as compared to other packages.
**Unit parsing**: prefixed and pluralized forms of units are recognized without
explicitly defining them. In other words: as the prefix *kilo* and the unit
*meter* are defined, Pint understands *kilometers*. This results in a much
shorter and maintainable unit definition list as compared to other packages.
**Standalone unit definitions**: units definitions are loaded from a text file which is simple and easy to edit.
Adding and changing units and their definitions does not involve changing the code.
**Standalone unit definitions**: units definitions are loaded from a text file
which is simple and easy to edit. Adding and changing units and their
definitions does not involve changing the code.
**Advanced string formatting**: a quantity can be formatted into string using PEP 3101 syntax.
Extended conversion flags are given to provide symbolic, latex and pretty formatting.
**Advanced string formatting**: a quantity can be formatted into string using
`PEP 3101`_ syntax. Extended conversion flags are given to provide symbolic,
LaTeX and pretty formatting.
**Free to choose the numerical type**: You can use any numerical type (`fraction`, `float`, `decimal`, `numpy.ndarray`, etc). NumPy_ is not required but supported.
**Free to choose the numerical type**: You can use any numerical type
(`fraction`, `float`, `decimal`, `numpy.ndarray`, etc). NumPy_ is not required
but supported.
**NumPy integration**: When you choose to use a NumPy_ ndarray, its methods and ufuncs are supported including automatic conversion of units. For example `numpy.arccos(q)` will require a dimensionless `q` and the units of the output quantity will be radian.
**NumPy integration**: When you choose to use a NumPy_ ndarray, its methods and
ufuncs are supported including automatic conversion of units. For example
`numpy.arccos(q)` will require a dimensionless `q` and the units of the output
quantity will be radian.
**Uncertainties integration**: transparently handles calculations with quantities with uncertainties (like 3.14±0.01) meter via the `uncertainties package`_.
**Uncertainties integration**: transparently handles calculations with
quantities with uncertainties (like 3.14±0.01) meter via the `uncertainties
package`_.
**Handle temperature**: conversion between units with different reference points, like positions on a map or absolute temperature scales.
**Handle temperature**: conversion between units with different reference
points, like positions on a map or absolute temperature scales.
**Small codebase**: easy to maintain codebase with a flat hierarchy.
**Dependency free**: it depends only on Python and its standard library.
**Python 2 and 3**: a single codebase that runs unchanged in Python 2.7+ and Python 3.0+.
**Python 2 and 3**: a single codebase that runs unchanged in Python 2.7+ and
Python 3.0+.
@@ -88,3 +108,4 @@ One last thing
.. _`comprehensive list of physical units, prefixes and constants`: https://github.com/hgrecco/pint/blob/master/pint/default_en.txt
.. _`uncertainties package`: https://pythonhosted.org/uncertainties/
.. _`NumPy`: http://www.numpy.org/
.. _`PEP 3101`: https://www.python.org/dev/peps/pep-3101/

View File

@@ -5,10 +5,10 @@ Temperature conversion
======================
Unlike meters and seconds, the temperature units fahrenheits and
celsius are non-multiplicative units. These temperature units are
celsius are non-multiplicative units. These temperature units are
expressed in a system with a reference point, and relations between
temperature units include not only a scaling factor but also an offset.
Pint supports these type of units and conversions between them.
Pint supports these type of units and conversions between them.
The default definition file includes fahrenheits, celsius,
kelvin and rankine abbreviated as degF, degC, degK, and degR.
@@ -39,7 +39,7 @@ or to other kelvin or rankine:
537.39 degR
Additionally, for every non-multiplicative temperature unit
in the registry, there is also a *delta* counterpart to specify
in the registry, there is also a *delta* counterpart to specify
differences. Absolute units have no *delta* counterpart.
For example, the change in celsius is equal to the change
in kelvin, but not in fahrenheit (as the scaling factor
@@ -61,7 +61,7 @@ Subtraction of two temperatures given in offset units yields a *delta* unit:
>>> Q_(25.4, ureg.degC) - Q_(10., ureg.degC)
<Quantity(15.4, 'delta_degC')>
You can add or subtract a quantity with *delta* unit and a quantity with
You can add or subtract a quantity with *delta* unit and a quantity with
offset unit:
.. doctest::
@@ -81,7 +81,7 @@ If you want to add a quantity with absolute unit to one with offset unit, like h
...
pint.unit.OffsetUnitCalculusError: Ambiguous operation with offset unit (degC, kelvin).
you have to avoid the ambiguity by either converting the offset unit to the
you have to avoid the ambiguity by either converting the offset unit to the
absolute unit before addition
.. doctest::
@@ -96,10 +96,10 @@ or convert the absolute unit to a *delta* unit:
>>> Q_(10., ureg.degC) + heating_rate.to('delta_degC/min') * Q_(30, ureg.min)
<Quantity(25.0, 'degC')>
In contrast to subtraction, the addition of quantities with offset units
In contrast to subtraction, the addition of quantities with offset units
is ambiguous, e.g. for *10 degC + 100 degC* two different result are reasonable
depending on the context, *110 degC* or *383.15 °C (= 283.15 K + 373.15 K)*.
Because of this ambiguity pint raises an error for the addition of two
Because of this ambiguity pint raises an error for the addition of two
quantities with offset units (since pint-0.6).
Quantities with *delta* units are multiplicative:
@@ -110,7 +110,7 @@ Quantities with *delta* units are multiplicative:
>>> print(speed.to('delta_degC/second'))
1.0 delta_degC / second
However, multiplication, division and exponentiation of quantities with
However, multiplication, division and exponentiation of quantities with
offset units is problematic just like addition. Pint (since version 0.6)
will by default raise an error when a quantity with offset unit is used in
these operations. Due to this quantities with offset units cannot be created
@@ -139,11 +139,11 @@ to true. In this mode, pint behaves differently:
>>> T = 25.4 * ureg.degC
>>> T
<Quantity(25.4, 'degC')>
* Before all other multiplications, all divisions and in case of
exponentiation [#f1]_ involving quantities with offset-units, pint
will convert the quantities with offset units automatically to the
corresponding base unit before performing the operation.
* Before all other multiplications, all divisions and in case of
exponentiation [#f1]_ involving quantities with offset-units, pint
will convert the quantities with offset units automatically to the
corresponding base unit before performing the operation.
>>> 1/T
<Quantity(0.00334952269302, '1 / kelvin')>

View File

@@ -121,13 +121,30 @@ And the following `ndarrays methods`_ and functions:
Comments
--------
What follows is a short discussion about how NumPy support is implemented in Pint's `Quantity` Object.
What follows is a short discussion about how NumPy support is implemented in
Pint's `Quantity` Object.
For the supported functions, Pint expects certain units and attempts to convert the input (or inputs). For example, the argument of the exponential function (`numpy.exp`) must be dimensionless. Units will be simplified (converting the magnitude appropriately) and `numpy.exp` will be applied to the resulting magnitude. If the input is not dimensionless, a `DimensionalityError` exception will be raised.
For the supported functions, Pint expects certain units and attempts to convert
the input (or inputs). For example, the argument of the exponential function
(`numpy.exp`) must be dimensionless. Units will be simplified (converting the
magnitude appropriately) and `numpy.exp` will be applied to the resulting
magnitude. If the input is not dimensionless, a `DimensionalityError` exception
will be raised.
In some functions that take 2 or more arguments (e.g. `arctan2`), the second argument is converted to the units of the first. Again, a `DimensionalityError` exception will be raised if this is not possible.
In some functions that take 2 or more arguments (e.g. `arctan2`), the second
argument is converted to the units of the first. Again, a `DimensionalityError`
exception will be raised if this is not possible.
This behaviour introduces some performance penalties and increased memory usage. Quantities that must be converted to other units require additional memory and cpu cycles. On top of this, all `ufuncs` are implemented in the `Quantity` class by overriding `__array_wrap__`, a NumPy hook that is executed after the calculation and before returning the value. To our knowledge, there is no way to signal back to NumPy that our code will take care of the calculation. For this reason the calculation is actually done twice: first in the original ndarray and then in then in the one that has been converted to the right units. Therefore, for numerically intensive code, you might want to convert the objects first and then use directly the magnitude.
This behaviour introduces some performance penalties and increased memory
usage. Quantities that must be converted to other units require additional
memory and CPU cycles. On top of this, all `ufuncs` are implemented in the
`Quantity` class by overriding `__array_wrap__`, a NumPy hook that is executed
after the calculation and before returning the value. To our knowledge, there
is no way to signal back to NumPy that our code will take care of the
calculation. For this reason the calculation is actually done twice:
first in the original ndarray and then in then in the one that has been
converted to the right units. Therefore, for numerically intensive code, you
might want to convert the objects first and then use directly the magnitude.

View File

@@ -75,7 +75,7 @@ To unpickle, just
<Quantity(24.2, 'year')>
You can use the same mechanism with any serialization protocol, not only with binary ones.
(In fact, version 0 of the Pickle protocol is ascii). Other common serialization protocols/packages
(In fact, version 0 of the Pickle protocol is ASCII). Other common serialization protocols/packages
are json_, yaml_, shelve_, hdf5_ (or via PyTables_) and dill_.
Notice that not all of these packages will serialize properly the magnitude (which can be any
numerical type such as `numpy.ndarray`)

View File

@@ -7,7 +7,8 @@ Tutorial
Converting Quantities
---------------------
Pint has the concept of Unit Registry, an object within which units are defined and handled. You start by creating your registry::
Pint has the concept of Unit Registry, an object within which units are defined
and handled. You start by creating your registry::
>>> from pint import UnitRegistry
>>> ureg = UnitRegistry()
@@ -18,7 +19,8 @@ Pint has the concept of Unit Registry, an object within which units are defined
ureg = UnitRegistry()
Q_ = ureg.Quantity
If no parameter is given to the constructor, the unit registry is populated with the default list of units and prefixes.
If no parameter is given to the constructor, the unit registry is populated
with the default list of units and prefixes.
You can now simply use the registry in the following way:
.. doctest::
@@ -32,7 +34,9 @@ You can now simply use the registry in the following way:
>>> print(repr(time))
<Quantity(8.0, 'second')>
In this code `distance` and `time` are physical quantity objects (`Quantity`). Physical quantities can be queried for their magnitude, units, and dimensionality:
In this code `distance` and `time` are physical quantity objects (`Quantity`).
Physical quantities can be queried for their magnitude, units, and
dimensionality:
.. doctest::
@@ -51,7 +55,8 @@ and can handle mathematical operations between:
>>> print(speed)
3.0 meter / second
As unit registry knows about the relationship between different units, you can convert quantities to the unit of choice:
As unit registry knows about the relationship between different units, you can
convert quantities to the unit of choice:
.. doctest::
@@ -65,7 +70,8 @@ This method returns a new object leaving the original intact as can be seen by:
>>> print(speed)
3.0 meter / second
If you want to convert in-place (i.e. without creating another object), you can use the `ito` method:
If you want to convert in-place (i.e. without creating another object), you can
use the `ito` method:
.. doctest::
@@ -84,7 +90,8 @@ If you ask Pint to perform an invalid conversion:
pint.pint.DimensionalityError: Cannot convert from 'inch / minute' (length / time) to 'joule' (length ** 2 * mass / time ** 2)
There are also methods 'to_base_units' and 'ito_base_units' which automatically convert to the reference units with the correct dimensionality:
There are also methods 'to_base_units' and 'ito_base_units' which automatically
convert to the reference units with the correct dimensionality:
.. doctest::
@@ -100,7 +107,8 @@ There are also methods 'to_base_units' and 'ito_base_units' which automatically
1.7526 meter
In some cases it is useful to define physical quantities objects using the class constructor:
In some cases it is useful to define physical quantities objects using the
class constructor:
.. doctest::
@@ -108,7 +116,8 @@ In some cases it is useful to define physical quantities objects using the class
>>> Q_(1.78, ureg.meter) == 1.78 * ureg.meter
True
(I tend to abbreviate Quantity as `Q_`) The built-in parser recognizes prefixed and pluralized units even though they are not in the definition list:
(I tend to abbreviate Quantity as `Q_`) The built-in parser recognizes prefixed
and pluralized units even though they are not in the definition list:
.. doctest::
@@ -127,7 +136,8 @@ If you try to use a unit which is not in the registry:
...
pint.pint.UndefinedUnitError: 'snail_speed' is not defined in the unit registry
You can add your own units to the registry or build your own list. More info on that :ref:`defining`
You can add your own units to the registry or build your own list. More info on
that :ref:`defining`
String parsing
@@ -206,7 +216,8 @@ Pint's physical quantities can be easily printed:
of `{}`, `{0!s}` instead of `{!s}` in string formatting operations.
But Pint also extends the standard formatting capabilities for unicode and latex representations:
But Pint also extends the standard formatting capabilities for unicode and
LaTeX representations:
.. doctest::
@@ -221,7 +232,7 @@ But Pint also extends the standard formatting capabilities for unicode and latex
>>> 'The HTML representation is {:H}'.format(accel)
'The HTML representation is 1.3 meter/second<sup>2</sup>'
.. note::
.. note::
In Python 2, run ``from __future__ import unicode_literals``
or prefix pretty formatted strings with `u` to prevent ``UnicodeEncodeError``.
@@ -249,8 +260,10 @@ Finally, you can specify a default format specification:
Using Pint in your projects
---------------------------
If you use Pint in multiple modules within your Python package, you normally want to avoid creating multiple instances of the unit registry.
The best way to do this is by instantiating the registry in a single place. For example, you can add the following code to your package `__init__.py`::
If you use Pint in multiple modules within your Python package, you normally
want to avoid creating multiple instances of the unit registry.
The best way to do this is by instantiating the registry in a single place. For
example, you can add the following code to your package `__init__.py`::
from pint import UnitRegistry
ureg = UnitRegistry()
@@ -264,7 +277,8 @@ Then in `yourmodule.py` the code would be::
length = 10 * ureg.meter
my_speed = Q_(20, 'm/s')
If you are pickling and unplicking Quantities within your project, you should also define the registry as the application registry::
If you are pickling and unplicking Quantities within your project, you should
also define the registry as the application registry::
from pint import UnitRegistry, set_application_registry
ureg = UnitRegistry()

View File

@@ -34,8 +34,8 @@ def _expression_to_function(eq):
class Context(object):
"""A specialized container that defines transformation functions from
one dimension to another. Each Dimension are specified using a UnitsContainer.
"""A specialized container that defines transformation functions from one
dimension to another. Each Dimension are specified using a UnitsContainer.
Simple transformation are given with a function taking a single parameter.
>>> timedim = UnitsContainer({'[time]': 1})
@@ -48,8 +48,8 @@ class Context(object):
>>> c.transform(timedim, spacedim, 2)
6
Conversion functions may take optional keyword arguments and the context can
have default values for these arguments.
Conversion functions may take optional keyword arguments and the context
can have default values for these arguments.
>>> def f(time, n):
... 'Time to length converter, n is the index of refraction of the material'
@@ -78,9 +78,9 @@ class Context(object):
@classmethod
def from_context(cls, context, **defaults):
"""Creates a new context that shares the funcs dictionary with the original
context. The default values are copied from the original context and updated
with the new defaults.
"""Creates a new context that shares the funcs dictionary with the
original context. The default values are copied from the original
context and updated with the new defaults.
If defaults is empty, return the same context.
"""

View File

@@ -149,7 +149,8 @@ class DimensionDefinition(Definition):
self.is_base = False
else:
raise ValueError('Base dimensions must be referenced to None. '
'Derived dimensions must only be referenced to dimensions.')
'Derived dimensions must only be referenced '
'to dimensions.')
self.reference = UnitsContainer(converter)
super(DimensionDefinition, self).__init__(name, symbol, aliases,

View File

@@ -14,6 +14,7 @@ from .formatting import _FORMATS
MISSING = object()
class _Measurement(object):
"""Implements a class to describe a quantity with uncertainty.
@@ -96,6 +97,3 @@ class _Measurement(object):
return mag + ' ' + format(self.units, spec)
else:
return pars.format(mag) + ' ' + format(self.units, spec)

View File

@@ -60,7 +60,8 @@ class _Quantity(SharedRegistryObject):
if units is None:
if isinstance(value, string_types):
if value == '':
raise ValueError('Expression to parse as Quantity cannot be an empty string.')
raise ValueError('Expression to parse as Quantity cannot '
'be an empty string.')
inst = cls._REGISTRY.parse_expression(value)
return cls.__new__(cls, inst)
elif isinstance(value, cls):
@@ -80,7 +81,8 @@ class _Quantity(SharedRegistryObject):
elif isinstance(units, SharedRegistryObject):
if isinstance(units, _Quantity) and units.magnitude != 1:
inst = copy.copy(units)
logger.warning('Creating new Quantity using a non unity Quantity as units.')
logger.warning('Creating new Quantity using a non unity '
'Quantity as units.')
else:
inst = object.__new__(cls)
inst._units = units._units
@@ -103,8 +105,8 @@ class _Quantity(SharedRegistryObject):
return ret
def __deepcopy__(self, memo):
ret = self.__class__(copy.deepcopy(self._magnitude, memo),
copy.deepcopy(self._units, memo))
ret = self.__class__(copy.deepcopy(self._magnitude, memo),
copy.deepcopy(self._units, memo))
ret.__used = self.__used
return ret
@@ -346,8 +348,9 @@ class _Quantity(SharedRegistryObject):
if _eq(other, 0, True):
# If the other value is 0 (but not Quantity 0)
# do the operation without checking units.
# We do the calculation instead of just returning the same value to
# enforce any shape checking and type casting due to the operation.
# We do the calculation instead of just returning the same
# value to enforce any shape checking and type casting due to
# the operation.
self._magnitude = op(self._magnitude, other_magnitude)
elif self.dimensionless:
self.ito(UnitsContainer())
@@ -439,8 +442,9 @@ class _Quantity(SharedRegistryObject):
if _eq(other, 0, True):
# If the other value is 0 (but not Quantity 0)
# do the operation without checking units.
# We do the calculation instead of just returning the same value to
# enforce any shape checking and type casting due to the operation.
# We do the calculation instead of just returning the same
# value to enforce any shape checking and type casting due to
# the operation.
units = self._units
magnitude = op(self._magnitude,
_to_magnitude(other, self.force_ndarray))
@@ -508,7 +512,7 @@ class _Quantity(SharedRegistryObject):
# Replace offset unit in self by the corresponding delta unit.
# This is done to prevent a shift by offset in the to()-call.
tu = self._units.rename(self_non_mul_unit,
'delta_' + self_non_mul_unit)
'delta_' + self_non_mul_unit)
magnitude = op(self._magnitude, other.to(tu).magnitude)
units = self._units
elif (len(other_non_mul_units) == 1
@@ -518,7 +522,7 @@ class _Quantity(SharedRegistryObject):
# Replace offset unit in other by the corresponding delta unit.
# This is done to prevent a shift by offset in the to()-call.
tu = other._units.rename(other_non_mul_unit,
'delta_' + other_non_mul_unit)
'delta_' + other_non_mul_unit)
magnitude = op(self._convert_magnitude(tu), other._magnitude)
units = other._units
else:
@@ -550,13 +554,16 @@ class _Quantity(SharedRegistryObject):
return -self._add_sub(other, operator.sub)
def _imul_div(self, other, magnitude_op, units_op=None):
"""Perform multiplication or division operation in-place and return the result.
"""Perform multiplication or division operation in-place and return the
result.
:param other: object to be multiplied/divided with self
:type other: Quantity or any type accepted by :func:`_to_magnitude`
:param magnitude_op: operator function to perform on the magnitudes (e.g. operator.mul)
:param magnitude_op: operator function to perform on the magnitudes
(e.g. operator.mul)
:type magnitude_op: function
:param units_op: operator function to perform on the units; if None, *magnitude_op* is used
:param units_op: operator function to perform on the units; if None,
*magnitude_op* is used
:type units_op: function or None
"""
if units_op is None:
@@ -610,9 +617,11 @@ class _Quantity(SharedRegistryObject):
:param other: object to be multiplied/divided with self
:type other: Quantity or any type accepted by :func:`_to_magnitude`
:param magnitude_op: operator function to perform on the magnitudes (e.g. operator.mul)
:param magnitude_op: operator function to perform on the magnitudes
(e.g. operator.mul)
:type magnitude_op: function
:param units_op: operator function to perform on the units; if None, *magnitude_op* is used
:param units_op: operator function to perform on the units; if None,
*magnitude_op* is used
:type units_op: function or None
"""
if units_op is None:
@@ -744,7 +753,6 @@ class _Quantity(SharedRegistryObject):
if np.size(other) > 1:
raise DimensionalityError(self._units, 'dimensionless')
new_self = self
if other == 1:
return self
elif other == 0:

View File

@@ -10,7 +10,7 @@
# Fixed for to work in Python 2 & 3 with "add_metaclass" decorator from six
# https://pypi.python.org/pypi/six
# Author: Benjamin Peterson
# License: MIT
# License: MIT
#
# Use like this:
#