cap-anndata 0.2.2__py3-none-any.whl → 0.3.1__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- cap_anndata/__init__.py +10 -10
- cap_anndata/backed_df.py +69 -69
- cap_anndata/backed_dict.py +34 -0
- cap_anndata/cap_anndata.py +600 -287
- cap_anndata/reader.py +57 -44
- {cap_anndata-0.2.2.dist-info → cap_anndata-0.3.1.dist-info}/LICENSE +28 -28
- cap_anndata-0.3.1.dist-info/METADATA +56 -0
- cap_anndata-0.3.1.dist-info/RECORD +10 -0
- {cap_anndata-0.2.2.dist-info → cap_anndata-0.3.1.dist-info}/WHEEL +1 -1
- cap_anndata/backed_uns.py +0 -28
- cap_anndata-0.2.2.dist-info/METADATA +0 -253
- cap_anndata-0.2.2.dist-info/RECORD +0 -10
- {cap_anndata-0.2.2.dist-info → cap_anndata-0.3.1.dist-info}/top_level.txt +0 -0
cap_anndata/reader.py
CHANGED
@@ -1,44 +1,57 @@
|
|
1
|
-
import logging
|
2
|
-
import
|
3
|
-
import
|
4
|
-
|
5
|
-
from cap_anndata import CapAnnData
|
6
|
-
|
7
|
-
|
8
|
-
logger = logging.getLogger(__name__)
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
"""
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
32
|
-
|
33
|
-
|
34
|
-
|
35
|
-
|
36
|
-
|
37
|
-
|
38
|
-
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
|
43
|
-
|
44
|
-
|
1
|
+
import logging
|
2
|
+
import h5py
|
3
|
+
import warnings
|
4
|
+
|
5
|
+
from cap_anndata import CapAnnData
|
6
|
+
|
7
|
+
|
8
|
+
logger = logging.getLogger(__name__)
|
9
|
+
|
10
|
+
|
11
|
+
def read_h5ad(file_path: str, edit: bool = False):
|
12
|
+
"""
|
13
|
+
This is the main read method for CapAnnData.
|
14
|
+
Must be used in 'with' context.
|
15
|
+
"""
|
16
|
+
mode = "r+" if edit else "r"
|
17
|
+
logger.debug(f"Read file {file_path} mode={mode} in context...")
|
18
|
+
|
19
|
+
try:
|
20
|
+
file = h5py.File(file_path, mode)
|
21
|
+
cap_adata = CapAnnData(file)
|
22
|
+
logger.debug(f"Successfully read anndata file path {file_path}")
|
23
|
+
return cap_adata
|
24
|
+
|
25
|
+
except Exception as error:
|
26
|
+
logger.error(
|
27
|
+
f"Error during read anndata file at path: {file_path}, error = {error}!"
|
28
|
+
)
|
29
|
+
raise error
|
30
|
+
|
31
|
+
|
32
|
+
def deprecated(message):
|
33
|
+
def deprecated_decorator(func):
|
34
|
+
def deprecated_func(*args, **kwargs):
|
35
|
+
warnings.warn(
|
36
|
+
"{} is a deprecated function. {}".format(func.__name__, message),
|
37
|
+
category=DeprecationWarning,
|
38
|
+
stacklevel=2,
|
39
|
+
)
|
40
|
+
warnings.simplefilter("default", DeprecationWarning)
|
41
|
+
return func(*args, **kwargs)
|
42
|
+
|
43
|
+
return deprecated_func
|
44
|
+
|
45
|
+
return deprecated_decorator
|
46
|
+
|
47
|
+
|
48
|
+
# TODO: remove deprecated function
|
49
|
+
@deprecated(
|
50
|
+
"It will be removed in the next version of package. Please replace it with `read_h5ad`."
|
51
|
+
)
|
52
|
+
def read_directly(file_path: str, edit: bool = False) -> CapAnnData:
|
53
|
+
"""
|
54
|
+
Must be used only in specific cases.
|
55
|
+
User is responsible to close the h5py file when the work with CapAnnData instance done.
|
56
|
+
"""
|
57
|
+
return read_h5ad(file_path, edit)
|
@@ -1,28 +1,28 @@
|
|
1
|
-
BSD 3-Clause License
|
2
|
-
|
3
|
-
Copyright (c) 2024, R. Mukhin, A. Isaev, Cell-Annotation Platform
|
4
|
-
|
5
|
-
Redistribution and use in source and binary forms, with or without
|
6
|
-
modification, are permitted provided that the following conditions are met:
|
7
|
-
|
8
|
-
1. Redistributions of source code must retain the above copyright notice, this
|
9
|
-
list of conditions and the following disclaimer.
|
10
|
-
|
11
|
-
2. Redistributions in binary form must reproduce the above copyright notice,
|
12
|
-
this list of conditions and the following disclaimer in the documentation
|
13
|
-
and/or other materials provided with the distribution.
|
14
|
-
|
15
|
-
3. Neither the name of the copyright holder nor the names of its
|
16
|
-
contributors may be used to endorse or promote products derived from
|
17
|
-
this software without specific prior written permission.
|
18
|
-
|
19
|
-
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
20
|
-
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
21
|
-
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
22
|
-
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
23
|
-
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
24
|
-
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
25
|
-
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
26
|
-
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
27
|
-
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
28
|
-
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
1
|
+
BSD 3-Clause License
|
2
|
+
|
3
|
+
Copyright (c) 2024, R. Mukhin, A. Isaev, Cell-Annotation Platform
|
4
|
+
|
5
|
+
Redistribution and use in source and binary forms, with or without
|
6
|
+
modification, are permitted provided that the following conditions are met:
|
7
|
+
|
8
|
+
1. Redistributions of source code must retain the above copyright notice, this
|
9
|
+
list of conditions and the following disclaimer.
|
10
|
+
|
11
|
+
2. Redistributions in binary form must reproduce the above copyright notice,
|
12
|
+
this list of conditions and the following disclaimer in the documentation
|
13
|
+
and/or other materials provided with the distribution.
|
14
|
+
|
15
|
+
3. Neither the name of the copyright holder nor the names of its
|
16
|
+
contributors may be used to endorse or promote products derived from
|
17
|
+
this software without specific prior written permission.
|
18
|
+
|
19
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
20
|
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
21
|
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
22
|
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
23
|
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
24
|
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
25
|
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
26
|
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
27
|
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
28
|
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
@@ -0,0 +1,56 @@
|
|
1
|
+
Metadata-Version: 2.1
|
2
|
+
Name: cap_anndata
|
3
|
+
Version: 0.3.1
|
4
|
+
Summary: Partial read/write of AnnData (h5ad) files for low-memory operations with large datasets.
|
5
|
+
Home-page: https://github.com/cellannotation/cap-anndata
|
6
|
+
Author: R. Mukhin, A. Isaev
|
7
|
+
Author-email: roman@ebookapplications.com
|
8
|
+
Project-URL: Bug Tracker, https://github.com/cellannotation/cap-anndata/issues
|
9
|
+
Project-URL: Changelog, https://github.com/cellannotation/cap-anndata/blob/main/CHANGELOG.md
|
10
|
+
Project-URL: Documentation, https://github.com/cellannotation/cap-anndata/blob/main/HOWTO.md
|
11
|
+
Classifier: Programming Language :: Python :: 3.9
|
12
|
+
Classifier: License :: OSI Approved :: BSD License
|
13
|
+
Classifier: Operating System :: OS Independent
|
14
|
+
Requires-Python: >=3.9
|
15
|
+
Description-Content-Type: text/markdown
|
16
|
+
License-File: LICENSE
|
17
|
+
Requires-Dist: numpy >=1.23.5
|
18
|
+
Requires-Dist: pandas >=2.2.0
|
19
|
+
Requires-Dist: anndata >=0.10.0
|
20
|
+
Provides-Extra: dev
|
21
|
+
Requires-Dist: pytest >=8.0.0 ; extra == 'dev'
|
22
|
+
Requires-Dist: setuptools ~=69.1.1 ; extra == 'dev'
|
23
|
+
|
24
|
+
# CAP-AnnData: Partial I/O for AnnData (.h5ad) Files
|
25
|
+
|
26
|
+
## Overview
|
27
|
+
CAP-AnnData offering functionalities for selective reading and writing of [AnnData](https://pypi.org/project/anndata/)
|
28
|
+
file fields without the need for loading entire dataset (or even entire field) into memory.
|
29
|
+
For example, it allows to read and modify the single `obs` column taking nothing into memory except the column itself.
|
30
|
+
Package eager to replicate the original AnnData API as much as possible,
|
31
|
+
while providing additional features for efficient data manipulation for heavy datasets.
|
32
|
+
|
33
|
+
## Installation
|
34
|
+
Install CAP-AnnData via pip:
|
35
|
+
|
36
|
+
```commandline
|
37
|
+
pip install -U cap-anndata
|
38
|
+
```
|
39
|
+
|
40
|
+
## Basic Example
|
41
|
+
|
42
|
+
The example below displayes how to read a single `obs` column, create new obs column and propagate it to the `.h5ad` file.
|
43
|
+
```python
|
44
|
+
from cap_anndata import read_h5ad
|
45
|
+
|
46
|
+
file_path = "your_data.h5ad"
|
47
|
+
with read_h5ad(file_path=file_path, edit=True) as cap_adata:
|
48
|
+
print(cap_adata.obs_keys()) # ['a', 'b', 'c']
|
49
|
+
print(cap_adata.obs) # Empty DataFrame
|
50
|
+
cap_adata.read_obs(columns=['a'])
|
51
|
+
print(cap_adata.obs.columns) # ['a']
|
52
|
+
cap_adata.obs['new_col'] = cap_adata.obs['a']
|
53
|
+
cap_adata.overwrite(fields=['obs'])
|
54
|
+
```
|
55
|
+
|
56
|
+
More example can be found in the [How-TO](https://github.com/cellannotation/cap-anndata/blob/main/HOWTO.md) file.
|
@@ -0,0 +1,10 @@
|
|
1
|
+
cap_anndata/__init__.py,sha256=WRAQEDsWTvLbJWVUA5FmKCVrD2GN4oRd5I3c8jc9ajo,197
|
2
|
+
cap_anndata/backed_df.py,sha256=bMNsArbPjA-TN7eQB4-9Y2l3s8o03-dM4hPnOR9tROc,2622
|
3
|
+
cap_anndata/backed_dict.py,sha256=Hb1SjnKuQ13mBUitQ5sL3kmcQ1j3GgB19r3yXkC0oIo,1019
|
4
|
+
cap_anndata/cap_anndata.py,sha256=uQh49Kwu2cE4-ebgOvb78mMGA_afkZcsr71j6f8EX2I,20600
|
5
|
+
cap_anndata/reader.py,sha256=UpZBCjaS4-K2w_9m6IuYetO9LwmEEJ5KvAw9aAoMRno,1609
|
6
|
+
cap_anndata-0.3.1.dist-info/LICENSE,sha256=XXTH6JikkxH7Gqy9VEj4crSizuwxzv04ROzkQ-ZS6o4,1532
|
7
|
+
cap_anndata-0.3.1.dist-info/METADATA,sha256=688YuF45IuOvu1Hqxbt_O1aeYkoMX4tjV0b2hb1WY8I,2304
|
8
|
+
cap_anndata-0.3.1.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
|
9
|
+
cap_anndata-0.3.1.dist-info/top_level.txt,sha256=GKi_Uk4LUhXwWBfFCTIyJvEoJqFREt_4uH4CWgeLsg4,12
|
10
|
+
cap_anndata-0.3.1.dist-info/RECORD,,
|
cap_anndata/backed_uns.py
DELETED
@@ -1,28 +0,0 @@
|
|
1
|
-
from typing import List, Any
|
2
|
-
|
3
|
-
|
4
|
-
class CapAnnDataUns(dict):
|
5
|
-
__keys_to_remove: List[str] = []
|
6
|
-
|
7
|
-
def __delitem__(self, __key: Any) -> None:
|
8
|
-
self.__keys_to_remove.append(__key)
|
9
|
-
return super().__delitem__(__key)
|
10
|
-
|
11
|
-
def __setitem__(self, __key: Any, __value: Any) -> None:
|
12
|
-
if __key in self.__keys_to_remove:
|
13
|
-
self.__keys_to_remove.remove(__key)
|
14
|
-
return super().__setitem__(__key, __value)
|
15
|
-
|
16
|
-
@property
|
17
|
-
def keys_to_remove(self):
|
18
|
-
return self.__keys_to_remove
|
19
|
-
|
20
|
-
def pop(self, __key: Any, __default: Any = None) -> Any:
|
21
|
-
if __key in self:
|
22
|
-
self.__keys_to_remove.append(__key)
|
23
|
-
return super().pop(__key, __default)
|
24
|
-
|
25
|
-
def popitem(self) -> Any:
|
26
|
-
item = super().popitem()
|
27
|
-
self.__keys_to_remove.append(item[0])
|
28
|
-
return item
|
@@ -1,253 +0,0 @@
|
|
1
|
-
Metadata-Version: 2.1
|
2
|
-
Name: cap_anndata
|
3
|
-
Version: 0.2.2
|
4
|
-
Summary: Partial read/write of AnnData (h5ad) files for low-memory operations with large datasets.
|
5
|
-
Home-page: https://github.com/cellannotation/cap-anndata
|
6
|
-
Author: R. Mukhin, A. Isaev
|
7
|
-
Author-email: roman@ebookapplications.com
|
8
|
-
Project-URL: Bug Tracker, https://github.com/cellannotation/cap-anndata/issues
|
9
|
-
Classifier: Programming Language :: Python :: 3.9
|
10
|
-
Classifier: License :: OSI Approved :: BSD License
|
11
|
-
Classifier: Operating System :: OS Independent
|
12
|
-
Requires-Python: >=3.9
|
13
|
-
Description-Content-Type: text/markdown
|
14
|
-
License-File: LICENSE
|
15
|
-
Requires-Dist: numpy ~=1.26.3
|
16
|
-
Requires-Dist: pandas ~=2.2.0
|
17
|
-
Requires-Dist: anndata ~=0.10.5
|
18
|
-
Requires-Dist: h5py ~=3.5.0
|
19
|
-
Provides-Extra: dev
|
20
|
-
Requires-Dist: pytest >=8.0.0 ; extra == 'dev'
|
21
|
-
Requires-Dist: setuptools ~=69.1.1 ; extra == 'dev'
|
22
|
-
|
23
|
-
# CAP-AnnData: Enhanced Partial I/O for AnnData Files
|
24
|
-
|
25
|
-
## Overview
|
26
|
-
CAP-AnnData enriches the AnnData ecosystem by offering tailored functionalities for partial reading and writing of AnnData files. This enhancement allows for selective manipulation of sections such as `obs`, `var`, `X`, `raw.X`, `obsm`, and `uns` without the need for loading entire datasets into memory. Leveraging AnnData's native methods, CAP-AnnData aims to maintain backward compatibility while improving efficiency, especially useful for large-scale single-cell genomics data.
|
27
|
-
|
28
|
-
## Getting Started
|
29
|
-
|
30
|
-
### Installation
|
31
|
-
Install CAP-AnnData via pip:
|
32
|
-
|
33
|
-
```commandline
|
34
|
-
pip install -U cap-anndata
|
35
|
-
```
|
36
|
-
|
37
|
-
### Running Tests
|
38
|
-
Ensure the integrity and reliability of CAP-AnnData on your system by running the unit tests via `pytest` from the root of the repo.
|
39
|
-
|
40
|
-
```commandline
|
41
|
-
pip install pytest
|
42
|
-
pytest test
|
43
|
-
```
|
44
|
-
|
45
|
-
Make sure Python 3.9 or newer is used, along with all requirements specified in requirements.txt
|
46
|
-
|
47
|
-
## How-TO:
|
48
|
-
|
49
|
-
#### 1. Access AnnData File DataFrames
|
50
|
-
|
51
|
-
##### Basic Reading
|
52
|
-
By default, `CapAnnData` does not automatically read any data. To begin working with dataframes, you need to explicitly read the data from the AnnData file. You can read the entire dataframe or select specific columns. For partial reading, provide a list of column names.
|
53
|
-
|
54
|
-
```python
|
55
|
-
from cap_anndata import read_h5ad
|
56
|
-
|
57
|
-
file_path = "your_data.h5ad"
|
58
|
-
with read_h5ad(file_path=file_path, edit=False) as cap_adata:
|
59
|
-
# Get the list of all obs columns in AnnData file
|
60
|
-
cap_adata.obs_keys() # ['a', 'b', 'c']
|
61
|
-
# Read all columns of 'obs'
|
62
|
-
cap_adata.read_obs()
|
63
|
-
# Get the list of columns of DataFrame in memory
|
64
|
-
cap_adata.obs.columns # ['a', 'b', 'c']
|
65
|
-
|
66
|
-
# Get the list of all var columns in AnnData file
|
67
|
-
cap_adata.var_keys() # ['d', 'e', 'f']
|
68
|
-
# Read specific columns of 'var'
|
69
|
-
cap_adata.read_var(columns=['d'])
|
70
|
-
cap_adata.var.columns # ['d']
|
71
|
-
# Read additional column
|
72
|
-
cap_adata.read_var(columns=['e'])
|
73
|
-
cap_adata.var.columns # ['d', 'e']
|
74
|
-
|
75
|
-
# Read column and reset the in-memory DataFrame before that
|
76
|
-
cap_adata.read_var(columns=['f'], reset=True)
|
77
|
-
cap_adata.var.columns # ['f']
|
78
|
-
|
79
|
-
# Read no columns of raw.var (only the index)
|
80
|
-
cap_adata.raw.read_var(columns=[])
|
81
|
-
```
|
82
|
-
|
83
|
-
##### Difference between `obs_keys()` and `obs.columns`
|
84
|
-
`obs_keys()` returns the list of columns in the on-disc AnnData file, while `obs.columns` returns the list of columns in the in-memory DataFrame. The two lists may differ if you read only specific columns. If you modify the in-memory DataFrame, the `obs_keys()` will reflect the changes. BTW it is recommended to check the `obs_keys()` before the `overwrite()` call to avoid the AnnData file damage.
|
85
|
-
|
86
|
-
If a column doesn't exist in the file, no error will be raised but the column will be missing in the resulting DataFrame. So, the list of columns saying more like "try to read this columns from the file". It is needed because we there is no way yet to check if the column exists before the read. Exactly the same behavior is for the `var_keys()` and `var.columns`.
|
87
|
-
|
88
|
-
#### 2. Modify the AnnData File DataFrames In-Place
|
89
|
-
|
90
|
-
You can directly modify the dataframe by adding, renaming, or removing columns.
|
91
|
-
|
92
|
-
```python
|
93
|
-
# Create a new column
|
94
|
-
cap_adata.obs['new_col'] = [value1, value2, value3]
|
95
|
-
|
96
|
-
# Rename a column
|
97
|
-
cap_adata.obs.rename_column('old_col_name', 'new_col_name')
|
98
|
-
|
99
|
-
# Remove a column
|
100
|
-
cap_adata.obs.remove_column('col_to_remove')
|
101
|
-
```
|
102
|
-
|
103
|
-
After modifications, you can overwrite the changes back to the AnnData file. If a value doesn't exist, it will be created.
|
104
|
-
Note: `read_h5ad` must be called with `edit=True` argument to open `.h5ad` file in `r+` mode.
|
105
|
-
|
106
|
-
```python
|
107
|
-
# overwrite all values which were read
|
108
|
-
cap_adata.overwrite()
|
109
|
-
|
110
|
-
# overwrite choosen fields
|
111
|
-
cap_adata.overwrite(['obs', 'var'])
|
112
|
-
```
|
113
|
-
|
114
|
-
The full list of supported fields: `obs`, `var`, `raw.var`, `obsm`, `uns`.
|
115
|
-
|
116
|
-
#### 3. How to Read Few Columns but Overwrite One in a Dataframe
|
117
|
-
|
118
|
-
The only way yet to do that is to drop all columns from in-memory dataframe (with `pandas.drop`!) before the call of `overwrite` method.
|
119
|
-
|
120
|
-
```python
|
121
|
-
# Read specific columns
|
122
|
-
cap_adata.read_obs(columns=['cell_type', 'sample'])
|
123
|
-
|
124
|
-
# Drop a column in-memory
|
125
|
-
# DON'T USE remove_column here!
|
126
|
-
cap_adata.obs.drop(columns='sample', inplace=True)
|
127
|
-
|
128
|
-
# Overwrite changes
|
129
|
-
cap_adata.overwrite(['obs'])
|
130
|
-
|
131
|
-
# NOTE that the line
|
132
|
-
# cap_adata.read_obs(columns=['sample'], reset=True)
|
133
|
-
# Will override in-memory changes with values from the AnnData file
|
134
|
-
```
|
135
|
-
|
136
|
-
#### 4. How to work with X and raw.X
|
137
|
-
|
138
|
-
The CapAnnData package won't read any field by default. However, the `X` and `raw.X` will be linked to the backed matrices automatically upon the first request to those fields.
|
139
|
-
The X object will be returned as the `h5py.Dataset` or `AnnData.experimental.sparse_dataset`.
|
140
|
-
|
141
|
-
```python
|
142
|
-
with read_h5ad(file_path=file_path, edit=False) as cap_adata:
|
143
|
-
# self.X is None here
|
144
|
-
cap_adata = CapAnnData(file)
|
145
|
-
|
146
|
-
# will return the h5py.Dataset or CSRDataset
|
147
|
-
x = cap_adata.X
|
148
|
-
|
149
|
-
# The same for raw.X
|
150
|
-
raw_x = cap_adata.raw.X
|
151
|
-
|
152
|
-
# take whole matrix in memory
|
153
|
-
x = cap_adata.X[:]
|
154
|
-
```
|
155
|
-
|
156
|
-
The CapAnnData supports the standard `numpy`/`h5py` sclising rules
|
157
|
-
|
158
|
-
```python
|
159
|
-
# slice rows
|
160
|
-
s_ = np.s_[0:5]
|
161
|
-
# slice columns
|
162
|
-
s_ = np.s_[:, 0:5]
|
163
|
-
# boolean mask + slicing
|
164
|
-
mask = np.array([i < 5 for i in range(adata.shape[0])])
|
165
|
-
s_ = np.s_[mask, :5]
|
166
|
-
```
|
167
|
-
|
168
|
-
#### 5. How to handle obsm embeddings matrixes
|
169
|
-
|
170
|
-
By the default the CapAnnData will not read the embeddings matrix.
|
171
|
-
The link to the h5py objects will be created upon the first call of the `.obsm` property.
|
172
|
-
Alike the AnnData package the call like `cap_adata.obsm["X_tsne"]` will not return the in-memory matrix but will return the backed version instead.
|
173
|
-
It is possible to get the information about the name and shape of the embeddings without taking the whole matrix in the memory.
|
174
|
-
|
175
|
-
```python
|
176
|
-
with read_h5ad(file_path=file_path, edit=False) as cap_adata:
|
177
|
-
# will return the list of strings
|
178
|
-
obsm_keys = cap_adata.obsm_keys()
|
179
|
-
|
180
|
-
# return the shape of the matrix in backed mode
|
181
|
-
embeddings = obsm_keys[0]
|
182
|
-
shape = cap_adata.obsm[embeddings].shape
|
183
|
-
|
184
|
-
# take the whole matrix in memory
|
185
|
-
matrix = cap_adata.obsm[embeddings][:]
|
186
|
-
```
|
187
|
-
|
188
|
-
#### 6. How to read and modify uns section
|
189
|
-
|
190
|
-
The `CapAnnData` class will lazely link the uns section upon the first call but ***WILL NOT*** read it into memory. Instead, the dictionary of the pairs `{'key': "__NotLinkedObject"}` will be creted. It allow to get the list of keys before the actual read. To read the uns section in the memory the `.read_uns(keys)` method must be called.
|
191
|
-
|
192
|
-
```python
|
193
|
-
with read_h5ad(file_path=file_path, edit=True) as cap_adata:
|
194
|
-
# will return the keys() object
|
195
|
-
keys = cap_adata.uns.keys()
|
196
|
-
|
197
|
-
# read in memory the first key only
|
198
|
-
cap_adata.read_uns([keys[0]])
|
199
|
-
|
200
|
-
# read the whole uns section into memory
|
201
|
-
cap_adata.read_uns()
|
202
|
-
```
|
203
|
-
|
204
|
-
Since the `.uns` section is in the memory (partially or completely) we can work with it as with the regular `dict()` python object. The main feature of the `CapAnnDataUns` class which inherited from `dict` is the tracking of the keys which must be removed from the `.h5ad` file upon overwrite.
|
205
|
-
|
206
|
-
```python
|
207
|
-
# get the value
|
208
|
-
v = cap_adata.uns["key1"]
|
209
|
-
v = cap_adata.uns.get("key1")
|
210
|
-
|
211
|
-
# modify values
|
212
|
-
cap_adata.uns["key1"] = "new_value"
|
213
|
-
|
214
|
-
# create new keys
|
215
|
-
cap_adata.uns["new_key"] = "value"
|
216
|
-
|
217
|
-
# remove keys
|
218
|
-
cap_adata.uns.pop("key1") # is recommended way
|
219
|
-
del cap_adata.uns.pop("key2")
|
220
|
-
cap_adata.uns.popitem()
|
221
|
-
```
|
222
|
-
|
223
|
-
To save `uns` changes the method `CapAnnData.overwrite()` must be called.
|
224
|
-
|
225
|
-
```python
|
226
|
-
cap_adata.overwrite() # all in-memory fields will be overwritten
|
227
|
-
cap_adata.overwrite(["uns"]) # overwrite the uns secion only
|
228
|
-
```
|
229
|
-
|
230
|
-
#### 7. Join and Merge DataFrames
|
231
|
-
|
232
|
-
Cap-AnnData provides enhanced methods for joining and merging dataframes, preserving column order and data integrity
|
233
|
-
|
234
|
-
```python
|
235
|
-
from cap_anndata import CapAnnDataDF
|
236
|
-
import pandas as pd
|
237
|
-
|
238
|
-
data1 = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
|
239
|
-
data2 = pd.DataFrame({'D': [7, 8, 9], 'E': [10, 11, 12]})
|
240
|
-
cap_anndata_df1 = CapAnnDataDF.from_df(data1, column_order=['A', 'B', 'C'])
|
241
|
-
|
242
|
-
cap_df = cap_anndata_df1.join(data2, how='left')
|
243
|
-
|
244
|
-
cap_df.columns # ['A', 'B', 'D', 'E']
|
245
|
-
cap_df.column_order # ['A', 'B', 'C', 'D', 'E']
|
246
|
-
|
247
|
-
data3 = pd.DataFrame({'A': [2, 3, 4], 'D': [10, 11, 12]})
|
248
|
-
cap_df = cap_anndata_df1.merge(data3, on='A')
|
249
|
-
|
250
|
-
cap_df.columns # ['A', 'B', 'D']
|
251
|
-
cap_df.column_order # ['A', 'B', 'C', 'D']
|
252
|
-
cap_df.shape # (2, 3)
|
253
|
-
```
|
@@ -1,10 +0,0 @@
|
|
1
|
-
cap_anndata/__init__.py,sha256=l9lvFpcMsQksp8_dI-fjUgrImoMdztbu3jVSdmxNPmA,205
|
2
|
-
cap_anndata/backed_df.py,sha256=06wZwEjszFQ8lkvy6-GgD_SD14idu9857RtlfMQiBjE,2691
|
3
|
-
cap_anndata/backed_uns.py,sha256=Tfxoz3RgcgENf4SvxFOox9w048K2QmBTh1VbAf4yqVI,854
|
4
|
-
cap_anndata/cap_anndata.py,sha256=fEaIwWIKKDJpIsQ7cwOfUTmUReIyryv5qRDqRjRsWhU,10185
|
5
|
-
cap_anndata/reader.py,sha256=kg9xoS_S0gY6WpsHE8PwGMa14VXh9Ibqjw4bwoerYsE,1267
|
6
|
-
cap_anndata-0.2.2.dist-info/LICENSE,sha256=JAV0w7TBl6wQe9iFcCKjAWgpurym0f-Q0B75zm2PrKw,1560
|
7
|
-
cap_anndata-0.2.2.dist-info/METADATA,sha256=h41dgoz3w2rDHnic828FahjEoKq1lt_Bi1jm-ZX-goA,9569
|
8
|
-
cap_anndata-0.2.2.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
|
9
|
-
cap_anndata-0.2.2.dist-info/top_level.txt,sha256=GKi_Uk4LUhXwWBfFCTIyJvEoJqFREt_4uH4CWgeLsg4,12
|
10
|
-
cap_anndata-0.2.2.dist-info/RECORD,,
|
File without changes
|