Skip to content

Commit f9c43c2

Browse files
committed
latex formatting does not simplify the dimensionality by default. CompoundUnits are not expressed as latex fractions
1 parent 0e35ca0 commit f9c43c2

File tree

2 files changed

+18
-11
lines changed

2 files changed

+18
-11
lines changed

quantities/dimensionality.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def unicode(self):
5050

5151
@property
5252
def latex(self):
53-
return markup.format_units_latex(self.simplified,font='mathrm',mult=r'\cdot')
53+
return markup.format_units_latex(self)
5454

5555
def __hash__(self):
5656
res = hash(unit_registry['dimensionless'])

quantities/markup.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,7 @@ def format_units_unicode(udict):
8787
return res
8888

8989

90-
91-
def format_units_latex(ustr,font='mathrm',mult='',paren=True):
90+
def format_units_latex(udict,font='mathrm',mult=r'\cdot',paren=True):
9291
'''
9392
Replace the units string provided with an equivalent latex string.
9493
@@ -102,23 +101,31 @@ def format_units_latex(ustr,font='mathrm',mult='',paren=True):
102101
103102
Multiplication (*) are replaced with the symbol specified by the mult argument.
104103
By default this is a blank string (no multiplication symbol). Other useful
105-
options may be r'\cdot' or r'\*'
104+
options may be r'\cdot' or r'*'
106105
107106
If paren=True, encapsulate the string in '\left(' and '\right)'
108107
108+
The result of format_units_latex is encapsulated in $. This allows the result
109+
to be used directly in Latex in normal text mode, or in Matplotlib text via the
110+
MathText feature.
111+
109112
Restrictions:
110-
With ambiguous units (having more than one division symbol), this routine
111-
will likely produce undesirable results. It is recommended that you first
112-
simplify the dimensionality before running it through this function.
113+
This routine will not put CompoundUnits into a fractional form.
113114
'''
114-
res = format_units(ustr)
115-
# Replace division (num/den) with \frac{num}{den}
116-
res = re.sub(r'(?P<num>.+)/(?P<den>.+)','\\\\frac{\g<num>}{\g<den>}',res)
115+
res = format_units(udict)
116+
if res.startswith('(') and res.endswith(')'):
117+
# Compound Unit
118+
compound = True
119+
else:
120+
# Not a compound unit
121+
compound = False
122+
# Replace division (num/den) with \frac{num}{den}
123+
res = re.sub(r'(?P<num>.+)/(?P<den>.+)',r'\\frac{\g<num>}{\g<den>}',res)
117124
# Replace exponentiation (**exp) with ^{exp}
118125
res = re.sub(r'\*{2,2}(?P<exp>\d+)',r'^{\g<exp>}',res)
119126
# Remove multiplication signs
120127
res = re.sub(r'\*','{'+mult+'}',res)
121-
if paren:
128+
if paren and not compound:
122129
res = r'\left(%s\right)' % res
123130
res = r'$\%s{%s}$' % (font,res)
124131
return res

0 commit comments

Comments
 (0)