{ "cells": [ { "cell_type": "code", "execution_count": 2, "id": "600ac04d", "metadata": {}, "outputs": [], "source": [ "from glob import glob\n", "import os\n", "import scanpy as sc\n", "from tqdm.auto import tqdm\n", "\n", "# All code, including comments, logs, and strings, is in English.\n", "import scanpy as sc\n", "import numpy as np\n", "import pandas as pd\n", "\n", "\n", "def preprocess(\n", " adata: sc.AnnData,\n", " filter_genes: bool = False,\n", " filter_cells: bool = False,\n", " min_cells: int = 1,\n", " min_genes: int = 5,\n", " normalize: str = \"auto\",\n", " target_sum: float = 1e4,\n", " standardize_genes: bool = True,\n", " cell_type_key: str = None,\n", ") -> sc.AnnData:\n", " \"\"\"\n", " Preprocesses an AnnData object with configurable settings.\n", "\n", " Args:\n", " adata (sc.AnnData): The AnnData object to preprocess.\n", " filter_genes (bool, optional): If True, filter genes by cell count. Defaults to True.\n", " min_cells (int, optional): Min number of cells a gene must be expressed in. Defaults to 1.\n", " normalize (str, optional): Normalization strategy. Can be:\n", " - 'auto': Normalize if data appears to be raw counts.\n", " - True: Force normalization.\n", " - False: Skip normalization.\n", " Defaults to 'auto'.\n", " target_sum (float, optional): Target sum for total-count normalization. Defaults to 1e4.\n", " standardize_genes (bool, optional): If True, set var_names to gene symbols from ENSEMBL IDs.\n", " Defaults to True.\n", " cell_type_key (str, optional): The key in adata.obs that contains cell type annotations.\n", " If provided, it will be copied to a new 'cell_type' column.\n", " Defaults to None.\n", "\n", " Returns:\n", " sc.AnnData: The processed AnnData object.\n", " \"\"\"\n", " # Work on a copy to avoid modifying the original object unexpectedly\n", " adata = adata.copy()\n", " print(\n", " f\"--- Starting preprocessing for AnnData object with {adata.n_obs} obs and {adata.n_vars} vars ---\"\n", " )\n", "\n", " # 1. Gene Filtering\n", " if filter_genes:\n", " print(f\"Filtering genes expressed in less than {min_cells} cells.\")\n", " sc.pp.filter_genes(adata, min_cells=min_cells)\n", " if filter_cells:\n", " print(f\"Filtering cells with less than {min_genes} genes expressed.\")\n", " sc.pp.filter_cells(adata, min_genes=min_genes)\n", "\n", " # 2. Normalization\n", " max_diff = np.max(np.abs(adata.X[:10] - adata.X[:10].astype(np.int32)))\n", " is_raw = max_diff < 0.1\n", " print(f\"Data appears to be {'raw' if is_raw else 'normalized'}.\")\n", " print(f\"Max difference in first 10 cells: {max_diff:.4f}\")\n", "\n", " if normalize is True or (normalize == \"auto\" and is_raw):\n", " print(\n", " f\"Normalizing data: target_sum={target_sum}, followed by log1p transformation.\"\n", " )\n", " adata.raw = adata.copy()\n", " sc.pp.normalize_total(adata, target_sum=target_sum)\n", " sc.pp.log1p(adata)\n", " elif normalize == \"auto\" and not is_raw:\n", " print(\"Data seems to be already normalized, skipping normalization.\")\n", " print(adata.X.max())\n", " else:\n", " print(\"Skipping normalization as requested.\")\n", "\n", " # 3. Gene Name Standardization\n", " if (\n", " standardize_genes\n", " and \"gene_name\" in adata.var.columns\n", " and adata.var_names[0].startswith(\"ENSG\")\n", " ):\n", " print(\"Standardizing gene names from ENSEMBL IDs to gene symbols.\")\n", " adata.var[\"ensembl_id\"] = adata.var_names\n", "\n", " def get_best_gene_name(gene_name_entry):\n", " # This helper handles cases where 'gene_name' might be a list\n", " if isinstance(gene_name_entry, str):\n", " return gene_name_entry\n", " elif hasattr(gene_name_entry, \"__iter__\"):\n", " # Prefer a non-ENSG name from the list\n", " for name in gene_name_entry:\n", " if isinstance(name, str) and not name.startswith(\"ENSG\"):\n", " return name\n", " # Fallback to the first item if all are ENSG or something else\n", " return gene_name_entry[0] if len(gene_name_entry) > 0 else \"\"\n", " return str(gene_name_entry) # Fallback for other types like float NaN\n", "\n", " new_var_names = [get_best_gene_name(x) for x in adata.var[\"gene_name\"]]\n", "\n", " # Ensure new var names are unique, which is a requirement for AnnData\n", " if pd.Series(new_var_names).duplicated().any():\n", " print(\n", " \"Warning: Duplicate gene names detected. Making them unique with '.var_names_make_unique()'.\"\n", " )\n", " adata.var[\"original_gene_symbol\"] = new_var_names\n", " adata.var_names = new_var_names\n", " adata.var_names_make_unique()\n", " else:\n", " adata.var_names = new_var_names\n", "\n", " print(f\"Example of new var_names: {adata.var_names[:5].tolist()}\")\n", "\n", " # Ensure 'gene_name' column is consistent with the final var_names\n", " adata.var[\"gene_name\"] = adata.var_names\n", "\n", " # 4. Cell Type Annotation\n", " if cell_type_key:\n", " if cell_type_key in adata.obs.columns:\n", " print(f\"Setting 'cell_type' from adata.obs['{cell_type_key}'].\")\n", " adata.obs[\"cell_type\"] = adata.obs[cell_type_key].astype(str)\n", " else:\n", " raise ValueError(\n", " f\"Warning: The provided cell_type_key '{cell_type_key}' was not found in adata.obs. Skipping.\"\n", " )\n", "\n", " print(\"--- Preprocessing finished ---\")\n", " return adata\n", "\n", "\n", "# for file in tqdm(glob(\"../dataset_raw/*.h5ad\")):\n", "# file = os.path.basename(file)\n", "\n", "# # if (\n", "# # (not \"COAD\" in file) and (not \"HCC\" in file) and (not \"OV\" in file)\n", "# # ): # This filter applies to all clustering for the dataset\n", "# # continue\n", "# # if \"COVID\" in file:\n", "# # continue\n", "# if not \"gse155468.h5ad\" in file:\n", "# continue\n", "\n", "# adata = sc.read_h5ad(f\"../dataset_raw/{file}\")\n", "# adata = preprocess(\n", "# adata,\n", "# filter_genes=False,\n", "# filter_cells=True,\n", "# min_cells=1,\n", "# min_genes=5,\n", "# normalize=\"auto\",\n", "# target_sum=1e4,\n", "# standardize_genes=True,\n", "# cell_type_key=\"celltype\",\n", "# )\n", "# file = file.replace(\".h5ad\", \"_filtered.h5ad\")\n", "# adata.write_h5ad(file)" ] }, { "cell_type": "code", "execution_count": 2, "id": "dcc30035", "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "a4323a2be829424785ea4a972a3ff7c1", "version_major": 2, "version_minor": 0 }, "text/plain": [ " 0%| | 0/49 [00:00