Skip to content

Commit

Permalink
use flake8 and pre-commit
Browse files Browse the repository at this point in the history
  • Loading branch information
quentinblampey committed Feb 9, 2024
1 parent c487bd3 commit 9287924
Show file tree
Hide file tree
Showing 22 changed files with 124 additions and 24 deletions.
20 changes: 20 additions & 0 deletions .flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[flake8]
max-line-length = 100
ignore =
# line break before a binary operator -> black does not adhere to PEP8
W503
# line break occured after a binary operator -> black does not adhere to PEP8
W504
# line too long -> we accept long comment lines; black gets rid of long code lines
E501
# whitespace before : -> black does not adhere to PEP8
E203
# leading '#' are fine if not used too often
E266
# it can be more convenient to use a bare 'except'
E722
exclude = .git,__pycache__
per-file-ignores =
tests/*: D
*/__init__.py: F401
sopa/main.py: F401
30 changes: 30 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
fail_fast: false
default_language_version:
python: python3
default_stages:
- commit
- push
minimum_pre_commit_version: 2.16.0
repos:
- repo: https://github.com/psf/black
rev: 24.1.1
hooks:
- id: black
- repo: https://github.com/PyCQA/isort
rev: 5.13.2
hooks:
- id: isort
- repo: https://github.com/PyCQA/flake8
rev: 7.0.0
hooks:
- id: flake8
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: debug-statements
- id: double-quote-string-fixer
- id: name-tests-test
- id: requirements-txt-fixer
56 changes: 55 additions & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ tangram-sc = { version = "^1.0.4", optional = true }

snakemake = { version = "^7.32.4,<8.1.3", optional = true }
pulp = { version = ">=2.3.1,<2.8", optional = true }
flake8 = {version = "^7.0.0", extras = ["dev"]}

[tool.poetry.extras]
cellpose = ["cellpose", "opencv-python", "torch"]
Expand Down
2 changes: 1 addition & 1 deletion sopa/annotation/tangram/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def pp_adata(self, ad_sp_: AnnData, ad_sc_: AnnData, split: np.ndarray) -> AnnDa

assert len(
selection
), f"No gene in common between the reference and the spatial adata object. Have you run transcript aggregation?"
), "No gene in common between the reference and the spatial adata object. Have you run transcript aggregation?"
log.info(f"Keeping {len(selection)} shared genes")

for ad_ in [ad_sp_split, ad_sc_]:
Expand Down
2 changes: 1 addition & 1 deletion sopa/cli/annotate.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def fluorescence(

sdata = read_zarr_standardized(sdata_path)

assert sdata.table is not None, f"Annotation requires `sdata.table` to be not None"
assert sdata.table is not None, "Annotation requires `sdata.table` to be not None"

higher_z_score(sdata.table, marker_cell_dict, cell_type_key)
sdata.table.write_zarr(Path(sdata_path) / "table" / "table")
Expand Down
4 changes: 2 additions & 2 deletions sopa/cli/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,15 @@ def reference(

def _get(config, *args):
for arg in args:
if not arg in config:
if arg not in config:
return False
config = config[arg]
return config


def _check_dict(config: dict, d: dict, log, prefix: str = "config"):
for key, values in d.items():
if not key in config:
if key not in config:
log.warn(f"Required config key {prefix}['{key}'] not found")
elif isinstance(values, dict):
_check_dict(config[key], values, log, f"{prefix}['{key}']")
Expand Down
2 changes: 0 additions & 2 deletions sopa/cli/patchify.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,6 @@ def baysor(
),
):
"""Prepare the patches for Baysor segmentation"""
from pathlib import Path

from sopa._constants import SopaFiles, SopaKeys
from sopa._sdata import get_key
from sopa.io.standardize import read_zarr_standardized, sanity_check
Expand Down
2 changes: 1 addition & 1 deletion sopa/cli/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
def _check_zip(names: list[str]):
for name in names:
if isinstance(name, str):
assert name.endswith(".zip"), f"Intermediate files names must end with .zip"
assert name.endswith(".zip"), "Intermediate files names must end with .zip"


def _default_boundary_dir(sdata_path: str, directory_name: str):
Expand Down
1 change: 0 additions & 1 deletion sopa/io/explorer/_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,6 @@ def experiment_dict(run_name: str, region_name: str, num_cells: int, pixel_size:
"instrument_sn": "N/A",
"instrument_sw_version": "N/A",
"analysis_sw_version": "xenium-1.3.0.5",
"experiment_uuid": "",
"cassette_uuid": "",
"roi_uuid": "",
"z_step_size": 3.0,
Expand Down
4 changes: 2 additions & 2 deletions sopa/io/explorer/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
def _check_explorer_directory(path: Path):
assert (
not path.exists() or path.is_dir()
), f"A path to an existing file was provided. It should be a path to a directory."
), "A path to an existing file was provided. It should be a path to a directory."
path.mkdir(parents=True, exist_ok=True)


Expand All @@ -33,7 +33,7 @@ def _should_save(mode: str | None, character: str):
assert len(mode) and mode[0] in [
"-",
"+",
], f"Mode should be a string that starts with '+' or '-'"
], "Mode should be a string that starts with '+' or '-'"

return character in mode if mode[0] == "+" else character not in mode

Expand Down
2 changes: 1 addition & 1 deletion sopa/io/explorer/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def _set_colors(channel_names: list[str]) -> list[str]:
]
valid_colors = [c for c in ExplorerConstants.COLORS if c != ExplorerConstants.NUCLEUS_COLOR]
n_missing = sum(
not is_wavelength and not c in ExplorerConstants.KNOWN_CHANNELS
not is_wavelength and c not in ExplorerConstants.KNOWN_CHANNELS
for c, is_wavelength in zip(channel_names, existing_wavelength)
)
colors_iterator: list = np.repeat(valid_colors, ceil(n_missing / len(valid_colors))).tolist()
Expand Down
2 changes: 1 addition & 1 deletion sopa/io/explorer/shapes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import zarr
from shapely.geometry import Polygon

from ._constants import ExplorerConstants, FileNames, cell_summary_attrs, group_attrs
from ._constants import FileNames, cell_summary_attrs, group_attrs
from .utils import explorer_file_path

log = logging.getLogger(__name__)
Expand Down
2 changes: 1 addition & 1 deletion sopa/io/imaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ def ome_tif(path: Path, as_image: bool = False) -> SpatialImage | SpatialData:
image: da.Array = imread(path)

if image.ndim == 4:
assert image.shape[0] == 1, f"4D images not supported"
assert image.shape[0] == 1, "4D images not supported"
image = da.moveaxis(image[0], 2, 0)
log.info(f"Transformed 4D image into a 3D image of shape (c, y, x) = {image.shape}")
elif image.ndim != 3:
Expand Down
4 changes: 2 additions & 2 deletions sopa/io/report/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def __init__(self, sdata: SpatialData):
self.sdata = sdata

def _table_has(self, key, default=False):
if not SopaKeys.UNS_KEY in self.sdata.table.uns:
if SopaKeys.UNS_KEY not in self.sdata.table.uns:
return default
return self.sdata.table.uns[SopaKeys.UNS_KEY].get(key, default)

Expand All @@ -70,7 +70,7 @@ def general_section(self):
"SpatialData information",
[
Paragraph(
f"Sopa is using <a href='https://spatialdata.scverse.org/en/latest/'>SpatialData</a> under the hood. This is how the object looks like:"
"Sopa is using <a href='https://spatialdata.scverse.org/en/latest/'>SpatialData</a> under the hood. This is how the object looks like:"
),
CodeBlock(str(self.sdata)),
],
Expand Down
2 changes: 1 addition & 1 deletion sopa/io/standardize.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
def sanity_check(sdata: SpatialData, delete_table: bool = False, warn: bool = False):
assert (
len(sdata.images) > 0
), f"The spatialdata object has no image. Sopa is not designed for this."
), "The spatialdata object has no image. Sopa is not designed for this."

if len(sdata.images) != 1:
message = f"The spatialdata object has {len(sdata.images)} images. We advise to run sopa on one image (which can have multiple channels and multiple scales)"
Expand Down
3 changes: 1 addition & 2 deletions sopa/io/transcriptomics.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@
from spatialdata import SpatialData
from spatialdata._logging import logger
from spatialdata.models import Image2DModel, PointsModel, ShapesModel, TableModel
from spatialdata.transformations import Affine, Identity
from spatialdata.transformations.transformations import Identity, Scale
from spatialdata.transformations import Affine, Identity, Scale
from spatialdata_io._constants._constants import MerscopeKeys, XeniumKeys


Expand Down
2 changes: 1 addition & 1 deletion sopa/segmentation/aggregate.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def update_table(

assert (
average_intensities or does_count
), f"You must choose at least one aggregation: transcripts or fluorescence intensities"
), "You must choose at least one aggregation: transcripts or fluorescence intensities"

if gene_column is not None:
if self.table is not None:
Expand Down
2 changes: 1 addition & 1 deletion sopa/segmentation/shapes.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def solve_conflicts(
n_cells = len(cells)
resolved_indices = np.arange(n_cells)

assert n_cells > 0, f"No cells was segmented, cannot continue"
assert n_cells > 0, "No cells was segmented, cannot continue"

tree = shapely.STRtree(cells)
conflicts = tree.query(cells, predicate="intersects")
Expand Down
1 change: 0 additions & 1 deletion sopa/segmentation/stainings.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import geopandas as gpd
import numpy as np
import zarr
from scipy.ndimage import gaussian_filter
from shapely import affinity
from shapely.geometry import Polygon, box
Expand Down
2 changes: 1 addition & 1 deletion sopa/spatial/_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def spatial_neighbors(

assert (
radius is None or len(radius) == 2
), f"Radius is expected to be a tuple (min_radius, max_radius)"
), "Radius is expected to be a tuple (min_radius, max_radius)"

log.info("Computing delaunay graph")

Expand Down
2 changes: 1 addition & 1 deletion sopa/spatial/morpho.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def niches_geometry_stats(
gdf = geometrize_niches(adata, niche_key, **geometrize_niches_kwargs)
value_counts = gdf[niche_key].value_counts()

assert len(gdf), f"No niche geometry found, stats can't be computed"
assert len(gdf), "No niche geometry found, stats can't be computed"

log.info(f"Computing pairwise distances between {len(gdf)} components")
pairwise_distances: pd.DataFrame = gdf.geometry.apply(lambda g: gdf.distance(g))
Expand Down

0 comments on commit 9287924

Please sign in to comment.