-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #81 from klarman-cell-observatory/rocherr
spatial read and write to zarr
- Loading branch information
Showing
8 changed files
with
256 additions
and
65 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
import numpy as np | ||
import pandas as pd | ||
from scipy.sparse import csr_matrix | ||
from typing import Dict, Optional, Union | ||
|
||
import logging | ||
|
||
from pegasusio.unimodal_data import UnimodalData | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class SpatialData(UnimodalData): | ||
""" | ||
Class to implement data structure to | ||
manipulate spatial data with the spatial image (img) field | ||
This class extends UnimodalData with additional | ||
functions specific to the img field | ||
""" | ||
|
||
def __init__( | ||
self, | ||
barcode_metadata: Optional[Union[dict, pd.DataFrame]] = None, | ||
feature_metadata: Optional[Union[dict, pd.DataFrame]] = None, | ||
matrices: Optional[Dict[str, csr_matrix]] = None, | ||
metadata: Optional[dict] = None, | ||
barcode_multiarrays: Optional[Dict[str, np.ndarray]] = None, | ||
feature_multiarrays: Optional[Dict[str, np.ndarray]] = None, | ||
barcode_multigraphs: Optional[Dict[str, csr_matrix]] = None, | ||
feature_multigraphs: Optional[Dict[str, csr_matrix]] = None, | ||
cur_matrix: str = "raw.data", | ||
img=None, | ||
) -> None: | ||
assert metadata["modality"] == "visium" | ||
super().__init__( | ||
barcode_metadata, | ||
feature_metadata, | ||
matrices, | ||
metadata, | ||
barcode_multiarrays, | ||
feature_multiarrays, | ||
barcode_multigraphs, | ||
feature_multigraphs, | ||
cur_matrix, | ||
) | ||
self._img = img | ||
|
||
@property | ||
def img(self) -> Optional[pd.DataFrame]: | ||
return self._img | ||
|
||
@img.setter | ||
def img(self, img: pd.DataFrame): | ||
self._img = img | ||
|
||
def __repr__(self) -> str: | ||
repr_str = super().__repr__() | ||
key = "img" | ||
fstr = self._gen_repr_str_for_attrs(key) | ||
if fstr != "": | ||
repr_str += f"\n {key}: {fstr}" | ||
return repr_str |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
import os | ||
|
||
import pandas as pd | ||
|
||
from pegasusio import MultimodalData, SpatialData | ||
from .hdf5_utils import load_10x_h5_file | ||
import json | ||
from PIL import Image | ||
|
||
|
||
def process_spatial_metadata(df): | ||
df["in_tissue"] = df["in_tissue"].apply(lambda n: True if n == 1 else False) | ||
df["barcodekey"] = df["barcodekey"].map(lambda s: s.split("-")[0]) | ||
df.set_index("barcodekey", inplace=True) | ||
|
||
|
||
def is_image(filename): | ||
return filename.endswith((".png", ".jpg")) | ||
|
||
|
||
def load_visium_folder(input_path) -> MultimodalData: | ||
""" | ||
Method to read the visium spatial data folder | ||
into MultimodalData object that contains SpatialData | ||
""" | ||
file_list = os.listdir(input_path) | ||
sample_id = input_path.split("/")[-1] | ||
# Load count matrix. | ||
hdf5_filename = "raw_feature_bc_matrix.h5" | ||
assert hdf5_filename in file_list, "Raw count hdf5 file is missing!" | ||
rna_data = load_10x_h5_file(f"{input_path}/{hdf5_filename}") | ||
|
||
# Load spatial metadata. | ||
assert ("spatial" in file_list) and ( | ||
os.path.isdir(f"{input_path}/spatial") | ||
), "Spatial folder is missing!" | ||
tissue_pos_csv = "spatial/tissue_positions_list.csv" | ||
spatial_metadata = pd.read_csv( | ||
f"{input_path}/{tissue_pos_csv}", | ||
names=[ | ||
"barcodekey", | ||
"in_tissue", | ||
"array_row", | ||
"array_col", | ||
"pxl_col_in_fullres", | ||
"pxl_row_in_fullres", | ||
], | ||
) | ||
process_spatial_metadata(spatial_metadata) | ||
|
||
barcode_metadata = pd.concat([rna_data.obs, spatial_metadata], axis=1) | ||
feature_metadata = rna_data.var | ||
|
||
matrices = {"raw.data": rna_data.X} | ||
metadata = {"genome": rna_data.get_genome(), "modality": "visium"} | ||
|
||
# Store “pxl_col_in_fullres” and ”pxl_row_in_fullres” as a 2D array, | ||
# which is the spatial location info of each cell in the dataset. | ||
obsm = spatial_metadata[["pxl_col_in_fullres", "pxl_row_in_fullres"]] | ||
barcode_multiarrays = {"spatial_coordinates": obsm.to_numpy()} | ||
|
||
# Store all the other spatial info of cells, i.e. “in_tissue”, “array_row”, and “array_col” | ||
obs = spatial_metadata[["in_tissue", "array_row", "array_col"]] | ||
barcode_metadata = obs | ||
|
||
# Store image metadata as a Pandas DataFrame, with the following structure: | ||
img = pd.DataFrame() | ||
spatial_path = f"{input_path}/spatial" | ||
|
||
with open(f"{spatial_path}/scalefactors_json.json") as fp: | ||
scale_factors = json.load(fp) | ||
|
||
arr = os.listdir(spatial_path) | ||
for png in arr: | ||
if not is_image(png): | ||
continue | ||
if "hires" in png: | ||
with Image.open(f"{spatial_path}/{png}") as data: | ||
data.load() | ||
dict = { | ||
"sample_id": sample_id, | ||
"image_id": "hires", | ||
"data": data, | ||
"scaleFactor": scale_factors["tissue_hires_scalef"], | ||
} | ||
img = img.append(dict, ignore_index=True) | ||
elif "lowres" in png: | ||
with Image.open(f"{spatial_path}/{png}") as data: | ||
data.load() | ||
dict = { | ||
"sample_id": sample_id, | ||
"image_id": "lowres", | ||
"data": data, | ||
"scaleFactor": scale_factors["tissue_lowres_scalef"], | ||
} | ||
img = img.append(dict, ignore_index=True) | ||
|
||
assert not img.empty, "the image data frame is empty" | ||
spdata = SpatialData( | ||
barcode_metadata, | ||
feature_metadata, | ||
matrices, | ||
metadata, | ||
barcode_multiarrays=barcode_multiarrays, | ||
img=img, | ||
) | ||
data = MultimodalData(spdata) | ||
|
||
return data |
Oops, something went wrong.