Skip to content

Commit 6b270c9

Browse files
DiDeoxyMax Hargreaves
andauthored
Change: formatted and reconfigured zarr imports for zarr 3 (#42)
* Change: formatted and reconfigured imports for zarr 3 * Change: reverse superfluous formatting --------- Co-authored-by: Max Hargreaves <hargreaves.max@gene.com>
1 parent cc3fb55 commit 6b270c9

14 files changed

Lines changed: 211 additions & 151 deletions

setup.cfg

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ install_requires =
5858
tiledb-vector-search>=0.11.0
5959
torch>=1.10.1
6060
tqdm
61-
zarr>=2.6.1,<3.0.0
61+
zarr>=2.6.1
6262
importlib-metadata; python_version<"3.8"
6363

6464
[options.packages.find]

setup.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
"""
2-
Setup file for scimilarity.
3-
Use setup.cfg to configure your project.
2+
Setup file for scimilarity.
3+
Use setup.cfg to configure your project.
44
5-
This file was generated with PyScaffold 4.5.
6-
PyScaffold helps you to put up the scaffold of your new Python project.
7-
Learn more under: https://pyscaffold.org/
5+
This file was generated with PyScaffold 4.5.
6+
PyScaffold helps you to put up the scaffold of your new Python project.
7+
Learn more under: https://pyscaffold.org/
88
"""
9+
910
from setuptools import setup
1011

1112
if __name__ == "__main__":

src/scimilarity/anndata_data_models.py

Lines changed: 33 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import pytorch_lightning as pl
55
import torch
66
from torch.utils.data import Dataset, DataLoader, WeightedRandomSampler
7-
from typing import Optional
7+
from typing import Optional, TYPE_CHECKING
88

99
from .utils import align_dataset
1010
from .ontologies import (
@@ -13,8 +13,21 @@
1313
find_most_viable_parent,
1414
)
1515

16+
if TYPE_CHECKING:
17+
import numpy
18+
from numpy.typing import NDArray
19+
from typing import Any
1620

17-
class scDataset(Dataset):
21+
Index = (
22+
NDArray[numpy.integer[Any]]
23+
| NDArray[numpy.bool_]
24+
| tuple[NDArray[numpy.integer[Any]] | NDArray[numpy.bool_], ...]
25+
)
26+
27+
28+
class scDataset(
29+
Dataset[tuple["numpy.ndarray", "numpy.ndarray", Optional["numpy.ndarray"]]]
30+
):
1831
"""A class that represents a single cell dataset.
1932
2033
Parameters
@@ -27,17 +40,28 @@ class scDataset(Dataset):
2740
The study identifier for every cell.
2841
"""
2942

30-
def __init__(self, X, Y, study=None):
43+
def __init__(
44+
self,
45+
X: "numpy.ndarray",
46+
Y: "numpy.ndarray",
47+
study: Optional["numpy.ndarray"] = None,
48+
):
3149
self.X = X
3250
self.Y = Y
3351
self.study = study
3452

35-
def __len__(self):
53+
def __len__(self) -> int:
3654
return len(self.Y)
3755

38-
def __getitem__(self, idx):
56+
def __getitem__(
57+
self, idx: "Index"
58+
) -> tuple["numpy.ndarray", "numpy.ndarray", Optional["numpy.ndarray"]]:
3959
# data, label, study
40-
return self.X[idx].toarray().flatten(), self.Y[idx], self.study[idx]
60+
return (
61+
self.X[idx].toarray().flatten(),
62+
self.Y[idx],
63+
self.study[idx] if self.study is not None else None,
64+
)
4165

4266

4367
class scCollator:
@@ -51,11 +75,7 @@ class scCollator:
5175
Use sparse matrices.
5276
"""
5377

54-
def __init__(
55-
self,
56-
label2int: dict,
57-
sparse: bool = False,
58-
):
78+
def __init__(self, label2int: dict, sparse: bool = False):
5979
self.label2int = label2int
6080
self.sparse = sparse
6181

@@ -65,11 +85,8 @@ def __call__(self, batch):
6585
X = torch.squeeze(torch.Tensor(np.vstack(profiles)))
6686
if self.sparse:
6787
X = X.to_sparse()
68-
return (
69-
X,
70-
torch.Tensor([self.label2int[l] for l in labels]),
71-
np.array(studies),
72-
)
88+
89+
return (X, torch.Tensor([self.label2int[l] for l in labels]), np.array(studies))
7390

7491

7592
class MetricLearningDataModule(pl.LightningDataModule):

src/scimilarity/cell_annotation.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
1-
from typing import Optional, Union, List, Set, Tuple
1+
from typing import Optional, Union, List, Set, Tuple, TYPE_CHECKING
2+
23

34
from .cell_search_knn import CellSearchKNN
45

6+
if TYPE_CHECKING:
7+
import anndata
8+
import numpy
9+
import pandas
10+
511

612
class CellAnnotation(CellSearchKNN):
713
"""A class that annotates cells using a cell embedding and then knn search.
@@ -21,10 +27,7 @@ class CellAnnotation(CellSearchKNN):
2127
"""
2228

2329
def __init__(
24-
self,
25-
model_path: str,
26-
use_gpu: bool = False,
27-
filenames: Optional[dict] = None,
30+
self, model_path: str, use_gpu: bool = False, filenames: Optional[dict] = None
2831
):
2932
import os
3033

src/scimilarity/cell_embedding.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
from typing import Optional, Tuple, Union
1+
from typing import Union, TYPE_CHECKING
2+
3+
if TYPE_CHECKING:
4+
import scipy.sparse
5+
import numpy
26

37

48
class CellEmbedding:
@@ -112,9 +116,9 @@ def get_embeddings(
112116
if (
113117
(isinstance(X, csr_matrix) or isinstance(X, csc_matrix))
114118
and (
115-
isinstance(X.data, zarr.core.Array)
116-
or isinstance(X.indices, zarr.core.Array)
117-
or isinstance(X.indptr, zarr.core.Array)
119+
isinstance(X.data, zarr.Array)
120+
or isinstance(X.indices, zarr.Array)
121+
or isinstance(X.indptr, zarr.Array)
118122
)
119123
and num_cells <= buffer_size
120124
):
@@ -141,7 +145,7 @@ def get_embeddings(
141145
embedding_parts.append(self.model(profiles))
142146

143147
if not embedding_parts:
144-
raise RuntimeError(f"No valid cells detected.")
148+
raise RuntimeError("No valid cells detected.")
145149

146150
if self.use_gpu:
147151
# detach, move from gpu into cpu, return as numpy array
@@ -151,6 +155,6 @@ def get_embeddings(
151155
embedding = torch.vstack(embedding_parts).detach().numpy()
152156

153157
if np.isnan(embedding).any():
154-
raise RuntimeError(f"NaN detected in embeddings.")
158+
raise RuntimeError("NaN detected in embeddings.")
155159

156160
return embedding

src/scimilarity/cell_query.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
1-
from typing import Dict, List, Optional, Tuple, Union, Set
1+
from typing import Dict, List, Optional, Tuple, Union, TYPE_CHECKING
22

33
from .cell_search_knn import CellSearchKNN
44

5+
if TYPE_CHECKING:
6+
import anndata
7+
import numpy
8+
import pandas
9+
510

611
class CellQuery(CellSearchKNN):
712
"""A class that searches for similar cells using a cell embedding.
@@ -39,8 +44,6 @@ def __init__(
3944
load_knn: bool = True,
4045
):
4146
import os
42-
import numpy as np
43-
import pandas as pd
4447
import tiledb
4548

4649
super().__init__(
@@ -340,7 +343,7 @@ def search_centroid_nearest(
340343

341344
import numpy as np
342345
from scipy.cluster.vq import kmeans
343-
from .utils import get_centroid, get_dist2centroid
346+
from .utils import get_centroid
344347

345348
cells = adata[adata.obs[centroid_key] == 1].copy()
346349
centroid = get_centroid(cells.layers["counts"])
@@ -623,7 +626,7 @@ def search_centroid_exhaustive(
623626

624627
import numpy as np
625628
from scipy.cluster.vq import kmeans
626-
from .utils import get_centroid, get_dist2centroid
629+
from .utils import get_centroid
627630

628631
cells = adata[adata.obs[centroid_key] == 1].copy()
629632
centroid = get_centroid(cells.layers["counts"])

src/scimilarity/cell_search_knn.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
1-
from typing import Optional, Tuple, Union
1+
from typing import Tuple, TYPE_CHECKING
22

33
from .cell_embedding import CellEmbedding
44

5+
if TYPE_CHECKING:
6+
import numpy
7+
58

69
class CellSearchKNN(CellEmbedding):
710
"""A class for searching similar cells using cell embeddings kNN.

src/scimilarity/interpreter.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
11
from torch import nn
2-
from typing import Optional, Union
2+
from typing import Optional, Union, TYPE_CHECKING
3+
4+
if TYPE_CHECKING:
5+
import torch
6+
import numpy
7+
import pandas
8+
import scipy.sparse
39

410

511
class SimpleDist(nn.Module):
@@ -15,11 +21,7 @@ def __init__(self, encoder: "torch.nn.Module"):
1521
super().__init__()
1622
self.encoder = encoder
1723

18-
def forward(
19-
self,
20-
anchors: "torch.Tensor",
21-
negatives: "torch.Tensor",
22-
):
24+
def forward(self, anchors: "torch.Tensor", negatives: "torch.Tensor"):
2325
"""Forward.
2426
2527
Parameters
@@ -55,11 +57,7 @@ class Interpreter:
5557
>>> interpreter = Interpreter(CellEmbedding("/opt/data/model").model)
5658
"""
5759

58-
def __init__(
59-
self,
60-
encoder: "torch.nn.Module",
61-
gene_order: list,
62-
):
60+
def __init__(self, encoder: "torch.nn.Module", gene_order: list):
6361
from captum.attr import IntegratedGradients
6462

6563
self.encoder = encoder

src/scimilarity/ontologies.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import networkx as nx
22
import obonet
33
import pandas as pd
4-
from typing import Union, Tuple, List
4+
from typing import Union, Tuple, List, TYPE_CHECKING
5+
6+
if TYPE_CHECKING:
7+
import pandas
8+
import numpy
59

610

711
def subset_nodes_to_set(nodes, restricted_set: Union[list, set]) -> nx.DiGraph:

src/scimilarity/tiledb_data_models.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import numpy as np
2-
import os, re
2+
import os
33
import pandas as pd
44
import pytorch_lightning as pl
55
from scipy.sparse import coo_matrix, diags
66
import tiledb
77
import torch
88
from torch.utils.data import Dataset, DataLoader, Sampler
9-
from typing import Dict, List, Optional
9+
from typing import Dict, List, Optional, TYPE_CHECKING
1010

1111
from .utils import query_tiledb_df
1212
from .ontologies import (
@@ -19,6 +19,9 @@
1919

2020
log = logging.getLogger(__name__)
2121

22+
if TYPE_CHECKING:
23+
import pandas
24+
2225

2326
class scDataset(Dataset):
2427
"""A class that represents cells in TileDB.
@@ -29,10 +32,7 @@ class scDataset(Dataset):
2932
Pandas dataframe of valid cells.
3033
"""
3134

32-
def __init__(
33-
self,
34-
data_df: "pandas.DataFrame",
35-
):
35+
def __init__(self, data_df: "pandas.DataFrame"):
3636
self.data_df = data_df
3737

3838
def __len__(self):

0 commit comments

Comments
 (0)