|
| 1 | +import unittest |
| 2 | +import numpy as np |
| 3 | +from tinycio import Spectral |
| 4 | + |
| 5 | + |
| 6 | +class TestSpectral(unittest.TestCase): |
| 7 | + |
| 8 | + def setUp(self): |
| 9 | + pass |
| 10 | + |
| 11 | + def tearDown(self): |
| 12 | + pass |
| 13 | + |
| 14 | + def test_cm_table_exceeds_one(self): |
| 15 | + # CIE 1931 2-degree CMFs legitimately exceed 1.0; |
| 16 | + # documents why wl_to_xyz must not clip to [0, 1]. |
| 17 | + tab = Spectral.cm_table() |
| 18 | + self.assertGreater(float(tab[:, 0].max()), 1.0) # x-bar peaks at 1.0622 (600nm) |
| 19 | + self.assertGreater(float(tab[:, 2].max()), 1.5) # z-bar peaks at 1.7826 (445nm) |
| 20 | + self.assertAlmostEqual(float(tab[:, 0].max()), 1.0622, places=4) |
| 21 | + self.assertAlmostEqual(float(tab[:, 2].max()), 1.7826, places=4) |
| 22 | + |
| 23 | + def test_wl_to_xyz_no_clip(self): |
| 24 | + # Regression test: wl_to_xyz must return raw CMF values, |
| 25 | + # not clipped to [0, 1]. Spot-check wavelengths where Z/X exceed 1. |
| 26 | + for wl, expected in [(445., (0.3481, 0.0298, 1.7826)), |
| 27 | + (450., (0.3362, 0.0380, 1.7721)), |
| 28 | + (600., (1.0622, 0.6310, 0.0008))]: |
| 29 | + np.testing.assert_allclose(np.asarray(Spectral.wl_to_xyz(wl)), |
| 30 | + np.asarray(expected), atol=1e-4) |
| 31 | + |
| 32 | + def test_wl_to_xyz_chromaticity_450(self): |
| 33 | + # Clipping Z 1.7721 -> 1.0 shifts x 0.1566 -> 0.2447; guard the ratio. |
| 34 | + x, y, z = [float(v) for v in Spectral.wl_to_xyz(450.)] |
| 35 | + self.assertAlmostEqual(x / (x + y + z), 0.1566, places=4) |
| 36 | + |
| 37 | + def test_wl_to_xyz_matches_table_on_grid(self): |
| 38 | + # Every 5nm grid point must round-trip the embedded table exactly. |
| 39 | + tab = Spectral.cm_table() |
| 40 | + for i in range(tab.shape[0]): |
| 41 | + wl = 380. + 5. * i |
| 42 | + if wl >= 780: |
| 43 | + break |
| 44 | + np.testing.assert_allclose(np.asarray(Spectral.wl_to_xyz(wl)), |
| 45 | + np.asarray(tab[i]), atol=1e-6) |
| 46 | + |
| 47 | + def test_wl_to_xyz_interpolation_midpoint(self): |
| 48 | + # Off-grid wavelengths linearly interpolate between neighbors. |
| 49 | + tab = Spectral.cm_table() |
| 50 | + i = int((445. - 380.) / 5.) |
| 51 | + expected = 0.5 * (np.asarray(tab[i]) + np.asarray(tab[i + 1])) |
| 52 | + np.testing.assert_allclose(np.asarray(Spectral.wl_to_xyz(447.5)), |
| 53 | + expected, atol=1e-6) |
| 54 | + |
| 55 | + |
| 56 | +if __name__ == '__main__': |
| 57 | + unittest.main() |
0 commit comments