summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
Diffstat (limited to 'docs')
-rw-r--r--docs/defining.rst14
-rw-r--r--docs/index.rst1
-rw-r--r--docs/numpy.ipynb11
-rw-r--r--docs/pint-convert.rst91
-rw-r--r--docs/pint-pandas.ipynb37
-rw-r--r--docs/tutorial.rst69
6 files changed, 196 insertions, 27 deletions
diff --git a/docs/defining.rst b/docs/defining.rst
index 7aba5bb..152893a 100644
--- a/docs/defining.rst
+++ b/docs/defining.rst
@@ -138,3 +138,17 @@ Same for aliases and derived dimensions:
.. warning::
Units, prefixes, aliases and dimensions added programmatically are forgotten when the
program ends.
+
+
+Units with constants
+--------------------
+
+Some units, such as ``L/100km``, contain constants. These can be defined with a
+leading underscore:
+
+.. doctest::
+
+ >>> ureg.define('_100km = 100 * kilometer')
+ >>> ureg.define('mpg = 1 * mile / gallon')
+ >>> fuel_ec_europe = 5 * ureg.L / ureg._100km
+ >>> fuel_ec_us = (1 / fuel_ec_europe).to(ureg.mpg)
diff --git a/docs/index.rst b/docs/index.rst
index e72ed87..5d22dda 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -128,6 +128,7 @@ User Guide
systems
currencies
pint-pandas.ipynb
+ pint-convert
More information
----------------
diff --git a/docs/numpy.ipynb b/docs/numpy.ipynb
index 2dc6078..41b6491 100644
--- a/docs/numpy.ipynb
+++ b/docs/numpy.ipynb
@@ -24,10 +24,6 @@
"# Import NumPy\n",
"import numpy as np\n",
"\n",
- "# Disable Pint's old fallback behavior (must come before importing Pint)\n",
- "import os\n",
- "os.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = \"0\"\n",
- "\n",
"# Import Pint\n",
"import pint\n",
"ureg = pint.UnitRegistry()\n",
@@ -778,10 +774,9 @@
"To achive these function and ufunc overrides, Pint uses the ``__array_function__`` and ``__array_ufunc__`` protocols respectively, as recommened by NumPy. This means that functions and ufuncs that Pint does not explicitly handle will error, rather than return a value with units stripped (in contrast to Pint's behavior prior to v0.10). For more\n",
"information on these protocols, see <https://docs.scipy.org/doc/numpy-1.17.0/user/basics.dispatch.html>.\n",
"\n",
- "This behaviour introduces some performance penalties and increased memory usage. Quantities that must be converted to other units require additional memory and CPU cycles. Therefore, for numerically intensive code, you might want to convert the objects first and then use directly the magnitude, such as by using Pint's `wraps` utility (see [wrapping](wrapping.html)).\n",
+ "This behaviour introduces some performance penalties and increased memory usage. Quantities that must be converted to other units require additional memory and CPU cycles. Therefore, for numerically intensive code, you might want to convert the objects first and then use directly the magnitude, such as by using Pint's `wraps` utility (see [wrapping](wrapping.rst)).\n",
"\n",
- "Array interface protocol attributes (such as `__array_struct__` and\n",
- "`__array_interface__`) are available on Pint Quantities by deferring to the corresponding `__array_*` attribute on the magnitude as casted to an ndarray. This has been found to be potentially incorrect and to cause unexpected behavior, and has therefore been deprecated. As of the next minor version of Pint (or when the `PINT_ARRAY_PROTOCOL_FALLBACK` environment variable is set to 0 prior to importing Pint as done at the beginning of this page), attempting to access these attributes will instead raise an AttributeError."
+ "Attempting to access array interface protocol attributes (such as `__array_struct__` and `__array_interface__`) on Pint Quantities will raise an AttributeError, since a Quantity is meant to behave as a \"duck array,\" and not a pure ndarray."
]
}
],
@@ -801,7 +796,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
- "version": "3.6.7"
+ "version": "3.7.6"
}
},
"nbformat": 4,
diff --git a/docs/pint-convert.rst b/docs/pint-convert.rst
new file mode 100644
index 0000000..8d548f8
--- /dev/null
+++ b/docs/pint-convert.rst
@@ -0,0 +1,91 @@
+.. _convert:
+
+Command-line script
+===================
+
+The script `pint-convert` allows a quick conversion to a target system or
+between arbitrary compatible units.
+
+By default, `pint-convert` converts to SI units::
+
+ $ pint-convert 225lb
+ 225 pound = 102.05828325 kg
+
+use the `--sys` argument to change it::
+
+ $ pint-convert --sys US 102kg
+ 102 kilogram = 224.871507429 lb
+
+or specify directly the target units::
+
+ $ pint-convert 102kg lb
+ 102 kilogram = 224.871507429 lb
+
+The input quantity can contain expressions::
+
+ $ pint-convert 7ft+2in
+ 7.166666666666667 foot = 2.1844 m
+
+in some cases parentheses and quotes may be needed::
+
+ $ pint-convert "225lb/(7ft+2in)"
+ 31.3953488372093 pound / foot = 46.7214261353 kg/m
+
+If a number is omitted, 1 is assumed::
+
+ $ pint-convert km mi
+ 1 kilometer = 0.621371192237 mi
+
+The default precision is 12 significant figures, it can be changed with `-p`,
+but note that the accuracy may be affected by floating-point errors::
+
+ $ pint-convert -p 3 mi
+ 1 mile = 1.61e+03 m
+
+ $ pint-convert -p 30 ly km
+ 1 light_year = 9460730472580.80078125 km
+
+Some contexts are automatically enabled, allowing conversion between not fully
+compatible units::
+
+ $ pint-convert 540nm
+ 540 nanometer = 5.4e-07 m
+
+ $ pint-convert kcal/mol
+ $ 1.0 kilocalorie / mole = 4184 kg·m²/mol/s²
+
+ $ pint-convert 540nm kcal/mol
+ 540 nanometer = 52.9471025594 kcal/mol
+
+With the `uncertainties` package, the experimental uncertainty in the physical
+constants is considered, and the result is given in compact notation, with the
+uncertainty in the last figures in parentheses::
+
+ $ pint-convert Eh eV
+ 1 hartree = 27.21138624599(5) eV
+
+The precision is limited by both the maximum number of significant digits (`-p`)
+and the maximum number of uncertainty digits (`-u`, 2 by default)::
+
+ $ pint-convert -p 20 Eh eV
+ 1 hartree = 27.211386245988(52) eV
+
+ $ pint-convert -p 20 -u 4 Eh eV
+ 1 hartree = 27.21138624598847(5207) eV
+
+The uncertainty can be disabled with `-U`)::
+
+ $ pint-convert -p 20 -U Eh eV
+ 1 hartree = 27.211386245988471444 eV
+
+Correlations between experimental constants are also known, and taken into
+account. Use `-C` to disable it::
+
+ $ pint-convert --sys atomic m_p
+ 1 proton_mass = 1836.15267344(11) m_e
+
+ $ pint-convert --sys atomic -C m_p
+ 1 proton_mass = 1836.15267344(79) m_e
+
+Again, note that results may differ slightly, usually in the last figure, from
+more authoritative sources, mainly due to floating-point errors.
diff --git a/docs/pint-pandas.ipynb b/docs/pint-pandas.ipynb
index 390831e..e213aff 100644
--- a/docs/pint-pandas.ipynb
+++ b/docs/pint-pandas.ipynb
@@ -6,6 +6,12 @@
"source": [
"# Pandas support\n",
"\n",
+ "<div class=\"alert alert-warning\">\n",
+ "\n",
+ "**Warning:** pandas support is currently experimental, don't expect everything to work.\n",
+ "\n",
+ "</div>\n",
+ "\n",
"It is convenient to use the Pandas package when dealing with numerical data, so Pint provides PintArray. A PintArray is a Pandas Extension Array, which allows Pandas to recognise the Quantity and store it in Pandas DataFrames and Series."
]
},
@@ -13,6 +19,19 @@
"cell_type": "markdown",
"metadata": {},
"source": [
+ "## Installation\n",
+ "\n",
+ "\n",
+ "Pandas support is provided by `pint-pandas`. It is not available on PyPI yet, to install it use\n",
+ "```\n",
+ "python -m pip install git+https://github.com/hgrecco/pint-pandas.git\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
"## Basic example"
]
},
@@ -531,8 +550,8 @@
}
],
"source": [
- "df = pd.read_csv(io.StringIO(test_data),header=[0,1])\n",
- "# df = pd.read_csv(\"/path/to/test_data.csv\",header=[0,1])\n",
+ "df = pd.read_csv(io.StringIO(test_data), header=[0, 1])\n",
+ "# df = pd.read_csv(\"/path/to/test_data.csv\", header=[0, 1])\n",
"df"
]
},
@@ -690,7 +709,7 @@
}
],
"source": [
- "df_.speed*df_.torque"
+ "df_.speed * df_.torque"
]
},
{
@@ -874,7 +893,7 @@
}
],
"source": [
- "df_['mech power'] = df_.speed*df_.torque\n",
+ "df_['mech power'] = df_.speed * df_.torque\n",
"df_['fluid power'] = df_['fuel flow rate'] * df_['rail pressure']\n",
"df_"
]
@@ -1219,7 +1238,7 @@
}
],
"source": [
- "pint.PintType.ureg.default_format = \"~P\"\n",
+ "pintpandas.PintType.ureg.default_format = \"~P\"\n",
"df_.pint.dequantify()"
]
},
@@ -1372,7 +1391,7 @@
"metadata": {},
"outputs": [],
"source": [
- "PA_ = pint.PintArray"
+ "PA_ = pintpandas.PintArray"
]
},
{
@@ -1388,8 +1407,8 @@
"metadata": {},
"outputs": [],
"source": [
- "ureg=pint.UnitRegistry()\n",
- "Q_=ureg.Quantity"
+ "ureg = pint.UnitRegistry()\n",
+ "Q_ = ureg.Quantity"
]
},
{
@@ -1405,7 +1424,7 @@
"metadata": {},
"outputs": [],
"source": [
- "pint.PintType.ureg = ureg"
+ "pintpandas.PintType.ureg = ureg"
]
},
{
diff --git a/docs/tutorial.rst b/docs/tutorial.rst
index 158d2ad..ac9c2b3 100644
--- a/docs/tutorial.rst
+++ b/docs/tutorial.rst
@@ -251,14 +251,14 @@ or
.. note:: Pint´s rule for parsing strings with a mixture of numbers and
units is that **units are treated with the same precedence as numbers**.
-
+
For example, the unit of
.. doctest::
>>> Q_('3 l / 100 km')
<Quantity(0.03, 'kilometer * liter')>
-
+
may be unexpected first but is a consequence of applying this rule. Use
brackets to get the expected result:
@@ -272,6 +272,38 @@ brackets to get the expected result:
exposed to when parsing information from untrusted sources.
+Strings containing values can be parsed using the ``ureg.parse_pattern`` function. A ``format``-like string with the units defined in it is used as the pattern:
+
+.. doctest::
+
+ >>> input_string = '10 feet 10 inches'
+ >>> pattern = '{feet} feet {inch} inches'
+ >>> ureg.parse_pattern(input_string, pattern)
+ [10.0 <Unit('foot')>, 10.0 <Unit('inch')>]
+
+To search for multiple matches, set the ``many`` parameter to ``True``. The following example also demonstrates how the parser is able to find matches in amongst filler characters:
+
+.. doctest::
+
+ >>> input_string = '10 feet - 20 feet ! 30 feet.'
+ >>> pattern = '{feet} feet'
+ >>> ureg.parse_pattern(input_string, pattern, many=True)
+ [[10.0 <Unit('foot')>], [20.0 <Unit('foot')>], [30.0 <Unit('foot')>]]
+
+The full power of regex can also be employed when writing patterns:
+
+.. doctest::
+
+ >>> input_string = "10` - 20 feet ! 30 ft."
+ >>> pattern = r"{feet}(`| feet| ft)"
+ >>> ureg.parse_pattern(input_string, pattern, many=True)
+ [[10.0 <Unit('foot')>], [20.0 <Unit('foot')>], [30.0 <Unit('foot')>]]
+
+*Note that the curly brackets (``{}``) are converted to a float-matching pattern by the parser.*
+
+This function is useful for tasks such as bulk extraction of units from thousands of uniform strings or even very large texts with units dotted around in no particular pattern.
+
+
.. _sec-string-formatting:
String formatting
@@ -303,12 +335,12 @@ Pint supports float formatting for numpy arrays as well:
>>> # scientific form formatting with unit pretty printing
>>> print('The array is {:+.2E~P}'.format(accel))
The array is [-1.10E+00 +1.00E-06 +1.25E+00 +1.30E+00] m/s²
-
+
Pint also supports 'f-strings'_ from python>=3.6 :
.. doctest::
- >>> accel = 1.3 * ureg['meter/second**2']
+ >>> accel = 1.3 * ureg['meter/second**2']
>>> print(f'The str is {accel}')
The str is 1.3 meter / second ** 2
>>> print(f'The str is {accel:.3e}')
@@ -318,7 +350,7 @@ Pint also supports 'f-strings'_ from python>=3.6 :
>>> print(f'The str is {accel:~.3e}')
The str is 1.300e+00 m / s ** 2
>>> print(f'The str is {accel:~H}')
- The str is 1.3 m/s²
+ The str is 1.3 m/s²
But Pint also extends the standard formatting capabilities for unicode and
LaTeX representations:
@@ -349,11 +381,11 @@ If you want to use abbreviated unit names, prefix the specification with `~`:
The same is true for latex (`L`) and HTML (`H`) specs.
.. note::
- The abbreviated unit is drawn from the unit registry where the 3rd item in the
- equivalence chain (ie 1 = 2 = **3**) will be returned when the prefix '~' is
+ The abbreviated unit is drawn from the unit registry where the 3rd item in the
+ equivalence chain (ie 1 = 2 = **3**) will be returned when the prefix '~' is
used. The 1st item in the chain is the canonical name of the unit.
-The formatting specs (ie 'L', 'H', 'P') can be used with Python string 'formatting
+The formatting specs (ie 'L', 'H', 'P') can be used with Python string 'formatting
syntax'_ for custom float representations. For example, scientific notation:
..doctest::
@@ -387,10 +419,27 @@ Finally, if Babel_ is installed you can translate unit names to any language
>>> accel.format_babel(locale='fr_FR')
'1.3 mètre par seconde²'
-You can also specify the format locale at u
+You can also specify the format locale at the registry level either at creation:
>>> ureg = UnitRegistry(fmt_locale='fr_FR')
+or later:
+
+.. doctest::
+
+ >>> ureg.set_fmt_locale('fr_FR')
+
+and by doing that, string formatting is now localized:
+
+.. doctest::
+
+ >>> str(accel)
+ '1.3 mètre par seconde²'
+ >>> "%s" % accel
+ '1.3 mètre par seconde²'
+ >>> "{}".format(accel)
+ '1.3 mètre par seconde²'
+
Using Pint in your projects
---------------------------
@@ -438,4 +487,4 @@ also define the registry as the application registry::
.. _`serious security problems`: http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
.. _`Babel`: http://babel.pocoo.org/
.. _'formatting syntax': https://docs.python.org/3/library/string.html#format-specification-mini-language
-.. _'f-strings': https://www.python.org/dev/peps/pep-0498/ \ No newline at end of file
+.. _'f-strings': https://www.python.org/dev/peps/pep-0498/