import re
import unittest
from damaris.experiments.Experiment import Experiment
def phase_of_state(state):
"extracts the phase value from a state's XML content"
match = re.search(r'phase="([-0-9.]+)"', state.content)
assert match, "no phase in state: %s" % state.content
return float(match.group(1))
class TestExperimentPhase(unittest.TestCase):
def test_set_phase_negative_normalized(self):
"""Test that set_phase() normalizes negative phases to [0, 360)."""
e = Experiment()
for degrees, expected in ((-90, 270.0), (-45.5, 314.5),
(-270, 90.0), (-360, 0.0)):
e.set_phase(degrees)
self.assertEqual(phase_of_state(e.state_list.list[-1]), expected)
def test_set_phase_positive_unchanged(self):
"""Test that set_phase() passes positive phases through unchanged."""
e = Experiment()
for degrees, expected in ((0, 0.0), (90, 90.0), (270, 270.0),
(45.5, 45.5)):
e.set_phase(degrees)
self.assertEqual(phase_of_state(e.state_list.list[-1]), expected)
def test_set_frequency_negative_phase_normalized(self):
"""Test that set_frequency() normalizes a negative phase."""
e = Experiment()
e.set_frequency(85e6, -90)
state = e.state_list.list[-1]
self.assertEqual(phase_of_state(state), 270.0)
self.assertIn('f="85000000.000000"', state.content)
def test_rf_pulse_negative_phase_normalized(self):
"""Test that rf_pulse() normalizes a negative pulse phase."""
e = Experiment(gating=1e-6, rf_sources=[1], rf_gates=[2])
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'- ([^<]*)
', 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('', xml)
self.assertIn('', xml)
if __name__ == "__main__":
unittest.main()