|
| 1 | +import numpy as np |
| 2 | +import pytest |
| 3 | + |
| 4 | +from diffpy.morph.morphs.morphsqueeze import MorphSqueeze |
| 5 | + |
| 6 | + |
| 7 | +class TestMorphSqueeze: |
| 8 | + @pytest.fixture |
| 9 | + def setup(self): |
| 10 | + # Create a sine-wave for testing |
| 11 | + self.x_morph = np.linspace(0, 2 * np.pi, 1000) |
| 12 | + self.y_morph = np.sin(self.x_morph) |
| 13 | + self.x_target = self.x_morph.copy() |
| 14 | + self.y_target = self.y_morph.copy() |
| 15 | + return |
| 16 | + |
| 17 | + def test_no_squeeze(self, setup): |
| 18 | + """When squeeze is zero, the input should be unchanged.""" |
| 19 | + morph = MorphSqueeze() |
| 20 | + morph.squeeze = 0.0 |
| 21 | + |
| 22 | + x_morph, y_morph, x_target, y_target = morph( |
| 23 | + self.x_morph, self.y_morph, self.x_target, self.y_target |
| 24 | + ) |
| 25 | + |
| 26 | + # Verify that the morph output matches the original input |
| 27 | + assert np.allclose(x_morph, self.x_morph) |
| 28 | + assert np.allclose(y_morph, self.y_morph) |
| 29 | + # And the target arrays remain unchanged |
| 30 | + assert np.allclose(x_target, self.x_target) |
| 31 | + assert np.allclose(y_target, self.y_target) |
| 32 | + |
| 33 | + def test_morph_with_squeeze(self, setup): |
| 34 | + """Test that with a non-zero squeeze, |
| 35 | + x_morph is transformed non-linearly.""" |
| 36 | + morph = MorphSqueeze() |
| 37 | + morph.squeeze = 0.7 |
| 38 | + x_new, y_new, x_target, y_target = morph( |
| 39 | + self.x_morph, self.y_morph, self.x_target, self.y_target |
| 40 | + ) |
| 41 | + |
| 42 | + # Check that target arrays remain unchanged |
| 43 | + assert np.allclose(self.y_target, y_target) |
| 44 | + |
| 45 | + # For this test, we expect: |
| 46 | + # x_new = x_morph + squeeze_factor * sin(x_morph) |
| 47 | + expected_x = self.x_morph + morph.squeeze * np.sin(self.x_morph) |
| 48 | + expected_y = np.sin(expected_x) |
| 49 | + |
| 50 | + # Allow for some tolerance because of numerical interpolation if used |
| 51 | + res = sum(np.fabs(expected_y - y_new)) |
| 52 | + assert res < 1 |
| 53 | + |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + TestMorphSqueeze() |
0 commit comments