Files
2026-09-29 22:41:29 +08:00

65 lines
1.7 KiB
Python

from __future__ import annotations
import json
from pathlib import Path
import numpy as np
import pytest
from src.gain_calibration import GainCalibration
REPOSITORY_ROOT = Path(__file__).parents[1]
def write_config(tmp_path, common_gain: float, trim: list[float]):
path = tmp_path / "gain.json"
path.write_text(
json.dumps(
{
"common_base_gain_db": common_gain,
"channel_trim_gain_db": trim,
}
),
encoding="utf-8",
)
return path
def test_applies_common_and_channel_gain_in_db(tmp_path) -> None:
path = write_config(tmp_path, 6.0, [0.0, -6.0])
calibration = GainCalibration.load(path, channels=2)
calibrated = calibration.apply(np.ones((3, 2), dtype=np.float32))
expected = np.array([10.0 ** (6.0 / 20.0), 1.0], dtype=np.float32)
np.testing.assert_allclose(calibrated, np.tile(expected, (3, 1)), rtol=1e-6)
def test_runtime_channel_trims_match_calibration_result() -> None:
runtime_config = json.loads(
(REPOSITORY_ROOT / "src" / "gain_cali.json").read_text(encoding="utf-8")
)
calibration_result = json.loads(
(REPOSITORY_ROOT / "calibration" / "data" / "calibration_result.json").read_text(
encoding="utf-8"
)
)
assert runtime_config["channel_trim_gain_db"] == calibration_result["correction_db"]
@pytest.mark.parametrize(
"common_gain, trim",
[
(0.0, [0.0]),
(float("nan"), [0.0, 0.0]),
(0.0, [0.0, float("inf")]),
],
)
def test_rejects_invalid_gain_configuration(tmp_path, common_gain, trim) -> None:
path = write_config(tmp_path, common_gain, trim)
with pytest.raises(ValueError):
GainCalibration.load(path, channels=2)