fix serialization of numpy scalars in job XML under numpy 2

numpy 2 changed repr(np.float64(1e-06)) to 'np.float64(1e-06)', so values
taken from lin_range() ended up unparsable in the job file: the result
script failed with "could not convert string to float". Description items
and state times are now converted to builtin types before writing.
This commit is contained in:
markusro committed 2026-10-16 12:16:16 +02:00
1 parent ef11824f8b
commit 1fb56e20f9
2 files changed
+34 -6

No files matched your search

+6 -6
View File
@@ -13,7 +13,7 @@ class StateSimple(StateBase):
super(StateSimple, self).__init__()
if time < 0:
raise AssertionError("time for state is negative!")
self.time = time
self.time = float(time)
self.content = content
def to_xml(self, indent = ""):
@@ -190,7 +190,7 @@ class Experiment:
Typically only used in very special cases.
"""
self.state_list.append('<state time="%s">\n' % repr(time))
self.state_list.append('<state time="%s">\n' % repr(float(time)))
self.total_time[-1] += time
## End of *state_start*
@@ -679,19 +679,19 @@ class Experiment:
value=""
elif type(value) is float or isinstance(value, numpy.floating):
type_string="Float"
value=repr(value)
value=repr(float(value))
elif type(value) is int or isinstance(value, numpy.integer):
type_string="Int"
value=repr(value)
value=repr(int(value))
elif type(value) is int:
type_string="Long"
value=repr(value)
elif type(value) is complex or isinstance(value, numpy.complexfloating):
type_string="Complex"
value=repr(value)
value=repr(complex(value))
elif type(value) is bool or isinstance(value, numpy.bool_):
type_string="Boolean"
value=repr(value)
value=repr(bool(value))
elif type(value) in (str,):
type_string="String"
else:
+28
View File
@@ -42,6 +42,34 @@ class TestExperimentPhase(unittest.TestCase):
e.rf_pulse(length=1e-6, phase=-90, source=0)
self.assertEqual(phase_of_state(e.state_list.list[0]), 270.0)
def test_numpy_scalars_in_description(self):
"""Test that description items with numpy scalars (e.g. from lin_range)
are written as plain numbers so the result script can parse them again."""
import numpy as np
from damaris.tools.ranges import lin_range
e = Experiment()
e.set_description("tau", lin_range(1e-6, 3e-6, 1e-6)[0])
e.set_description("n", np.int64(42))
xml = e.write_xml_string()
items = {key: (typ, text)
for key, typ, text in
re.findall(r'<item key="([^"]+)" type="([^"]+)">([^<]*)</item>', xml)}
self.assertEqual(items["tau"][0], "Float")
self.assertEqual(items["n"][0], "Int")
self.assertEqual(float(items["tau"][1]), 1e-6)
self.assertEqual(int(items["n"][1]), 42)
def test_numpy_scalar_state_times(self):
"""Test that numpy scalar times do not end up as np.float64(...) in the XML."""
import numpy as np
e = Experiment()
e.wait(np.float64(1e-6))
e.state_start(np.float64(2e-6))
xml = e.write_xml_string()
self.assertNotIn("np.float64", xml)
self.assertIn('<state time="1e-06"/>', xml)
self.assertIn('<state time="2e-06">', xml)
if __name__ == "__main__":
unittest.main()