Skip to content

Commit

Permalink
run pre-commit hooks in all files
Browse files Browse the repository at this point in the history
  • Loading branch information
juliomateoslangerak committed Jan 11, 2024
1 parent 7a8525e commit 8746116
Show file tree
Hide file tree
Showing 14 changed files with 41 additions and 104 deletions.
3 changes: 2 additions & 1 deletion docs/examples/new_sample.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ class DetectLinesAnalysis(
AnalysisMixin
): # Subclass Analysis for each analysis you want to implement for a given sample
"""Write a good documentation:
This analysis detects lines in a 2D image through a progressive probabilistic hough transform."""
This analysis detects lines in a 2D image through a progressive probabilistic hough transform.
"""

# Define the __init__
def __init__(self):
Expand Down
10 changes: 2 additions & 8 deletions src/microscopemetrics/analysis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ def get_image_data(image, device):
if raw_img.shape[2] == 1:
raw_img = np.squeeze(raw_img, 2) # TODO: Fix this time dimension.
else:
raise Exception(
"Image has a time dimension. Time is not yet implemented for this analysis"
)
raise Exception("Image has a time dimension. Time is not yet implemented for this analysis")
pixel_size = interface.get_pixel_size(image)
pixel_size_units = interface.get_pixel_size_units(image)

Expand All @@ -69,7 +67,6 @@ def get_image_data(image, device):
def save_data_table(
conn, table_name, col_names, col_descriptions, col_data, interface_obj, namespace
):

table_ann = interface.create_annotation_table(
connection=conn,
table_name=table_name,
Expand Down Expand Up @@ -118,7 +115,6 @@ def create_image(
source_image_id=None,
metrics_generated_tag_id=None,
):

zct_list = list(
product(
range(image_intensities.shape[0]),
Expand Down Expand Up @@ -175,9 +171,7 @@ def analyze_dataset(connection, script_params, dataset, analysis_config, device_
"sources": list(),
}

for section, analyses, handler in zip(
SAMPLE_SECTIONS, SAMPLE_ANALYSES, SAMPLE_HANDLERS
):
for section, analyses, handler in zip(SAMPLE_SECTIONS, SAMPLE_ANALYSES, SAMPLE_HANDLERS):
if analysis_config.has_section(section):
module_logger.info(f"Running analysis on {section.capitalize()} sample(s)")
section_conf = analysis_config[section]
Expand Down
32 changes: 8 additions & 24 deletions src/microscopemetrics/devices/devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,9 +207,7 @@ def update_settings(self, incoming, init=False):
my_keys = set(self._settings.keys())
their_keys = set(incoming.keys())
update_keys = set(
key
for key in my_keys & their_keys
if self.get_setting(key) != incoming[key]
key for key in my_keys & their_keys if self.get_setting(key) != incoming[key]
)
results = {}
# Update values.
Expand Down Expand Up @@ -246,9 +244,7 @@ def _get_conf_objective_nr(self, image):
"More than one reference to an objective lens was found in the image name. Only the first one will be considered."
)
elif len(obj_nrs) == 0:
module_logger.info(
"No references to any objective lens were found in the image name"
)
module_logger.info("No references to any objective lens were found in the image name")
return None
return obj_nrs[0]

Expand Down Expand Up @@ -290,9 +286,7 @@ def _get_conf_channel_nrs(self, image):
# Sort channels according to their position in the name
ch_nrs = tuple(ch for _, ch in sorted(zip(token_positions, ch_nrs)))
if len(ch_nrs) == 0:
module_logger.info(
"No references to any channel were found in the image name"
)
module_logger.info("No references to any channel were found in the image name")
return None
return ch_nrs

Expand Down Expand Up @@ -405,9 +399,7 @@ def get_all_settings(self, **kwargs):
return settings

def _get_conf_objective_lens_refr_index(self, image):
return self._get_conf_objective_setting(
"objective_lens_refractive_index", image
)
return self._get_conf_objective_setting("objective_lens_refractive_index", image)

def _get_name_objective_lens_refr_index(self, image):
return self._get_metadata_from_name("_RI=", "_", float, image)
Expand All @@ -419,9 +411,7 @@ def _get_name_objective_lens_na(self, image):
return self._get_metadata_from_name("_NA=", "_", float, image)

def _get_conf_objective_lens_nominal_magnification(self, image):
return self._get_conf_objective_setting(
"objective_lens_nominal_magnification", image
)
return self._get_conf_objective_setting("objective_lens_nominal_magnification", image)

def _get_name_objective_lens_nominal_magnification(self, image):
return self._get_metadata_from_name("_MAG=", "_", float, image)
Expand Down Expand Up @@ -500,9 +490,7 @@ def get_theoretical_res_fwhm(self, **kwargs):
na = self.get_setting("objective_lens_na", **kwargs)
for em in self.get_setting("emission_wavelengths", **kwargs):
try:
theoretical_res["resolution_theoretical_fwhm_lateral"].append(
0.353 * em / na
)
theoretical_res["resolution_theoretical_fwhm_lateral"].append(0.353 * em / na)
except TypeError as e:
module_logger.warning(
"FWHM theoretical resolution could not be calculated. Verify configuration files."
Expand Down Expand Up @@ -538,9 +526,7 @@ def get_theoretical_res_rayleigh(self, **kwargs):
ri = self.get_setting("objective_lens_refractive_index", **kwargs)
for em in self.get_setting("emission_wavelengths", **kwargs):
try:
theoretical_res["resolution_theoretical_rayleigh_lateral"].append(
0.61 * em / na
)
theoretical_res["resolution_theoretical_rayleigh_lateral"].append(0.61 * em / na)
except TypeError as e:
module_logger.warning(
"Rayleigh theoretical lateral resolution could not be calculated. Verify configuration files."
Expand Down Expand Up @@ -585,9 +571,7 @@ def get_nyquist(self, **kwargs):
)
nyquist_delta["nyquist_lateral"].append(None)
try:
nyquist_delta["nyquist_axial"].append(
em / (2 * ri * (1 - cos(asin(na / ri))))
)
nyquist_delta["nyquist_axial"].append(em / (2 * ri * (1 - cos(asin(na / ri)))))
except TypeError as e:
module_logger.warning(
"Axial Nyquist criterion could not be calculated. Verify configuration files."
Expand Down
18 changes: 4 additions & 14 deletions src/microscopemetrics/plots/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,7 @@ def plot_distances_maps(distances, x_dim, y_dim):
distances_map = np.asarray(p["dist_3d"])

grid_x, grid_y = np.mgrid[0:x_dim:1, 0:y_dim:1]
interpolated = griddata(
positions_map, distances_map, (grid_x, grid_y), method="cubic"
)
interpolated = griddata(positions_map, distances_map, (grid_x, grid_y), method="cubic")

ax = axes.ravel()
ax[(p["channels"][0] * 4) + p["channels"][1]].imshow(
Expand All @@ -89,19 +87,14 @@ def plot_distances_maps(distances, x_dim, y_dim):


def plot_homogeneity_map(raw_stack, spots_properties, spots_positions, labels_stack):

nb_of_channels = raw_stack.shape[1]
x_dim = raw_stack.shape[-2]
y_dim = raw_stack.shape[-1]

fig, axes = plt.subplots(
ncols=nb_of_channels, nrows=3, squeeze=False, figsize=(12, 6)
)
fig, axes = plt.subplots(ncols=nb_of_channels, nrows=3, squeeze=False, figsize=(12, 6))

for c in range(nb_of_channels):
weighted_centroid = np.array(
[x["weighted_centroid"][0] for x in spots_properties[c]]
)
weighted_centroid = np.array([x["weighted_centroid"][0] for x in spots_properties[c]])
areas = np.array([x["area"] for x in spots_properties[c]])
max_intensity = np.array([x["max_intensity"] for x in spots_properties[c]])
grid_x, grid_y = np.mgrid[0:x_dim, 0:y_dim]
Expand Down Expand Up @@ -143,12 +136,9 @@ def plot_homogeneity_map(raw_stack, spots_properties, spots_positions, labels_st


def plot_peaks(profiles, peaks, properties, resolutions, res_indexes):
fig, axes = plt.subplots(
ncols=1, nrows=len(profiles), squeeze=False, figsize=(48, 24)
)
fig, axes = plt.subplots(ncols=1, nrows=len(profiles), squeeze=False, figsize=(48, 24))

for c, profile in enumerate(profiles):

ax = axes.ravel()

ax[c].plot(profile)
Expand Down
50 changes: 8 additions & 42 deletions src/microscopemetrics/plots/argolight.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,7 @@ def plot_homogeneity_map(self, image):
x_dim = image.getSizeX()
y_dim = image.getSizeY()

tables = self.get_tables(
image, namespace_start="metrics", name_filter="properties"
)
tables = self.get_tables(image, namespace_start="metrics", name_filter="properties")
if len(tables) != 1:
raise Exception(
"There are none or more than one properties tables. Verify data integrity."
Expand Down Expand Up @@ -69,12 +67,7 @@ def plot_homogeneity_map(self, image):
),
)
max_intensity = np.array(
[
val
for col in data.columns
for val in col.values
if col.name == "max_intensity"
]
[val for col in data.columns for val in col.values if col.name == "max_intensity"]
)
integrated_intensity = np.array(
[
Expand Down Expand Up @@ -165,9 +158,7 @@ def plot_distances_map(self, image):
col_names = [c.name for c in table.getHeaders()]

# We need the positions too
pos_tables = get_tables(
image, namespace_start="metrics", name_filter="properties"
)
pos_tables = get_tables(image, namespace_start="metrics", name_filter="properties")
if len(tables) != 1:
raise Exception(
"There are none or more than one positions tables. Verify data integrity."
Expand Down Expand Up @@ -205,12 +196,7 @@ def plot_distances_map(self, image):
)

mask_labels = np.array(
[
val
for col in pos_data.columns
for val in col.values
if col.name == "mask_labels"
]
[val for col in pos_data.columns for val in col.values if col.name == "mask_labels"]
)
x_positions = np.array(
[
Expand Down Expand Up @@ -251,36 +237,16 @@ def plot_distances_map(self, image):
)
labels_map += 1 # Mask labels are augmented by one as 0 is background
distances_map_3d = np.array(
[
val
for col in data.columns
for val in col.values
if col.name == "distance_3d"
]
[val for col in data.columns for val in col.values if col.name == "distance_3d"]
)
distances_map_x = np.array(
[
val
for col in data.columns
for val in col.values
if col.name == "distance_x"
]
[val for col in data.columns for val in col.values if col.name == "distance_x"]
)
distances_map_y = np.array(
[
val
for col in data.columns
for val in col.values
if col.name == "distance_y"
]
[val for col in data.columns for val in col.values if col.name == "distance_y"]
)
distances_map_z = np.array(
[
val
for col in data.columns
for val in col.values
if col.name == "distance_z"
]
[val for col in data.columns for val in col.values if col.name == "distance_z"]
)

filtered_positions = positions_map[
Expand Down
1 change: 1 addition & 0 deletions src/microscopemetrics/plots/field_illum.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ def get_norm_intensity_profile(img, save_path=""):

return fig


def get_intensity_plot(img, save_path=""):
"""
get the distribution of pixel intensities of the mid
Expand Down
5 changes: 2 additions & 3 deletions src/microscopemetrics/samples/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@

import logging
from abc import ABC, abstractmethod
from typing import List, Union, Dict

import numpy as np
from typing import Dict, List, Union

import microscopemetrics_schema.datamodel as mm_schema
import numpy as np

# We are defining some global dictionaries to register the different analysis types
IMAGE_ANALYSIS_REGISTRY = {}
Expand Down
10 changes: 7 additions & 3 deletions src/microscopemetrics/samples/argolight.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from itertools import product
from typing import Any, Dict, List, Tuple, Union

import microscopemetrics_schema.datamodel as mm_schema
import numpy as np
import pandas as pd
from numpy import float64, int64, ndarray
Expand All @@ -11,7 +12,6 @@
from scipy.signal import find_peaks
from skimage.transform import hough_line # hough_line_peaks, probabilistic_hough_line

import microscopemetrics_schema.datamodel as mm_schema
from microscopemetrics.analysis.tools import (
compute_distances_matrix,
compute_spots_properties,
Expand Down Expand Up @@ -108,9 +108,13 @@ def run(self) -> bool:
ch_properties_kv["channel"] = ch
ch_properties_kv["nr_of_spots"] = len(ch_df)
ch_properties_kv["intensity_max_spot"] = ch_df["integrated_intensity"].max().item()
ch_properties_kv["intensity_max_spot_roi"] = ch_df["integrated_intensity"].argmax().item()
ch_properties_kv["intensity_max_spot_roi"] = (
ch_df["integrated_intensity"].argmax().item()
)
ch_properties_kv["intensity_min_spot"] = ch_df["integrated_intensity"].min().item()
ch_properties_kv["intensity_min_spot_roi"] = ch_df["integrated_intensity"].argmin().item()
ch_properties_kv["intensity_min_spot_roi"] = (
ch_df["integrated_intensity"].argmin().item()
)
ch_properties_kv["mean_intensity"] = ch_df["integrated_intensity"].mean().item()
ch_properties_kv["median_intensity"] = ch_df["integrated_intensity"].median().item()
ch_properties_kv["std_mean_intensity"] = ch_df["integrated_intensity"].std().item()
Expand Down
4 changes: 1 addition & 3 deletions src/microscopemetrics/samples/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,7 @@ def __init__(self, config=None):
"laser_power_measurement": self.analyze_laser_power_measurement,
}
self.configurator = DatasetConfigurator(config)
super().__init__(
config=config, dataset_analysis_to_func=dataset_analysis_to_func
)
super().__init__(config=config, dataset_analysis_to_func=dataset_analysis_to_func)

@staticmethod
def analyze_laser_power_measurement(dataset, config):
Expand Down
2 changes: 1 addition & 1 deletion src/microscopemetrics/samples/field_illumination.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
from datetime import datetime
from typing import Dict, Tuple

import microscopemetrics_schema.datamodel as mm_schema
import numpy as np
import scipy
from skimage.filters import gaussian
from skimage.measure import regionprops

import microscopemetrics_schema.datamodel as mm_schema
from microscopemetrics.samples import AnalysisMixin, logger, numpy_to_inlined_image
from microscopemetrics.utilities.utilities import is_saturated

Expand Down
1 change: 0 additions & 1 deletion src/microscopemetrics/samples/psf_beads.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,6 @@ def _analyze_bead(image):

@staticmethod
def _find_beads(image, min_distance, sigma=None):

image = np.squeeze(image)
image_mip = np.max(image, axis=0)

Expand Down
1 change: 0 additions & 1 deletion src/microscopemetrics/utilities/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ def multi_airy_fun(x: ndarray, *params) -> ndarray:


def wavelength_to_rgb(wavelength, gamma=0.8):

"""
Copied from https://www.noah.org/wiki/Wavelength_to_RGB_in_Python
This converts a given wavelength of light to an
Expand Down
6 changes: 4 additions & 2 deletions tests/test_utilities.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from tests.constants import TEST_DATA_DIR
from os import path
from urllib.parse import urlparse

import requests
from os import path

from tests.constants import TEST_DATA_DIR


def get_file(file_url):
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/schema/test_core_schema.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from typing import List

import microscopemetrics_schema.datamodel as mm_schema
import numpy as np
import pytest
from linkml_runtime.dumpers import YAMLDumper
from linkml_runtime.loaders import YAMLLoader

import microscopemetrics_schema.datamodel as mm_schema
from microscopemetrics.samples import numpy_to_inlined_image, numpy_to_inlined_mask


Expand Down

0 comments on commit 8746116

Please sign in to comment.