Skip to content

Commit

Permalink
Merge branch 'master' of github.com:lebigot/uncertainties
Browse files Browse the repository at this point in the history
  • Loading branch information
lebigot committed Jun 19, 2022
2 parents 143baa9 + 1c8678d commit cfeacef
Show file tree
Hide file tree
Showing 8 changed files with 105 additions and 48 deletions.
15 changes: 8 additions & 7 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
uncertainties
=============

.. image:: https://readthedocs.org/projects/uncertainties-python-package/badge/?version=latest
:target: http://uncertainties-python-package.readthedocs.io/en/latest/?badge=latest
.. image:: https://readthedocs.org/projects/uncertainties/badge/?version=latest
:target: https://uncertainties.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
.. image:: https://img.shields.io/pypi/v/uncertainties.svg
:target: https://pypi.org/project/uncertainties/
.. image:: https://pepy.tech/badge/uncertainties/week
:target: https://pepy.tech/badge/uncertainties/week
:target: https://pepy.tech/project/uncertainties
.. image:: https://codecov.io/gh/lebigot/uncertainties/branch/master/graph/badge.svg
:target: https://codecov.io/gh/lebigot/uncertainties/
.. image:: https://travis-ci.org/lebigot/uncertainties.svg?branch=master
:target: https://travis-ci.org/lebigot/uncertainties
.. image:: https://travis-ci.com/lebigot/uncertainties.svg?branch=master
:target: https://travis-ci.com/lebigot/uncertainties
.. image:: https://ci.appveyor.com/api/projects/status/j5238244myqx0a0r?svg=true
:target: https://ci.appveyor.com/project/lebigot/uncertainties

Expand All @@ -26,13 +27,13 @@ calculations with uncertainties** (aka "error propagation"):
>>> sin(2*x) # In a Python shell, "print" is optional
0.9092974268256817+/-0.08322936730942848

This package also automatically calculates derivatives:
This package also **automatically calculates derivatives of arbitrary functions**:

>>> (2*x+1000).derivatives[x]
2.0

The main documentation is available at
http://uncertainties-python-package.readthedocs.io/.
https://uncertainties.readthedocs.io/.

Git branches
------------
Expand Down
7 changes: 5 additions & 2 deletions doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,8 +194,11 @@
# Additional stuff for the LaTeX preamble.
#latex_preamble = r'\DeclareUnicodeCharacter{207B}{$^-$}'
latex_elements = {
# Superscript -, for pdflatex (unnecessary, with xelatex):
'preamble': r'\DeclareUnicodeCharacter{207B}{$^-$}'
# Superscript -, etc. for pdflatex (unnecessary, with xelatex):
'preamble': r'''
\DeclareUnicodeCharacter{207B}{$^-$}
\DeclareUnicodeCharacter{22C5}{$\cdot$}
'''
}

# Documents to append as an appendix to all manuals.
Expand Down
2 changes: 1 addition & 1 deletion doc/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ License
This software is released under a **dual license**; one of the
following options can be chosen:

1. The `Revised BSD License`_ (© 2010–2019, Eric O. LEBIGOT [EOL]).
1. The `Revised BSD License`_ (© 2010–2021, Eric O. LEBIGOT [EOL]).
2. Any other license, as long as it is obtained from the creator of
this package.

Expand Down
27 changes: 22 additions & 5 deletions doc/user_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,10 @@ completely **transparently**.
Access to the uncertainty and to the nominal value
==================================================

.. index::
pair: nominal value; scalar
pair: uncertainty; scalar

The nominal value and the uncertainty (standard deviation) can also be
accessed independently:

Expand Down Expand Up @@ -588,9 +592,19 @@ use the shorthand notation for numbers with uncertainties:
prints with the shorthand notation: ``Result = 0.20(1)``.


.. index::
pair: nominal value; scalar
pair: uncertainty; scalar
Customizing the pretty-print and LaTeX outputs
----------------------------------------------

The pretty print and LaTeX outputs themselves can be customized.

For example, the pretty-print representation of numbers with uncertainty can
display multiplication with a centered dot (⋅) instead of the default symbol
(×), like in ``(2.00±0.10)⋅10⁻¹``; this is easily done through the global
setting ``uncertainties.core.MULT_SYMBOLS["pretty-print"] = "⋅"``.

Beyond this multiplication symbol, the "±" symbol, the parentheses and the
exponent representations can also be customized globally. The details can be
found in the documentation of :func:`uncertainties.core.format_num`.

Making custom functions accept numbers with uncertainties
=========================================================
Expand All @@ -609,8 +623,11 @@ works with numbers with uncertainties:

>>> wrapped_f = uncertainties.wrap(f)

The new function :func:`wrapped_f` *accepts numbers with uncertainties*
as arguments *wherever a Python float is used* for :func:`f`.
The new function :func:`wrapped_f` (optionally) *accepts a number
with uncertainty* in place of any float *argument* of :func:`f` (note
that floats contained instead *inside* arguments of :func:`f`, like
in a list or a NumPy array, *cannot* be replaced by numbers with
uncertainties).
:func:`wrapped_f` returns the same values as :func:`f`, but with
uncertainties.

Expand Down
5 changes: 3 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
# Common options for distutils/setuptools's setup():
setup_options = dict(
name='uncertainties',
version='3.1.5',
version='3.1.7',
author='Eric O. LEBIGOT (EOL)',
author_email='[email protected]',
url='http://uncertainties-python-package.readthedocs.io/',
Expand Down Expand Up @@ -131,7 +131,8 @@
Main changes:
- 3.1.5: added a "p" formatting option, that makes sure that there are always
- 3.1.6: The pretty-print and LaTeX format can now be customized.
- 3.1.5: Added a "p" formatting option, that makes sure that there are always
parentheses around the … ± … part of printed numbers.
- 3.1.4: Python 2.7+ is now required.
- 3.1.2: Fix for NumPy 1.17 and ``unumpy.ulinalg.pinv()``.
Expand Down
2 changes: 1 addition & 1 deletion uncertainties/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@
from .core import __all__ # For a correct help(uncertainties)

# Numerical version:
__version_info__ = (3, 1, 5)
__version_info__ = (3, 1, 6)
__version__ = '.'.join(map(str, __version_info__))

__author__ = 'Eric O. LEBIGOT (EOL) <[email protected]>'
72 changes: 42 additions & 30 deletions uncertainties/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,19 @@

from __future__ import division # Many analytical derivatives depend on this

from builtins import str
from builtins import next
from builtins import map
from builtins import zip
from builtins import range
from past.builtins import basestring
from builtins import object
import sys
import re
from builtins import str, next, map, zip, range, object
import math
from math import sqrt, log, isnan, isinf # Optimization: no attribute look-up
import re
import sys
if sys.version_info < (3,):
from past.builtins import basestring
else:
# Avoid importing from past in Python 3 since it utilizes the builtin
# 'imp' module, which is deprecated as of Python 3.4, see
# https://docs.python.org/3/library/imp.html. The 2to3 tool replaces
# basestring with str, so that's what we effectively do here as well:
basestring = str

try:
from math import isinfinite # !! Python 3.2+
Expand Down Expand Up @@ -1021,11 +1023,19 @@ def nrmlze_superscript(number_str):
# a subclass of unicode, in Python 2):
return int(str(number_str).translate(FROM_SUPERSCRIPT))

# Function that transforms an exponent produced by format_num() into
PM_SYMBOLS = {'pretty-print': u'±', 'latex': r' \pm ', 'default': '+/-'}

# Multiplication symbol for pretty printing (so that pretty printing can
# be customized):
MULT_SYMBOLS = {'pretty-print': u'×', 'latex': r'\times'}

# Function that transforms a numerical exponent produced by format_num() into
# the corresponding string notation (for non-default modes):
EXP_PRINT = {
'pretty-print': lambda common_exp: u'×10%s' % to_superscript(common_exp),
'latex': lambda common_exp: r' \times 10^{%d}' % common_exp}
'pretty-print': lambda common_exp: u'%s10%s' % (
MULT_SYMBOLS['pretty-print'], to_superscript(common_exp)),
'latex': lambda common_exp: r' %s 10^{%d}' % (
MULT_SYMBOLS['latex'], common_exp)}

# Symbols used for grouping (typically between parentheses) in format_num():
GROUP_SYMBOLS = {
Expand All @@ -1041,21 +1051,30 @@ def nrmlze_superscript(number_str):

def format_num(nom_val_main, error_main, common_exp,
fmt_parts, prec, main_pres_type, options):
r'''
u'''
Return a formatted number with uncertainty.
Null errors (error_main) are displayed as the integer 0, with
no decimal point.
The formatting can be partially customized globally. The EXP_PRINT
maps non-default modes ("latex", "pretty-print") to a function
that transforms a common exponent into a string (of the form
"times 10 to the power <exponent>", where "times" can be
represented, e.g., as a centered dot instead of the multiplication
symbol). The GROUP_SYMBOLS mapping maps each of these modes to the
pair of strings used for grouping expressions (typically
parentheses, which can be for instance replaced by "\left(" and
"\right(" in LaTeX so as to create a non-breakable group).
The formatting can be customized globally through the PM_SYMBOLS,
MULT_SYMBOLS, GROUP_SYMBOLS and EXP_PRINT dictionaries, which contain
respectively the symbol for ±, for multiplication, for parentheses, and a
function that maps an exponent to something like "×10²" (using
MULT_SYMBOLS).
Each of these dictionary has (at least) a 'pretty-print' and a 'latex' key,
that define the symbols to be used for these two output formats (the
PM_SYMBOLS and GROUP_SYMBOLS also have a 'default' key for the default
output format). For example, the defaults for the 'pretty-print' format
are:
- PM_SYMBOLS['pretty-print'] = '±'
- MULT_SYMBOLS['pretty-print'] = '×'
- GROUP_SYMBOLS['pretty-print'] = ( '(', ')' )
- EXP_PRINT['pretty-print']: see the source code.
Arguments:
nom_val_main, error_main -- nominal value and error, before using
common_exp (e.g., "1.23e2" would have a main value of 1.23;
Expand Down Expand Up @@ -1418,14 +1437,7 @@ def format_num(nom_val_main, error_main, common_exp,
fmt_parts['width'])

####################
if 'P' in options:
# Unicode has priority over LaTeX, so that users with a
# Unicode-compatible LaTeX source can use ±:
pm_symbol = u'±'
elif 'L' in options:
pm_symbol = r' \pm '
else:
pm_symbol = '+/-'
pm_symbol = PM_SYMBOLS[print_type] # Shortcut

####################

Expand Down
23 changes: 23 additions & 0 deletions uncertainties/test_uncertainties.py
Original file line number Diff line number Diff line change
Expand Up @@ -2131,6 +2131,29 @@ def test_unicode_format():
assert isinstance(u'Résultat = %s' % x.format(''), str)
assert isinstance(u'Résultat = %s' % x.format('P'), str)

def test_custom_pretty_print_and_latex():
'''Test of the pretty-print and LaTeX format customizations'''

x = ufloat(2, 0.1)*1e-11

# We will later restore the defaults:
PREV_CUSTOMIZATIONS = {
var: getattr(uncert_core, var).copy()
for var in ['PM_SYMBOLS', 'MULT_SYMBOLS', 'GROUP_SYMBOLS']}

# Customizations:
for format in ["pretty-print", "latex"]:
uncert_core.PM_SYMBOLS[format] = u" ± "
uncert_core.MULT_SYMBOLS[format] = u"⋅"
uncert_core.GROUP_SYMBOLS[format] = ( "[", "]" )

assert u"{:P}".format(x) == u'[2.00 ± 0.10]⋅10⁻¹¹'
assert u"{:L}".format(x) == u'[2.00 ± 0.10] ⋅ 10^{-11}'

# We restore the defaults:
for (var, setting) in PREV_CUSTOMIZATIONS.items():
setattr(uncert_core, var, setting)

###############################################################################

# The tests below require NumPy, which is an optional package:
Expand Down

0 comments on commit cfeacef

Please sign in to comment.