Skip to content
Snippets Groups Projects
Commit feb41533 authored by Vanessa Stehr's avatar Vanessa Stehr
Browse files

Add option to add wrappers and pre-/suffixes to latex

parent 541ac218
No related branches found
No related tags found
No related merge requests found
Pipeline #27426 passed
...@@ -8,4 +8,9 @@ Create a D-SI tree with the D-SI unit string as an argument: `tree = dsiParser.d ...@@ -8,4 +8,9 @@ Create a D-SI tree with the D-SI unit string as an argument: `tree = dsiParser.d
- To validate the D-SI unit string, inspect the `valid` property: `print(tree.valid)` - To validate the D-SI unit string, inspect the `valid` property: `print(tree.valid)`
- To see any warning messages generated while parsing the string, inspect the `warnings` property: `print(tree.warnings)` - To see any warning messages generated while parsing the string, inspect the `warnings` property: `print(tree.warnings)`
- To generate the corresponding LaTeX code, call the `toLatex` function: `latexString = tree.toLatex()` - To generate the corresponding LaTeX code, call the `toLatex` function: `latexString = tree.toLatex()`
\ No newline at end of file - Optional arguments for the `toLatex` function:
- `wrapper`: appears at the beginning and end of the string. Defaults to "$$".
- `prefix`: appears et the beginning of the string, after the wrapper. Defaults to "".
- `suffix`: appears at the end of the string, before the wrapper. Defaults to "".
- If the string would only consist of the wrappers, an empty string is returned instead.
\ No newline at end of file
[metadata] [metadata]
name = dsiParser name = dsiParser
version = 0.1.0 version = 0.2.0
description = Parse D-SI unit strings to LaTeX description = Parse D-SI unit strings to LaTeX
long_description = file: README.md long_description = file: README.md
......
...@@ -14,19 +14,27 @@ class dsiTree: ...@@ -14,19 +14,27 @@ class dsiTree:
(self.tree, self.warnings) = _parseDsi(dsiString) (self.tree, self.warnings) = _parseDsi(dsiString)
self.valid = len(self.warnings) == 0 self.valid = len(self.warnings) == 0
def toLatex(self): def toLatex(self, wrapper='$$', prefix='', suffix=''):
"""converts D-SI unit string to LaTeX """converts D-SI unit string to LaTeX
Args:
wrapper (str, optional): String to be added both in the beginning and the end of the LaTeX string. Defaults to '$$'.
prefix (str, optional): String to be added in the beginning of the LaTeX string, after the wrapper. Defaults to ''.
suffix (str, optional): String to be added in the end of the LaTeX string, before the wrapper. Defaults to ''.
Returns: Returns:
str: the corresponding LaTeX code str: the corresponding LaTeX code
""" """
if self.tree == []: if self.tree == []:
return "" if len(prefix)+len(suffix) > 0:
return wrapper+prefix+suffix+wrapper
else:
return ""
latexArray = [] latexArray = []
if len(self.tree) == 1: # no fractions if len(self.tree) == 1: # no fractions
for node in self.tree[0]: for node in self.tree[0]:
latexArray.append(node.toLatex()) latexArray.append(node.toLatex())
return '$'+r'\,'.join(latexArray)+'$' latexString = r'\,'.join(latexArray)
elif len(self.tree) == 2: # one fraction elif len(self.tree) == 2: # one fraction
latexString = "" latexString = ""
latexString += r'\frac' latexString += r'\frac'
...@@ -37,7 +45,6 @@ class dsiTree: ...@@ -37,7 +45,6 @@ class dsiTree:
nodeArray.append(node.toLatex()) nodeArray.append(node.toLatex())
latexString += r'\,'.join(nodeArray) latexString += r'\,'.join(nodeArray)
latexString += r'}' latexString += r'}'
return '$'+latexString+'$'
else: # more than one fraction else: # more than one fraction
latexString = "" latexString = ""
for i in range(len(self.tree)): for i in range(len(self.tree)):
...@@ -47,7 +54,7 @@ class dsiTree: ...@@ -47,7 +54,7 @@ class dsiTree:
for node in self.tree[i]: for node in self.tree[i]:
nodeArray.append(node.toLatex()) nodeArray.append(node.toLatex())
latexString += r'\,'.join(nodeArray) latexString += r'\,'.join(nodeArray)
return '$'+latexString+'$' return wrapper+prefix+latexString+suffix+wrapper
@dataclass @dataclass
class _node: class _node:
......
...@@ -5,13 +5,13 @@ def test_baseCase(): ...@@ -5,13 +5,13 @@ def test_baseCase():
# Most basic case: one unit without prefix or exponent # Most basic case: one unit without prefix or exponent
tree = dsiTree(r'\metre') tree = dsiTree(r'\metre')
assert tree.tree == [[_node('','metre','')]] assert tree.tree == [[_node('','metre','')]]
assert tree.toLatex() == r'$\mathrm{m}$' assert tree.toLatex() == r'$$\mathrm{m}$$'
assert tree.valid assert tree.valid
assert tree.warnings == [] assert tree.warnings == []
# One longer unit # One longer unit
tree = dsiTree(r'\milli\metre\tothe{0.5}\kilogram\per\mega\second\tothe{3}\ampere\tothe{-2}') tree = dsiTree(r'\milli\metre\tothe{0.5}\kilogram\per\mega\second\tothe{3}\ampere\tothe{-2}')
assert tree.toLatex() == r'$\frac{\sqrt{\mathrm{m}\mathrm{m}}\,\mathrm{kg}}{\mathrm{M}\mathrm{s}^{3}\,\mathrm{A}^{-2}}$' assert tree.toLatex() == r'$$\frac{\sqrt{\mathrm{m}\mathrm{m}}\,\mathrm{kg}}{\mathrm{M}\mathrm{s}^{3}\,\mathrm{A}^{-2}}$$'
assert tree.valid assert tree.valid
assert tree.warnings == [] assert tree.warnings == []
...@@ -20,7 +20,7 @@ def test_robustness(): ...@@ -20,7 +20,7 @@ def test_robustness():
# Unknown unit # Unknown unit
with pytest.warns(RuntimeWarning, match='The identifier \"foo\" does not match any D-SI units!'): with pytest.warns(RuntimeWarning, match='The identifier \"foo\" does not match any D-SI units!'):
tree = dsiTree(r'\foo') tree = dsiTree(r'\foo')
assert tree.toLatex() == r'${\color{red}\mathrm{foo}}$' assert tree.toLatex() == r'$${\color{red}\mathrm{foo}}$$'
assert not tree.valid assert not tree.valid
assert len(tree.warnings) == 1 assert len(tree.warnings) == 1
assert tree.warnings == ['The identifier \"foo\" does not match any D-SI units!'] assert tree.warnings == ['The identifier \"foo\" does not match any D-SI units!']
...@@ -29,7 +29,7 @@ def test_robustness(): ...@@ -29,7 +29,7 @@ def test_robustness():
with pytest.warns(RuntimeWarning, match='The identifier \"mini\" does not match any D-SI units!'): with pytest.warns(RuntimeWarning, match='The identifier \"mini\" does not match any D-SI units!'):
tree = dsiTree(r'\kilo\metre\per\mini\second') tree = dsiTree(r'\kilo\metre\per\mini\second')
print(tree.toLatex()) print(tree.toLatex())
assert tree.toLatex() == r'$\frac{\mathrm{k}\mathrm{m}}{{\color{red}\mathrm{mini}}\,\mathrm{s}}$' assert tree.toLatex() == r'$$\frac{\mathrm{k}\mathrm{m}}{{\color{red}\mathrm{mini}}\,\mathrm{s}}$$'
assert not tree.valid assert not tree.valid
assert len(tree.warnings) == 1 assert len(tree.warnings) == 1
assert tree.warnings == ['The identifier \"mini\" does not match any D-SI units!'] assert tree.warnings == ['The identifier \"mini\" does not match any D-SI units!']
...@@ -38,7 +38,7 @@ def test_robustness(): ...@@ -38,7 +38,7 @@ def test_robustness():
with pytest.warns(RuntimeWarning, match=r'This D-SI unit seems to be missing the base unit! \"\\milli\\tothe\{2\}\"'): with pytest.warns(RuntimeWarning, match=r'This D-SI unit seems to be missing the base unit! \"\\milli\\tothe\{2\}\"'):
tree = dsiTree(r'\milli\tothe{2}') tree = dsiTree(r'\milli\tothe{2}')
print(tree.toLatex()) print(tree.toLatex())
assert tree.toLatex() == r'${\color{red}\mathrm{m}{\color{red}\mathrm{}}^{2}}$' assert tree.toLatex() == r'$${\color{red}\mathrm{m}{\color{red}\mathrm{}}^{2}}$$'
assert not tree.valid assert not tree.valid
assert len(tree.warnings) == 1 assert len(tree.warnings) == 1
assert tree.warnings == ['This D-SI unit seems to be missing the base unit! \"\\milli\\tothe{2}\"'] assert tree.warnings == ['This D-SI unit seems to be missing the base unit! \"\\milli\\tothe{2}\"']
...@@ -48,42 +48,41 @@ def test_power(): ...@@ -48,42 +48,41 @@ def test_power():
# power # power
powerTree = dsiTree(r'\metre\tothe{2}') powerTree = dsiTree(r'\metre\tothe{2}')
assert powerTree.tree == [[_node('','metre','2')]] assert powerTree.tree == [[_node('','metre','2')]]
assert powerTree.toLatex() == r'$\mathrm{m}^{2}$' assert powerTree.toLatex() == r'$$\mathrm{m}^{2}$$'
assert powerTree.valid assert powerTree.valid
assert powerTree.warnings == [] assert powerTree.warnings == []
assert dsiTree(r'\metre\tothe{0.5}').toLatex() == r'$\sqrt{\mathrm{m}}$' assert dsiTree(r'\metre\tothe{0.5}').toLatex() == r'$$\sqrt{\mathrm{m}}$$'
assert dsiTree(r'\metre\tothe{-2}').toLatex() == r'$\mathrm{m}^{-2}$' assert dsiTree(r'\metre\tothe{-2}').toLatex() == r'$$\mathrm{m}^{-2}$$'
assert dsiTree(r'\metre\tothe{1337}').toLatex() == r'$\mathrm{m}^{1337}$' assert dsiTree(r'\metre\tothe{1337}').toLatex() == r'$$\mathrm{m}^{1337}$$'
# Non-numerical power # Non-numerical power
with pytest.warns(RuntimeWarning, match='The exponent \"foo\" is not a number!'): with pytest.warns(RuntimeWarning, match='The exponent \"foo\" is not a number!'):
assert dsiTree(r'\metre\tothe{foo}').toLatex() == r'$\mathrm{m}^{{\color{red}\mathrm{foo}}}$' assert dsiTree(r'\metre\tothe{foo}').toLatex() == r'$$\mathrm{m}^{{\color{red}\mathrm{foo}}}$$'
def test_prefix(): def test_prefix():
# prefix # prefix
prefixTree = dsiTree(r'\kilo\metre') prefixTree = dsiTree(r'\kilo\metre')
assert prefixTree.tree == [[_node('kilo','metre','')]] assert prefixTree.tree == [[_node('kilo','metre','')]]
assert prefixTree.toLatex() == r'$\mathrm{k}\mathrm{m}$' assert prefixTree.toLatex() == r'$$\mathrm{k}\mathrm{m}$$'
assert prefixTree.valid assert prefixTree.valid
def test_node(): def test_node():
# full node # full node
fullNodeTree = dsiTree(r'\kilo\metre\tothe{2}') fullNodeTree = dsiTree(r'\kilo\metre\tothe{2}')
assert fullNodeTree.tree == [[_node('kilo','metre','2')]] assert fullNodeTree.tree == [[_node('kilo','metre','2')]]
assert fullNodeTree.toLatex() == r'$\mathrm{k}\mathrm{m}^{2}$' assert fullNodeTree.toLatex() == r'$$\mathrm{k}\mathrm{m}^{2}$$'
assert fullNodeTree.valid assert fullNodeTree.valid
def test_fraction(): def test_fraction():
fractionTree = dsiTree(r'\mega\metre\per\second\tothe{2}') fractionTree = dsiTree(r'\mega\metre\per\second\tothe{2}')
assert fractionTree.tree == [[_node('mega','metre','')],[_node('','second','2')]] assert fractionTree.tree == [[_node('mega','metre','')],[_node('','second','2')]]
assert fractionTree.toLatex() == r'$\frac{\mathrm{M}\mathrm{m}}{\mathrm{s}^{2}}$' assert fractionTree.toLatex() == r'$$\frac{\mathrm{M}\mathrm{m}}{\mathrm{s}^{2}}$$'
assert fractionTree.valid assert fractionTree.valid
# double fraction # double fraction
with pytest.warns(RuntimeWarning, match=r'The dsi string contains more than one \\per, does not match specs! Given string: \\metre\\per\\metre\\per\\metre'): with pytest.warns(RuntimeWarning, match=r'The dsi string contains more than one \\per, does not match specs! Given string: \\metre\\per\\metre\\per\\metre'):
tree = dsiTree(r'\metre\per\metre\per\metre') tree = dsiTree(r'\metre\per\metre\per\metre')
print(tree.toLatex()) assert tree.toLatex() == r'$$\mathrm{m}{\color{red}/}\mathrm{m}{\color{red}/}\mathrm{m}$$'
assert tree.toLatex() == r'$\mathrm{m}{\color{red}/}\mathrm{m}{\color{red}/}\mathrm{m}$'
assert not tree.valid assert not tree.valid
assert len(tree.warnings) == 1 assert len(tree.warnings) == 1
assert tree.warnings == [r'The dsi string contains more than one \per, does not match specs! Given string: \metre\per\metre\per\metre'] assert tree.warnings == [r'The dsi string contains more than one \per, does not match specs! Given string: \metre\per\metre\per\metre']
...@@ -91,3 +90,7 @@ def test_fraction(): ...@@ -91,3 +90,7 @@ def test_fraction():
def test_empty(): def test_empty():
with pytest.warns(RuntimeWarning, match='Given D-SI string is empty!'): with pytest.warns(RuntimeWarning, match='Given D-SI string is empty!'):
assert dsiTree('').toLatex() == '' assert dsiTree('').toLatex() == ''
def test_wrappers():
assert dsiTree(r'\metre').toLatex(wrapper='') == r'\mathrm{m}'
assert dsiTree(r'\metre').toLatex(wrapper='$',prefix=r'\mathrm{Unit: }',suffix=r'\mathrm{(generated from D-SI string)}') == r'$\mathrm{Unit: }\mathrm{m}\mathrm{(generated from D-SI string)}$'
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment