Skip to content

Commit cfeacef

Browse files
committed
Merge branch 'master' of github.com:lebigot/uncertainties
2 parents 143baa9 + 1c8678d commit cfeacef

File tree

8 files changed

+105
-48
lines changed

8 files changed

+105
-48
lines changed

README.rst

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,17 @@
11
uncertainties
22
=============
33

4-
.. image:: https://readthedocs.org/projects/uncertainties-python-package/badge/?version=latest
5-
:target: http://uncertainties-python-package.readthedocs.io/en/latest/?badge=latest
4+
.. image:: https://readthedocs.org/projects/uncertainties/badge/?version=latest
5+
:target: https://uncertainties.readthedocs.io/en/latest/?badge=latest
6+
:alt: Documentation Status
67
.. image:: https://img.shields.io/pypi/v/uncertainties.svg
78
:target: https://pypi.org/project/uncertainties/
89
.. image:: https://pepy.tech/badge/uncertainties/week
9-
:target: https://pepy.tech/badge/uncertainties/week
10+
:target: https://pepy.tech/project/uncertainties
1011
.. image:: https://codecov.io/gh/lebigot/uncertainties/branch/master/graph/badge.svg
1112
:target: https://codecov.io/gh/lebigot/uncertainties/
12-
.. image:: https://travis-ci.org/lebigot/uncertainties.svg?branch=master
13-
:target: https://travis-ci.org/lebigot/uncertainties
13+
.. image:: https://travis-ci.com/lebigot/uncertainties.svg?branch=master
14+
:target: https://travis-ci.com/lebigot/uncertainties
1415
.. image:: https://ci.appveyor.com/api/projects/status/j5238244myqx0a0r?svg=true
1516
:target: https://ci.appveyor.com/project/lebigot/uncertainties
1617

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

29-
This package also automatically calculates derivatives:
30+
This package also **automatically calculates derivatives of arbitrary functions**:
3031

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

3435
The main documentation is available at
35-
http://uncertainties-python-package.readthedocs.io/.
36+
https://uncertainties.readthedocs.io/.
3637

3738
Git branches
3839
------------

doc/conf.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -194,8 +194,11 @@
194194
# Additional stuff for the LaTeX preamble.
195195
#latex_preamble = r'\DeclareUnicodeCharacter{207B}{$^-$}'
196196
latex_elements = {
197-
# Superscript -, for pdflatex (unnecessary, with xelatex):
198-
'preamble': r'\DeclareUnicodeCharacter{207B}{$^-$}'
197+
# Superscript -, etc. for pdflatex (unnecessary, with xelatex):
198+
'preamble': r'''
199+
\DeclareUnicodeCharacter{207B}{$^-$}
200+
\DeclareUnicodeCharacter{22C5}{$\cdot$}
201+
'''
199202
}
200203

201204
# Documents to append as an appendix to all manuals.

doc/index.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -416,7 +416,7 @@ License
416416
This software is released under a **dual license**; one of the
417417
following options can be chosen:
418418

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

doc/user_guide.rst

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,10 @@ completely **transparently**.
167167
Access to the uncertainty and to the nominal value
168168
==================================================
169169

170+
.. index::
171+
pair: nominal value; scalar
172+
pair: uncertainty; scalar
173+
170174
The nominal value and the uncertainty (standard deviation) can also be
171175
accessed independently:
172176

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

590594

591-
.. index::
592-
pair: nominal value; scalar
593-
pair: uncertainty; scalar
595+
Customizing the pretty-print and LaTeX outputs
596+
----------------------------------------------
597+
598+
The pretty print and LaTeX outputs themselves can be customized.
599+
600+
For example, the pretty-print representation of numbers with uncertainty can
601+
display multiplication with a centered dot (⋅) instead of the default symbol
602+
(×), like in ``(2.00±0.10)⋅10⁻¹``; this is easily done through the global
603+
setting ``uncertainties.core.MULT_SYMBOLS["pretty-print"] = "⋅"``.
604+
605+
Beyond this multiplication symbol, the "±" symbol, the parentheses and the
606+
exponent representations can also be customized globally. The details can be
607+
found in the documentation of :func:`uncertainties.core.format_num`.
594608

595609
Making custom functions accept numbers with uncertainties
596610
=========================================================
@@ -609,8 +623,11 @@ works with numbers with uncertainties:
609623

610624
>>> wrapped_f = uncertainties.wrap(f)
611625

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

setup.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
# Common options for distutils/setuptools's setup():
2121
setup_options = dict(
2222
name='uncertainties',
23-
version='3.1.5',
23+
version='3.1.7',
2424
author='Eric O. LEBIGOT (EOL)',
2525
author_email='[email protected]',
2626
url='http://uncertainties-python-package.readthedocs.io/',
@@ -131,7 +131,8 @@
131131
132132
Main changes:
133133
134-
- 3.1.5: added a "p" formatting option, that makes sure that there are always
134+
- 3.1.6: The pretty-print and LaTeX format can now be customized.
135+
- 3.1.5: Added a "p" formatting option, that makes sure that there are always
135136
parentheses around the … ± … part of printed numbers.
136137
- 3.1.4: Python 2.7+ is now required.
137138
- 3.1.2: Fix for NumPy 1.17 and ``unumpy.ulinalg.pinv()``.

uncertainties/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@
226226
from .core import __all__ # For a correct help(uncertainties)
227227

228228
# Numerical version:
229-
__version_info__ = (3, 1, 5)
229+
__version_info__ = (3, 1, 6)
230230
__version__ = '.'.join(map(str, __version_info__))
231231

232232
__author__ = 'Eric O. LEBIGOT (EOL) <[email protected]>'

uncertainties/core.py

Lines changed: 42 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,19 @@
1414

1515
from __future__ import division # Many analytical derivatives depend on this
1616

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

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

1024-
# Function that transforms an exponent produced by format_num() into
1026+
PM_SYMBOLS = {'pretty-print': u'±', 'latex': r' \pm ', 'default': '+/-'}
1027+
1028+
# Multiplication symbol for pretty printing (so that pretty printing can
1029+
# be customized):
1030+
MULT_SYMBOLS = {'pretty-print': u'×', 'latex': r'\times'}
1031+
1032+
# Function that transforms a numerical exponent produced by format_num() into
10251033
# the corresponding string notation (for non-default modes):
10261034
EXP_PRINT = {
1027-
'pretty-print': lambda common_exp: u'×10%s' % to_superscript(common_exp),
1028-
'latex': lambda common_exp: r' \times 10^{%d}' % common_exp}
1035+
'pretty-print': lambda common_exp: u'%s10%s' % (
1036+
MULT_SYMBOLS['pretty-print'], to_superscript(common_exp)),
1037+
'latex': lambda common_exp: r' %s 10^{%d}' % (
1038+
MULT_SYMBOLS['latex'], common_exp)}
10291039

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

10421052
def format_num(nom_val_main, error_main, common_exp,
10431053
fmt_parts, prec, main_pres_type, options):
1044-
r'''
1054+
u'''
10451055
Return a formatted number with uncertainty.
10461056
10471057
Null errors (error_main) are displayed as the integer 0, with
10481058
no decimal point.
10491059
1050-
The formatting can be partially customized globally. The EXP_PRINT
1051-
maps non-default modes ("latex", "pretty-print") to a function
1052-
that transforms a common exponent into a string (of the form
1053-
"times 10 to the power <exponent>", where "times" can be
1054-
represented, e.g., as a centered dot instead of the multiplication
1055-
symbol). The GROUP_SYMBOLS mapping maps each of these modes to the
1056-
pair of strings used for grouping expressions (typically
1057-
parentheses, which can be for instance replaced by "\left(" and
1058-
"\right(" in LaTeX so as to create a non-breakable group).
1060+
The formatting can be customized globally through the PM_SYMBOLS,
1061+
MULT_SYMBOLS, GROUP_SYMBOLS and EXP_PRINT dictionaries, which contain
1062+
respectively the symbol for ±, for multiplication, for parentheses, and a
1063+
function that maps an exponent to something like "×10²" (using
1064+
MULT_SYMBOLS).
1065+
1066+
Each of these dictionary has (at least) a 'pretty-print' and a 'latex' key,
1067+
that define the symbols to be used for these two output formats (the
1068+
PM_SYMBOLS and GROUP_SYMBOLS also have a 'default' key for the default
1069+
output format). For example, the defaults for the 'pretty-print' format
1070+
are:
1071+
1072+
- PM_SYMBOLS['pretty-print'] = '±'
1073+
- MULT_SYMBOLS['pretty-print'] = '×'
1074+
- GROUP_SYMBOLS['pretty-print'] = ( '(', ')' )
1075+
- EXP_PRINT['pretty-print']: see the source code.
1076+
1077+
Arguments:
10591078
10601079
nom_val_main, error_main -- nominal value and error, before using
10611080
common_exp (e.g., "1.23e2" would have a main value of 1.23;
@@ -1418,14 +1437,7 @@ def format_num(nom_val_main, error_main, common_exp,
14181437
fmt_parts['width'])
14191438

14201439
####################
1421-
if 'P' in options:
1422-
# Unicode has priority over LaTeX, so that users with a
1423-
# Unicode-compatible LaTeX source can use ±:
1424-
pm_symbol = u'±'
1425-
elif 'L' in options:
1426-
pm_symbol = r' \pm '
1427-
else:
1428-
pm_symbol = '+/-'
1440+
pm_symbol = PM_SYMBOLS[print_type] # Shortcut
14291441

14301442
####################
14311443

uncertainties/test_uncertainties.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2131,6 +2131,29 @@ def test_unicode_format():
21312131
assert isinstance(u'Résultat = %s' % x.format(''), str)
21322132
assert isinstance(u'Résultat = %s' % x.format('P'), str)
21332133

2134+
def test_custom_pretty_print_and_latex():
2135+
'''Test of the pretty-print and LaTeX format customizations'''
2136+
2137+
x = ufloat(2, 0.1)*1e-11
2138+
2139+
# We will later restore the defaults:
2140+
PREV_CUSTOMIZATIONS = {
2141+
var: getattr(uncert_core, var).copy()
2142+
for var in ['PM_SYMBOLS', 'MULT_SYMBOLS', 'GROUP_SYMBOLS']}
2143+
2144+
# Customizations:
2145+
for format in ["pretty-print", "latex"]:
2146+
uncert_core.PM_SYMBOLS[format] = u" ± "
2147+
uncert_core.MULT_SYMBOLS[format] = u"⋅"
2148+
uncert_core.GROUP_SYMBOLS[format] = ( "[", "]" )
2149+
2150+
assert u"{:P}".format(x) == u'[2.00 ± 0.10]⋅10⁻¹¹'
2151+
assert u"{:L}".format(x) == u'[2.00 ± 0.10] ⋅ 10^{-11}'
2152+
2153+
# We restore the defaults:
2154+
for (var, setting) in PREV_CUSTOMIZATIONS.items():
2155+
setattr(uncert_core, var, setting)
2156+
21342157
###############################################################################
21352158

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

0 commit comments

Comments
 (0)