Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bugfix: add_labels_from_dataframe #114

Merged
merged 1 commit into from
Jan 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions spatialproteomics/la/label.py
Original file line number Diff line number Diff line change
Expand Up @@ -827,6 +827,7 @@ def add_labels_from_dataframe(
assert (
Layers.NEIGHBORHOODS not in self._obj
), f"Already found neighborhoods in the object. Since these are dependent on the labels, please remove them with pp.drop_layers('{Layers.NEIGHBORHOODS}') before adding new labels."
assert self._obj.coords[Dims.CELLS].shape[0] != 0, "No cells found in the object. Cannot add labels."

if df is None:
cells = self._obj.coords[Dims.CELLS].values
Expand All @@ -835,6 +836,11 @@ def add_labels_from_dataframe(
unique_labels = np.unique(formated_labels)
else:
sub = df.loc[:, [cell_col, label_col]].dropna()
# removing cells that are not in the object
sub = sub[sub[cell_col].isin(self._obj.coords[Dims.CELLS].values)]
assert (
sub.shape[0] != 0
), f"Could not find any overlap between the cells in the data frame's {cell_col} column and the cells in the object. Please make sure the cells for which you want to add labels are present in the object."
cells = sub.loc[:, cell_col].to_numpy().squeeze()
labels = sub.loc[:, label_col].to_numpy().squeeze()

Expand Down Expand Up @@ -868,13 +874,6 @@ def add_labels_from_dataframe(
name=Layers.OBS,
)

da = da.where(
da.coords[Dims.CELLS].isin(
self._obj.coords[Dims.CELLS],
),
drop=True,
)

obj = self._obj.copy()
obj = xr.merge([obj.sel(cells=da.cells), da])

Expand Down
18 changes: 18 additions & 0 deletions tests/la/test_add_labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,24 @@ def test_add_labels_from_dataframe_unassigned_cells(dataset):
assert 1 in labeled[Layers.OBS].sel(features=Features.LABELS).values


def test_add_labels_from_dataframe_invalid_cells(dataset):
# creating a dummy data frame
cells = dataset.coords[Dims.CELLS].values
num_cells = len(cells)
df = pd.DataFrame(
{
"cell": [num_cells + 5],
"label": ["CT1"],
}
)

with pytest.raises(
AssertionError,
match="Could not find any overlap between the cells in the data frame",
):
dataset.la.add_labels_from_dataframe(df)


def test_add_labels(dataset):
# creating a dummy dict
cells = dataset.coords[Dims.CELLS].values
Expand Down
Loading