Skip to content

Use tissue json to filter cell bin json files

Guang-Wei Zhang edited this page Aug 26, 2023 · 1 revision

import json import os from shapely.geometry import Point, Polygon

Load the tissue JSON file

def load_tissue_polygon(tissue_filepath): with open(tissue_filepath, 'r') as file: tissue_data = json.load(file) return tissue_data['shapes'][0]['points']

def is_point_inside_polygon(point, polygon): """Check if the given point is inside the given polygon.""" return Point(point).within(Polygon(polygon))

def filter_cells_by_tissue(cell_filepath, tissue_polygon): with open(cell_filepath, 'r') as file: cell_data = json.load(file)

filtered_cells = [cell for cell in cell_data['shapes'] if all(is_point_inside_polygon(point, tissue_polygon) for point in cell['points'])]
cell_data['shapes'] = filtered_cells

return cell_data

def batch_process(root_folder): cell_dir = os.path.join(root_folder, "final_corrected_cell_json") tissue_dir = os.path.join(root_folder, "final_tissue_json") output_dir = os.path.join(root_folder, "filtered_cell_json")

# Ensure the output directory exists
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# Filter cell files
for cell_file in os.listdir(cell_dir):
    # Find the matching tissue JSON file by filename
    tissue_file = os.path.join(tissue_dir, cell_file)
    if os.path.exists(tissue_file):
        tissue_polygon = load_tissue_polygon(tissue_file)
        filtered_data = filter_cells_by_tissue(os.path.join(cell_dir, cell_file), tissue_polygon)
        with open(os.path.join(output_dir, cell_file), 'w') as output_file:
            json.dump(filtered_data, output_file)
    else:
        print(f"No matching tissue file found for {cell_file}")

Execute the batch processing

batch_process("G:\My Drive\Project\[1] Spinal Cord Spatial Transcriptome\h5ad\Cell_bin_json_files\bin1_images_Edwin")

Data processing pipeline

preparation of cell bin data

Data Structure of scanpy

Clone this wiki locally