Skip to content

Commit

Permalink
Merge branch 'master' into lp-fix
Browse files Browse the repository at this point in the history
  • Loading branch information
dylanclam12 authored Jul 4, 2024
2 parents c6c7540 + 21a6f2c commit 28a7b08
Show file tree
Hide file tree
Showing 13 changed files with 204 additions and 99 deletions.
10 changes: 5 additions & 5 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ name: Python Package Tests

on:
push:
branches: [ master, v2.0 ]
branches: [ master ]
pull_request:
branches: [ master, v2.0 ]
branches: [ master ]

jobs:
build:
Expand All @@ -16,7 +16,7 @@ jobs:
strategy:
matrix:
os : [ubuntu-latest, windows-latest, macos-latest]
python-version: ['3.9', '3.10', '3.11']
python-version: ['3.10', '3.11']
steps:
- uses: actions/[email protected]
- name: Set up Python ${{ matrix.python-version }}
Expand All @@ -26,11 +26,11 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install .[docs]
python -m pip install ".[docs]"
- name: Lint & test coverage
if: ${{ matrix.os == 'ubuntu-latest' && matrix.python-version == '3.10' }}
run: |
pip install flake8
pip install flake8 pytest
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
Expand Down
13 changes: 6 additions & 7 deletions bento/geometry/_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@ def overlay(
)



@singledispatch
def labels_to_shapes(labels: np.ndarray, attrs: dict, bg_value: int = 0):
"""
Expand All @@ -80,7 +79,7 @@ def labels_to_shapes(labels: np.ndarray, attrs: dict, bg_value: int = 0):
-------
GeoPandas DataFrame
GeoPandas DataFrame containing the polygons extracted from the labeled image.
"""
import rasterio as rio
import shapely.geometry
Expand All @@ -91,8 +90,8 @@ def labels_to_shapes(labels: np.ndarray, attrs: dict, bg_value: int = 0):
shapes = gpd.GeoDataFrame(
polygons[:, 1], geometry=gpd.GeoSeries(polygons[:, 0]).T, columns=["id"]
)
shapes = shapes[shapes["id"] != bg_value] # Ignore background
shapes = shapes[shapes["id"] != bg_value] # Ignore background

# Validate for SpatialData
sd_shape = ShapesModel.parse(shapes)
sd_shape.attrs = attrs
Expand All @@ -112,13 +111,13 @@ def _(labels: SpatialImage, attrs: dict, bg_value: int = 0):
Dictionary of attributes to set for the SpatialData object.
bg_value : int, optional
Value of the background pixels, by default 0
Returns
-------
GeoPandas DataFrame
GeoPandas DataFrame containing the polygons extracted from the labeled image.
"""

# Convert spatial_image.SpatialImage to np.ndarray
labels = labels.values
return labels_to_shapes(labels, attrs, bg_value)
return labels_to_shapes(labels, attrs, bg_value)
10 changes: 7 additions & 3 deletions bento/tools/_composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ def comp(sdata: SpatialData, points_key: str, shape_names: list):
sdata : spatialdata.SpatialData
Updates `sdata.table.uns` with average gene compositions for each shape.
"""
points = get_points(sdata,points_key=points_key, astype="pandas")
points = get_points(sdata, points_key=points_key, astype="pandas")

instance_key = get_instance_key(sdata)
feature_key = get_feature_key(sdata)
Expand All @@ -86,7 +86,9 @@ def comp(sdata: SpatialData, points_key: str, shape_names: list):
sdata.table.uns["comp_stats"] = comp_stats


def comp_diff(sdata: SpatialData, points_key: str, shape_names: list, groupby: str, ref_group: str):
def comp_diff(
sdata: SpatialData, points_key: str, shape_names: list, groupby: str, ref_group: str
):
"""Calculate the average difference in gene composition for shapes across batches of cells. Uses the Wasserstein distance.
Parameters
Expand All @@ -109,7 +111,9 @@ def comp_diff(sdata: SpatialData, points_key: str, shape_names: list, groupby: s
# Get average gene compositions for each batch
comp_stats = dict()
for group, pt_group in points.groupby(groupby):
comp_stats[group] = _get_compositions(pt_group, shape_names, instance_key=instance_key, feature_key=feature_key)
comp_stats[group] = _get_compositions(
pt_group, shape_names, instance_key=instance_key, feature_key=feature_key
)

ref_comp = comp_stats[ref_group]

Expand Down
15 changes: 6 additions & 9 deletions bento/tools/_flux.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,26 +497,23 @@ def fluxmap(
columns=["fluxmap"],
)

# Add back offsets
shapes["geometry"] = shapes["geometry"].translate(x_offset, y_offset)

# Remove background shape
shapes["fluxmap"] = shapes["fluxmap"].astype(int)
shapes = shapes[shapes["fluxmap"] != 0]

# Group same fields as MultiPolygons
shapes = shapes.dissolve("fluxmap")["geometry"]

# Upscale to match original resolution, shift back to original coordinates
shapes = shapes.scale(xfact=1 / res, yfact=1 / res, origin=(0, 0)).translate(
x_offset, y_offset
)

fluxmap_df[cell] = shapes

fluxmap_df = pd.DataFrame.from_dict(fluxmap_df).T
fluxmap_df.columns = "fluxmap" + fluxmap_df.columns.astype(str)

# Upscale to match original resolution
fluxmap_df = fluxmap_df.apply(
lambda col: gpd.GeoSeries(col).scale(
xfact=1 / res, yfact=1 / res, origin=(0, 0)
)
)
pbar.update()

pbar.set_description("Saving")
Expand Down
5 changes: 1 addition & 4 deletions bento/tools/_flux_enrichment.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,13 +99,10 @@ def fe(
cell_raster = get_points(
sdata, points_key=f"{instance_key}_raster", astype="pandas", sync=False
)[features]
cell_raster_matrix = np.mat(cell_raster)
mat = sparse.csr_matrix(cell_raster_matrix) # sparse matrix in csr format

samples = cell_raster.index.astype(str)

enrichment = dc.run_wsum(
mat=[mat, samples, features],
mat=cell_raster,
net=net,
source=source,
target=target,
Expand Down
12 changes: 6 additions & 6 deletions bento/tools/_point_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,12 @@ def analyze_points(
for shape in list(
set(obs_attrs).intersection(set([x for x in shape_keys if x != instance_key]))
):
points_df = (
points_df.join(
sdata.shapes[shape].set_index(instance_key), on=instance_key, lsuffix="", rsuffix=f"_{shape}"
)
.rename(columns={shape: f"{shape}_index", f"geometry_{shape}": shape})
)
points_df = points_df.join(
sdata.shapes[shape].set_index(instance_key),
on=instance_key,
lsuffix="",
rsuffix=f"_{shape}",
).rename(columns={shape: f"{shape}_index", f"geometry_{shape}": shape})

# Pull cell_boundaries shape features into the points dataframe
points_df = (
Expand Down
Loading

0 comments on commit 28a7b08

Please sign in to comment.