From d240478c1cecee14dede4f32296312814b0f458b Mon Sep 17 00:00:00 2001 From: Alex Kong Date: Tue, 26 Nov 2024 10:41:10 -0800 Subject: [PATCH] Ensure peaks can be visualized properly --- src/maldi_tools/plotting.py | 10 +++++++--- tests/plotting_test.py | 18 ++++++++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/maldi_tools/plotting.py b/src/maldi_tools/plotting.py index 07706ea..51bd5dc 100644 --- a/src/maldi_tools/plotting.py +++ b/src/maldi_tools/plotting.py @@ -163,13 +163,17 @@ def plot_peak_hist(peak: float, bin_count: int, extraction_dir: Path) -> None: extraction_dir (Path): The directory the peak images are saved in """ # verify that the peak provided exists - peak_path = extraction_dir / f"{str(peak).replace('.', '_')}.tiff" + peak_file: str = f"{peak:.4f}".replace(".", "_") + peak_file = peak_file + ".tiff" + peak_path = Path(extraction_dir) / "float" / peak_file if not os.path.exists(peak_path): - raise FileNotFoundError(f"Peak {peak} does not have a corresponding peak image in {extraction_dir}") + raise FileNotFoundError( + f"Peak {peak:.4f} does not have a corresponding peak image in {extraction_dir}" + ) # load the peak image in and display histogram peak_img: np.ndarray = io.imread(peak_path) - plt.hist(peak_img.values, bins=bin_count) + plt.hist(peak_img, bins=bin_count) def save_matched_peak_images( diff --git a/tests/plotting_test.py b/tests/plotting_test.py index 279f37f..7ce0a64 100644 --- a/tests/plotting_test.py +++ b/tests/plotting_test.py @@ -5,6 +5,7 @@ import numpy as np import pandas as pd +import pytest import xarray as xr from skimage.io import imread @@ -82,6 +83,23 @@ def test_save_peak_images(image_xr: xr.DataArray, tmp_path: pathlib.Path): assert os.path.exists(iname) +def test_plot_peak_hist(image_xr: xr.DataArray, tmp_path: pathlib.Path): + extraction_dir = tmp_path / "extraction_dir" + extraction_dir.mkdir(parents=True, exist_ok=True) + + # ensure the test actually truncates to 4 digits correctly + image_xr = image_xr.assign_coords(peak=np.random.rand(6) * 100) + + plotting.save_peak_images(image_xr=image_xr, extraction_dir=extraction_dir) + + # this test should run to completion, since the peak can be loaded + plotting.plot_peak_hist(peak=image_xr.peak.values[0], bin_count=30, extraction_dir=extraction_dir) + + # this test should fail since the peak does not exist + with pytest.raises(FileNotFoundError): + plotting.plot_peak_hist(peak=50.0123, bin_count=30, extraction_dir=extraction_dir) + + def test_save_matched_peak_images(rng: np.random.Generator, image_xr: xr.DataArray, tmp_path: pathlib.Path): extraction_dir = tmp_path / "extraction_dir" extraction_dir.mkdir(parents=True, exist_ok=True)