Skip to content

Commit 7139bb7

Browse files
authored
Merge pull request #23 from iterorganization/allow-scientific-notation
Allow for scientific notation
2 parents 4f2beaf + 0b6e027 commit 7139bb7

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

tests/test_yaml_parser.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,3 +91,30 @@ def assert_tendencies_correct(tendencies):
9191
assert tendencies[6].duration == approx(2)
9292
assert tendencies[6].from_ == approx(8)
9393
assert tendencies[6].to == approx(0)
94+
95+
96+
def test_scientific_notation():
97+
"""Test if scientific notation is parsed correctly."""
98+
waveforms = {
99+
"waveform:\n- {type: linear, to: 1.5e5}": 1.5e5,
100+
"waveform:\n- {type: linear, to: 1.5e+5}": 1.5e5,
101+
"waveform:\n- {type: linear, to: 1.5E+5}": 1.5e5,
102+
"waveform:\n- {type: linear, to: 1.5e-5}": 1.5e-5,
103+
"waveform:\n- {type: linear, to: 1.5E-5}": 1.5e-5,
104+
"waveform:\n- {type: linear, to: 1e5}": 1e5,
105+
"waveform:\n- {type: linear, to: 1e+5}": 1e5,
106+
"waveform:\n- {type: linear, to: 1E+5}": 1e5,
107+
"waveform:\n- {type: linear, to: 1e-5}": 1e-5,
108+
"waveform:\n- {type: linear, to: 1E-5}": 1e-5,
109+
"waveform:\n- {type: linear, to: 0e5}": 0.0,
110+
"waveform:\n- {type: linear, to: 0E0}": 0.0,
111+
"waveform:\n- {type: linear, to: -1.5e5}": -1.5e5,
112+
"waveform:\n- {type: linear, to: -1E+5}": -1e5,
113+
"waveform:\n- {type: linear, to: -1.5e-5}": -1.5e-5,
114+
}
115+
116+
yaml_parser = YamlParser()
117+
118+
for waveform, expected_value in waveforms.items():
119+
yaml_parser.parse_waveforms(waveform)
120+
assert yaml_parser.waveform.tendencies[0].to == expected_value

waveform_editor/yaml_parser.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import re
2+
13
import holoviews as hv
24
import yaml
35

@@ -48,7 +50,24 @@ def parse_waveforms(self, yaml_str):
4850
"""
4951
self.has_yaml_error = False
5052
try:
51-
waveform_yaml = yaml.load(yaml_str, Loader=LineNumberYamlLoader)
53+
loader = LineNumberYamlLoader
54+
# Parse scientific notation as a float, instead of a string. For
55+
# more information see: https://stackoverflow.com/a/30462009/8196245
56+
loader.add_implicit_resolver(
57+
"tag:yaml.org,2002:float",
58+
re.compile(
59+
"""^(?:
60+
[-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?
61+
|[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
62+
|\\.[0-9_]+(?:[eE][-+][0-9]+)?
63+
|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*
64+
|[-+]?\\.(?:inf|Inf|INF)
65+
|\\.(?:nan|NaN|NAN))$""",
66+
re.X,
67+
),
68+
list("-+0123456789."),
69+
)
70+
waveform_yaml = yaml.load(yaml_str, Loader=loader)
5271

5372
if not isinstance(waveform_yaml, dict):
5473
raise yaml.YAMLError(

0 commit comments

Comments
 (0)