Skip to content

Commit

Permalink
code formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
leoschwarz committed May 30, 2024
1 parent 5c7c9a5 commit aad8f49
Show file tree
Hide file tree
Showing 23 changed files with 52 additions and 42 deletions.
7 changes: 4 additions & 3 deletions src/depiction/calibration/perform_calibration.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(
# raise ValueError(f"Unknown pattern={repr(pattern)}")

def _validate_per_spectra_array(self, array: DataArray, coordinates_2d) -> None:
"""Checks the DataArray has the correct shapes and dimensions. Used for debugging. """
"""Checks the DataArray has the correct shapes and dimensions. Used for debugging."""
# TODO make it configurable in the future, whether this check is executed, during development it definitely
# should be here since it can safe a ton of time
expected_coords = {"i", "x", "y"}
Expand Down Expand Up @@ -102,8 +102,9 @@ def _extract_all_features(self, read_peaks: ImzmlReadFile) -> DataArray:
),
reduce_fn=lambda chunks: xarray.concat(chunks, dim="i"),
)
return all_features.assign_coords(x=("i", read_peaks.coordinates_2d[:, 0]),
y=("i", read_peaks.coordinates_2d[:, 1]))
return all_features.assign_coords(
x=("i", read_peaks.coordinates_2d[:, 0]), y=("i", read_peaks.coordinates_2d[:, 1])
)

def _apply_all_models(
self, read_file: ImzmlReadFile, write_file: ImzmlWriteFile, all_model_coefs: DataArray
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ def fit_spectrum_model(self, features: DataArray) -> DataArray:
# us to provide the information about mz_arr, which also risks breaking the abstraction again
return features

def apply_spectrum_model(self, spectrum_mz_arr: NDArray[float], spectrum_int_arr: NDArray[float],
model_coef: DataArray) -> tuple[NDArray[float], NDArray[float]]:
def apply_spectrum_model(
self, spectrum_mz_arr: NDArray[float], spectrum_int_arr: NDArray[float], model_coef: DataArray
) -> tuple[NDArray[float], NDArray[float]]:
res_mz_arr = self._calibration.align_masses(mz_arr=spectrum_mz_arr, int_arr=spectrum_int_arr)
return res_mz_arr, spectrum_int_arr
1 change: 1 addition & 0 deletions src/depiction/evaluate_normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

# TODO deprecated, use tools.normalize_intensities instead


class EvaluateTICNormalization:
"""
Evaluates the TIC normalization of spectra.
Expand Down
1 change: 1 addition & 0 deletions src/depiction/image/sparse_image_2d.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from __future__ import annotations

# file is deprecated, use MultiChannelImage instead!

import warnings
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ def display_altair_chart(active_cell):
.add_params(brush)
)


plot_hist = (
alt.Chart(channel_df)
.mark_bar()
Expand Down
15 changes: 7 additions & 8 deletions src/depiction/misc/experimental/dash_data_visualizer_exp2.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,13 @@ def better_from_dense(x):
[
html.H3("Select a marker of interest"),
dcc.Dropdown(df["Marker"].tolist(), id="marker-dropdown", value=df["Marker"].iloc[0], clearable=False),
#dash_table.DataTable(
# dash_table.DataTable(
# id="table",
# columns=[{"name": i, "id": i} for i in df.columns],
# data=df.to_dict("records"),
# style_table={"height": "300px", "overflowY": "auto"},
# active_cell={"row": 0, "column": 0},
#),
# ),
html.H3("Visualization"),
dvc.Vega(id="altair-chart", opt={"actions": False}),
],
Expand All @@ -70,12 +70,12 @@ def better_from_dense(x):
######## return [{"if": {"row_index": active_cell["row"]}, "backgroundColor": "#3D9970"}]


#@callback(Output("altair-chart", "spec"), Input("table", "active_cell"))
#def display_altair_chart(active_cell):
@callback(Output("altair-chart","spec"), Input("marker-dropdown","value"))
# @callback(Output("altair-chart", "spec"), Input("table", "active_cell"))
# def display_altair_chart(active_cell):
@callback(Output("altair-chart", "spec"), Input("marker-dropdown", "value"))
def display_altair_chart(marker_name):
#i_channel = active_cell["row"]
i_channel = df[df["Marker"]==marker_name].index[0]
# i_channel = active_cell["row"]
i_channel = df[df["Marker"] == marker_name].index[0]
coordinates_2d = ion_images.sparse_coordinates
channel_df = pd.DataFrame(
{
Expand Down Expand Up @@ -103,7 +103,6 @@ def display_altair_chart(marker_name):
.add_params(brush)
)


plot_hist = (
alt.Chart(channel_df)
.mark_bar()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def get_sd_img_channels(channel_img_path: Path, area_coords: NDArray) -> spatial
# fill nan (TODO)
flipped_img = flipped_img.copy()
# TODO?
#flipped_img = flipped_img.fillna(-1.0)
# flipped_img = flipped_img.fillna(-1.0)
# normalize (TODO reconsider)
# flipped_img = ImageNormalization().normalize_xarray(flipped_img, ImageNormalizationVariant.VEC_NORM)
return spatialdata.models.Image2DModel.parse(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def generate_label_image_circles(
label_image[h, w, i_label] = 1

data = DataArray(label_image, dims=("y", "x", "c"), coords={"c": [f"synthetic_{i}" for i in range(n_labels)]})
data["bg_value"] = 0.
data["bg_value"] = 0.0
return MultiChannelImage(data)

def generate_imzml_for_labels(
Expand Down
1 change: 1 addition & 0 deletions src/depiction/parallel_ops/parallel_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

if TYPE_CHECKING:
from depiction.parallel_ops import ParallelConfig

S = TypeVar("S")
T = TypeVar("T")
U = TypeVar("U")
Expand Down
1 change: 1 addition & 0 deletions src/depiction/parallel_ops/read_spectra_parallel.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
if TYPE_CHECKING:
from numpy.typing import NDArray
from depiction.persistence import ImzmlReadFile, ImzmlReader

T = TypeVar("T")
V = TypeVar("V")

Expand Down
8 changes: 5 additions & 3 deletions src/depiction/persistence/imzml_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def __getstate__(self) -> dict[str, Any]:
"int_arr_dtype": self._int_arr_dtype,
"mz_bytes": self._mz_bytes,
"int_bytes": self._int_bytes,
"coordinates": self._coordinates
"coordinates": self._coordinates,
}

# TODO
Expand Down Expand Up @@ -215,5 +215,7 @@ def parse_imzml(cls, path: Path) -> ImzmlReader:
)

def __str__(self) -> str:
return (f"ImzmlReader[{self._imzml_path}, n_spectra={self.n_spectra},"
f" int_arr_dtype={self._int_arr_dtype}, mz_arr_dtype={self._mz_arr_dtype}]")
return (
f"ImzmlReader[{self._imzml_path}, n_spectra={self.n_spectra},"
f" int_arr_dtype={self._int_arr_dtype}, mz_arr_dtype={self._mz_arr_dtype}]"
)
7 changes: 5 additions & 2 deletions src/depiction/persistence/imzml_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def __init__(
self,
*,
wrapped_imzml_writer: pyimzml.ImzMLWriter.ImzMLWriter,
imzml_alignment_tracker: Optional[ImzmlAlignmentTracker]
imzml_alignment_tracker: Optional[ImzmlAlignmentTracker],
) -> None:
self._imzml_writer = wrapped_imzml_writer
self._imzml_alignment_tracker = imzml_alignment_tracker
Expand Down Expand Up @@ -70,7 +70,7 @@ def add_spectrum(
) -> None:
if len(mz_arr) != len(int_arr):
raise ValueError(f"{len(mz_arr)=} and {len(int_arr)=} must be equal.")

# Handle alignment check information.
if self._imzml_alignment_tracker:
self._imzml_alignment_tracker.track_mz_array(mz_arr)
Expand All @@ -96,9 +96,12 @@ def copy_spectra(
:param spectra_indices: The indices of the spectra to copy.
"""
if tqdm_position is not None:

def progress_fn(x):
return tqdm(x, desc=" spectrum", position=tqdm_position)

else:

def progress_fn(x):
return x

Expand Down
1 change: 0 additions & 1 deletion src/depiction/persistence/pixel_size.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,3 @@ class PixelSize:
size_x: float
size_y: float
unit: str

9 changes: 6 additions & 3 deletions src/depiction/persistence/ram_write_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,13 @@ def __init__(self, imzml_mode: ImzmlModeEnum) -> None:
def imzml_mode(self):
return self._imzml_mode

#Just for the sake of a clean api this does not really belong here...
#def add_spectrum(
# Just for the sake of a clean api this does not really belong here...
# def add_spectrum(
# self,
# mz_arr: np.ndarray,
# int_arr: np.ndarray,
# coordinates: tuple[int, int] | tuple[int, int, int],
#):
# ):
# self._mz_arr.append(mz_arr)
# self._int_arr.append(int_arr)
# self._coordinates.append(coordinates)
Expand Down Expand Up @@ -58,9 +58,12 @@ def add_spectrum(self, mz_arr: np.ndarray, int_arr: np.ndarray, coordinates) ->
def copy_spectra(self, reader, spectra_indices: Sequence[int], tqdm_position: int | None = None) -> None:
# TODO reuse the implementation from ImzmlWriter as this is 100% identical
if tqdm_position is not None:

def progress_fn(x):
return tqdm(x, desc=" spectrum", position=tqdm_position)

else:

def progress_fn(x):
return x

Expand Down
2 changes: 1 addition & 1 deletion src/depiction/spectrum/baseline/baseline.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Baseline(Protocol):
"""Baseline estimation and subtraction protocol."""

def evaluate_baseline(self, mz_arr: NDArray[float], int_arr: NDArray[float]) -> NDArray[float]:
"""Returns the spectrum intensities of the baseline. """
"""Returns the spectrum intensities of the baseline."""
raise NotImplementedError()

def subtract_baseline(self, mz_arr: NDArray[float], int_arr: NDArray[float]) -> NDArray[float]:
Expand Down
4 changes: 3 additions & 1 deletion src/depiction/spectrum/evaluate_bins.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ def evaluate(self, mz_arr: NDArray[float], int_arr: NDArray[float]) -> NDArray[f
self._statistic.value,
)

def evaluate_file(self, read_file: ImzmlReadFile, write_file: ImzmlWriteFile, parallel_config: ParallelConfig) -> None:
def evaluate_file(
self, read_file: ImzmlReadFile, write_file: ImzmlWriteFile, parallel_config: ParallelConfig
) -> None:
write_parallel = WriteSpectraParallel.from_config(parallel_config)
write_parallel.map_chunked_to_file(
read_file=read_file,
Expand Down
5 changes: 1 addition & 4 deletions src/depiction/spectrum/peak_picking/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
from .basic_peak_picker import BasicPeakPicker
from .basic_interpolated_peak_picker import BasicInterpolatedPeakPicker

__all__ = [
"BasicPeakPicker",
"BasicInterpolatedPeakPicker"
]
__all__ = ["BasicPeakPicker", "BasicInterpolatedPeakPicker"]
1 change: 0 additions & 1 deletion src/depiction/tools/align_imzml.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ class AlignImzmlMethod(enum.Enum):
FIRST_MZ_ARR = "FIRST_MZ_ARR"



class AlignImzml:
"""Aligns the m/z values of an imzml file to a common set of bins."""

Expand Down
2 changes: 1 addition & 1 deletion src/depiction/tools/correct_baseline.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def evaluate_file(self, read_file: ImzmlReadFile, write_file: ImzmlWriteFile) ->
read_file=read_file,
write_file=write_file,
operation=self._operation,
bind_args=dict(baseline_correction=self._baseline_correction)
bind_args=dict(baseline_correction=self._baseline_correction),
)

def evaluate_spectrum(self, mz_arr: NDArray[float], int_arr: NDArray[float]) -> NDArray[float]:
Expand Down
2 changes: 1 addition & 1 deletion src/depiction/tools/generate_ion_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from depiction.persistence import ImzmlReadFile, ImzmlReader
from depiction.tools.image_channel_statistics import ImageChannelStatistics


class GenerateIonImage:
"""Generates ion images from an imzML file.
Expand All @@ -21,7 +22,6 @@ class GenerateIonImage:
it can be expected to be faster than calling the generate_*_for_file methods multiple times.
"""


def __init__(self, parallel_config: ParallelConfig) -> None:
# TODO for peak picked data, it could be worth considering an option to only select the closest peak in case
# multiple peaks would fall within the window of interest
Expand Down
4 changes: 3 additions & 1 deletion src/depiction/tools/normalize_spectra_intensities.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ class NormalizeSpectraIntensitiesVariant:
class NormalizeSpectraIntensities:
variant: NormalizeSpectraIntensitiesVariant

def process_file(self, read_file: ImzmlReadFile, write_file: ImzmlWriteFile, parallel_config: ParallelConfig) -> None:
def process_file(
self, read_file: ImzmlReadFile, write_file: ImzmlWriteFile, parallel_config: ParallelConfig
) -> None:
write_parallel = WriteSpectraParallel.from_config(parallel_config)
write_parallel.map_chunked_to_file(
read_file=read_file,
Expand Down
10 changes: 5 additions & 5 deletions src/depiction/visualize/visualize_2d_channels.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# TODO delete this file if not needed anymore
#from typing import Optional, Callable, Sequence
# from typing import Optional, Callable, Sequence
#
#from matplotlib import pyplot as plt
# from matplotlib import pyplot as plt
#
#from ion_mapper.image.sparse_image_2d import SparseImage2d
# from ion_mapper.image.sparse_image_2d import SparseImage2d
#
#
## TODO the configuration of intensity transformation needs to be more generic / standardized
#
#class Visualize2dChannels:
# class Visualize2dChannels:
# """Visualizes 2D image channels."""
#
# def __init__(self, image: SparseImage2d):
Expand Down Expand Up @@ -57,4 +57,4 @@
# axs: Optional[NDArray[plt.Axes]] = None,
# ) -> tuple[plt.Figure, plt.Axes]:
# pass
#
#
3 changes: 1 addition & 2 deletions src/depiction/visualize/visualize_mass_shift_map.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,7 @@ def _plot_row(

# plot the map
PlotImage(correction_image).plot_single_channel_image(
correction_image.channel_names[0],
ax=ax_map, cmap="coolwarm", vmin=-abs_perc, vmax=abs_perc
correction_image.channel_names[0], ax=ax_map, cmap="coolwarm", vmin=-abs_perc, vmax=abs_perc
)
ax_map.set_title(f"Error for {name}")
ax_map.axis("off")
Expand Down

0 comments on commit aad8f49

Please sign in to comment.