|
| 1 | +"""Tests for the plotting.utils module.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import re |
| 5 | +from unittest.mock import Mock |
| 6 | + |
| 7 | +import pytest |
| 8 | +from matplotlib.colors import to_rgb |
| 9 | + |
| 10 | +from ir_amplitude_detuning.detuning.measurements import Constraints, Detuning, DetuningMeasurement, MeasureValue |
| 11 | +from ir_amplitude_detuning.detuning.targets import Target, TargetData |
| 12 | +from ir_amplitude_detuning.plotting.utils import ( |
| 13 | + OtherColors, |
| 14 | + get_color_for_field, |
| 15 | + get_color_for_ip, |
| 16 | + get_default_scaling, |
| 17 | + get_full_target_labels, |
| 18 | +) |
| 19 | +from ir_amplitude_detuning.utilities.correctors import Corrector, FieldComponent |
| 20 | + |
| 21 | + |
| 22 | +# ============================================================================ |
| 23 | +# Tests for get_default_scaling |
| 24 | +# ============================================================================ |
| 25 | + |
| 26 | +class TestGetDefaultScaling: |
| 27 | + """Test cases for the get_default_scaling function.""" |
| 28 | + |
| 29 | + @pytest.mark.parametrize( |
| 30 | + "term,expected_exponent,expected_scaling", |
| 31 | + [ |
| 32 | + ("X02", 12, 1e-12), |
| 33 | + ("Y01", 3, 1e-3), |
| 34 | + ("Y11", 12, 1e-12), |
| 35 | + ("X10", 3, 1e-3), |
| 36 | + ], |
| 37 | + ) |
| 38 | + def test_get_default_scaling(self, term: str, expected_exponent: int, expected_scaling: float): |
| 39 | + """Test default scaling factors for various detuning terms.""" |
| 40 | + exponent, scaling = get_default_scaling(term) |
| 41 | + assert exponent == expected_exponent |
| 42 | + assert scaling == pytest.approx(expected_scaling) |
| 43 | + |
| 44 | + def test_get_default_scaling_invalid_sum(self): |
| 45 | + """Test that invalid term sums raise KeyError.""" |
| 46 | + with pytest.raises(KeyError): |
| 47 | + get_default_scaling("X00") # sum is 0, not in dict |
| 48 | + |
| 49 | + with pytest.raises(KeyError): |
| 50 | + get_default_scaling("Y31") # sum is 4, not in dict |
| 51 | + |
| 52 | + |
| 53 | +# ============================================================================ |
| 54 | +# Tests for get_color_for_field |
| 55 | +# ============================================================================ |
| 56 | + |
| 57 | +class TestGetColorForField: |
| 58 | + """Test cases for the get_color_for_field function.""" |
| 59 | + |
| 60 | + @pytest.mark.parametrize("field", list(FieldComponent)) |
| 61 | + def test_get_color_for_field_valid(self, field: FieldComponent): |
| 62 | + """Test that valid fields return colors.""" |
| 63 | + result = get_color_for_field(field) # asserts all fields are valid |
| 64 | + _, _, _ = to_rgb(result) # asserts that it is convertable to RGB |
| 65 | + |
| 66 | + def test_all_colors_different(self): |
| 67 | + """Test that all colors are different.""" |
| 68 | + colors = [get_color_for_field(field) for field in list(FieldComponent)] |
| 69 | + assert len(set(colors)) == len(colors) |
| 70 | + |
| 71 | + def test_get_color_for_field_invalid(self): |
| 72 | + """Test that invalid fields raise NotImplementedError.""" |
| 73 | + # Create a mock field that doesn't match any case |
| 74 | + mock_field = Mock(spec=FieldComponent) |
| 75 | + mock_field.__str__ = Mock(return_value="invalid_field") |
| 76 | + |
| 77 | + with pytest.raises(NotImplementedError, match="Field must be one of"): |
| 78 | + get_color_for_field(mock_field) |
| 79 | + |
| 80 | + |
| 81 | +# ============================================================================ |
| 82 | +# Tests for get_color_for_ip |
| 83 | +# ============================================================================ |
| 84 | + |
| 85 | +class TestGetColorForIp: |
| 86 | + """Test cases for the get_color_for_ip function.""" |
| 87 | + |
| 88 | + @pytest.mark.parametrize("ip", ["15", "1", "5"]) |
| 89 | + def test_get_color_for_ip_valid(self, ip: str): |
| 90 | + """Test that valid IPs return colors.""" |
| 91 | + result = get_color_for_ip(ip) # asserts all IPs are valid |
| 92 | + _, _, _ = to_rgb(result) # asserts that it is convertable to RGB |
| 93 | + |
| 94 | + def test_all_colors_different(self): |
| 95 | + """Test that all colors are different.""" |
| 96 | + colors = [get_color_for_ip(ip) for ip in ["15", "1", "5"]] |
| 97 | + assert len(set(colors)) == len(colors) |
| 98 | + |
| 99 | + @pytest.mark.parametrize("invalid_ip", ["2", "8", "invalid", "", "1 ", "15a", "0"]) |
| 100 | + def test_get_color_for_ip_invalid(self, invalid_ip: str): |
| 101 | + """Test that invalid IPs raise NotImplementedError.""" |
| 102 | + with pytest.raises( |
| 103 | + NotImplementedError, |
| 104 | + match=f"IP must be one of \\['15', '1', '5'\\], got {invalid_ip}\\." |
| 105 | + ): |
| 106 | + get_color_for_ip(invalid_ip) |
| 107 | + |
| 108 | + |
| 109 | +# ============================================================================ |
| 110 | +# Tests for OtherColors |
| 111 | +# ============================================================================ |
| 112 | + |
| 113 | +class TestOtherColors: |
| 114 | + """Test cases for the OtherColors class.""" |
| 115 | + |
| 116 | + def test_other_colors_estimated(self): |
| 117 | + """Test that OtherColors.estimated has correct value.""" |
| 118 | + _, _, _ = to_rgb(OtherColors.estimated) |
| 119 | + assert OtherColors.flat != OtherColors.estimated |
| 120 | + |
| 121 | + def test_other_colors_flat(self): |
| 122 | + """Test that OtherColors.flat has correct value.""" |
| 123 | + _, _, _ = to_rgb(OtherColors.estimated) |
| 124 | + assert OtherColors.flat != OtherColors.estimated |
| 125 | + |
| 126 | +# ============================================================================ |
| 127 | +# Tests for get_full_target_labels |
| 128 | +# ============================================================================ |
| 129 | + |
| 130 | +class TestGetFullTargetLabels: |
| 131 | + """Test cases for the get_full_target_labels function.""" |
| 132 | + |
| 133 | + def test_get_full_target_labels_single_target_no_suffixes(self, target_data): |
| 134 | + """Test with single target and no suffixes.""" |
| 135 | + result = get_full_target_labels([Target(name="target_name", data=[target_data])]) |
| 136 | + |
| 137 | + assert isinstance(result, dict) |
| 138 | + assert "target_name" in result |
| 139 | + target_label = result["target_name"] |
| 140 | + assert isinstance(target_label, str) |
| 141 | + assert re.search(r"\$Q_\{x,yy\}\$\s+=\s+1\.5\s+\|\s+3\.5", target_label) # values from the fixture |
| 142 | + assert re.search(r"\$Q_\{y,xy\}\$\s+=\s+--\s+\|\s+2\.5", target_label) |
| 143 | + |
| 144 | + |
| 145 | + def test_get_full_target_labels_multiple_targets_with_suffixes(self, target_data): |
| 146 | + """Test with multiple targets and suffixes.""" |
| 147 | + result = get_full_target_labels( |
| 148 | + [Target(name="target1", data=[target_data]), |
| 149 | + Target(name="target2", data=[target_data])], |
| 150 | + suffixes=["suffix_1", "suffix_2"] |
| 151 | + ) |
| 152 | + |
| 153 | + assert len(result) == 2 |
| 154 | + assert "target1" in result |
| 155 | + assert "target2" in result |
| 156 | + assert "suffix_1" in result["target1"] |
| 157 | + assert "suffix_2" in result["target2"] |
| 158 | + assert result["target1"].replace("suffix_1","") == result["target2"].replace("suffix_2","") |
| 159 | + |
| 160 | + def test_get_full_target_labels_empty_targets(self): |
| 161 | + """Test with empty targets list.""" |
| 162 | + result = get_full_target_labels([]) |
| 163 | + |
| 164 | + assert isinstance(result, dict) |
| 165 | + assert len(result) == 0 |
| 166 | + |
| 167 | + def test_get_full_target_labels_mismatched_suffixes_error(self, target_data): |
| 168 | + """Test that mismatched suffixes count raises ValueError.""" |
| 169 | + with pytest.raises(ValueError, match="Number of suffixes must match number of targets"): |
| 170 | + get_full_target_labels( |
| 171 | + [ |
| 172 | + Target(name="target1", data=[target_data]), |
| 173 | + Target(name="target2", data=[target_data]), |
| 174 | + ], |
| 175 | + suffixes=["only_one_suffix"], |
| 176 | + ) |
| 177 | + |
| 178 | + def test_get_full_target_labels_custom_scale_exponent(self, target_data): |
| 179 | + """Test with custom scale exponent.""" |
| 180 | + result = get_full_target_labels([Target(name="target_name", data=[target_data])], rescale=4) |
| 181 | + |
| 182 | + assert isinstance(result, dict) |
| 183 | + assert "target_name" in result # replace "target_data.name" with the actual name of the target |
| 184 | + target_label = result["target_name"] |
| 185 | + assert isinstance(target_label, str) |
| 186 | + assert re.search(r"\$Q_\{x,yy\}\$\s+=\s+0\.2\s+\|\s+0\.4", target_label) # values /10 from the fixture |
| 187 | + assert re.search(r"\$Q_\{y,xy\}\$\s+=\s+--\s+\|\s+0\.3", target_label) |
| 188 | + |
| 189 | + |
| 190 | +@pytest.fixture |
| 191 | +def target_data(): |
| 192 | + """Fixture for TargetData. Used in the TestGetFullTargetLabels class.""" |
| 193 | + correctors = [ |
| 194 | + Corrector(field=FieldComponent.b4, circuit="k4", magnet="K4", length=0.5), |
| 195 | + Corrector(field=FieldComponent.b5, circuit="k5", magnet="K5", length=0.5), |
| 196 | + ] |
| 197 | + optics = {1: Mock(), 2: Mock()} |
| 198 | + detuning = { |
| 199 | + 1: DetuningMeasurement(X02=(1.51, 2.5), scale=1e3), |
| 200 | + 2: DetuningMeasurement(Y11=(2.51, 2.5), X02=(3.52, 4.5), scale=1e3) |
| 201 | + } |
| 202 | + constraints = {1: Constraints(Y02="<=10"), 2: Constraints(Y02=">=11")} |
| 203 | + return TargetData( |
| 204 | + correctors=correctors, optics=optics, detuning=detuning, constraints=constraints |
| 205 | + ) |
0 commit comments