{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a4c6d364", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:02.636954Z", "iopub.status.busy": "2025-03-25T03:50:02.636786Z", "iopub.status.idle": "2025-03-25T03:50:02.803484Z", "shell.execute_reply": "2025-03-25T03:50:02.803136Z" } }, "outputs": [], "source": [ "import sys\n", "import os\n", "sys.path.append(os.path.abspath(os.path.join(os.getcwd(), '../..')))\n", "\n", "# Path Configuration\n", "from tools.preprocess import *\n", "\n", "# Processing context\n", "trait = \"Retinoblastoma\"\n", "cohort = \"GSE68950\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Retinoblastoma\"\n", "in_cohort_dir = \"../../input/GEO/Retinoblastoma/GSE68950\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Retinoblastoma/GSE68950.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Retinoblastoma/gene_data/GSE68950.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Retinoblastoma/clinical_data/GSE68950.csv\"\n", "json_path = \"../../output/preprocess/Retinoblastoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "28e0eaf9", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "1db21a28", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:02.804752Z", "iopub.status.busy": "2025-03-25T03:50:02.804608Z", "iopub.status.idle": "2025-03-25T03:50:03.210672Z", "shell.execute_reply": "2025-03-25T03:50:03.210329Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"caArray_golub-00327: Sanger cell line Affymetrix gene expression project\"\n", "!Series_summary\t\"The microarray gene expression pattern was studied using 798 different cancer cell lines. The cancer cell lines are obtained from different centers. Annotation information were provided in the supplementary file.\"\n", "!Series_overall_design\t\"golub-00327\"\n", "!Series_overall_design\t\"Assay Type: Gene Expression\"\n", "!Series_overall_design\t\"Provider: Affymetrix\"\n", "!Series_overall_design\t\"Array Designs: HT_HG-U133A\"\n", "!Series_overall_design\t\"Organism: Homo sapiens (ncbitax)\"\n", "!Series_overall_design\t\"Tissue Sites: leukemia, Urinary tract, Lung, BiliaryTract, Autonomic Ganglion, Thyroid gland, Stomach, Breast, Pancreas, Head and Neck, Lymphoma, Colorectal, Placenta, Liver, Brain, Bone, pleura, Skin, endometrium, Ovary, cervix, Oesophagus, Connective and Soft Tissue, Muscle, Kidney, Prostate, Adrenal Gland, Eye, Testis, Smooth Muscle Tissue, Vulva, Unknow\"\n", "!Series_overall_design\t\"Material Types: cell, synthetic_RNA, whole_organism, total_RNA, BVG\"\n", "!Series_overall_design\t\"Disease States: M3 acute myeloid leukemia, hairy cell leukemia, transitional cell carcinoma, Adenocarcinoma, B cell lymphoma unspecified, Acute Lymphoblastic Leukemia, blast phase chronic myeloid leukemia, Carcinoma, M6 acute myeloid leukemia, Neuroblastoma, follicular carcinoma, ductal carcinoma, Burkitt Lymphoma, Squamous Cell Carcinoma, M5 acute myeloid leukemia, Mycosis Fungoides and Sezary Syndrome, Acute T-Cell Lymphoblastic Leukemia, Adult T-Cell Leukemia/Lymphoma, M2 Therapy-Related Myeloid Neoplasm, Choriocarcinoma, Plasma Cell Myeloma, Hepatocellular Carcinoma, anaplastic large cell lymphoma, primitive neuroectodermal tumor-medulloblastoma, M4 acute myeloid leukemia, B Acute Lymphoblastic Leukemia, Acute Leukemia of Ambiguous Lineage, Osteosarcoma, Hodgkin Lymphoma, Mesothelioma, chondrosarcoma, Glioblastoma Multiforme, Malignant Melanoma, carcinosarcoma-malignant mesodermal mixed tumor, bronchioloalveolar adenocarcinoma, chronic lymphocytic leukemia-small lymphocytic lymphoma, micropapillary carcinoma, diffuse large B cell lymphoma, myelodysplastic syndrome, giant cell carcinoma, teratoma, multipotential sarcoma, Small Cell Carcinoma, ASTROCYTOMA, Fibrosarcoma, mucoepidermoid carcinoma, Rhabdomyosarcoma, L1 Acute T-Cell Lymphoblastic Leukemia, Glioma, Anaplastic Astrocytoma, Non-small cell carcinoma, Large Cell Carcinoma, mucinous carcinoma, Acute Myeloid Leukemia, malignant fibrous histiocytoma-pleomorphic sarcoma, clear cell carcinoma, B cell lymphoma unspecified, Anaplastic Carcinoma, Ewings sarcoma-peripheral primitive neuroectodermal tumor, undifferentiated carcinoma, Sarcoma, Embryonal Rhabdomyosarcoma, epithelioid sarcoma, renal cell carcinoma, carcinoid-endocrine tumor, Synovial Sarcoma, lymphoid neoplasm, rhabdoid tumor, Refractory Anemia with Excess Blasts, Liposarcoma, biphasic mesothelioma, adrenal cortical carcinoma, adenosquamous carcinoma, L2 Acute T-Cell Lymphoblastic Leukemia, chronic myeloid leukemia, Micropapillary Serous Carcinoma, desmoplastic, acute leukemia, Retinoblastoma, teratocarcinoma, clear cell renal cell carcinoma, Follicular Lymphoma, Wilms Tumor, M7 acute myeloid leukemia, gliosarcoma, embryonal carcinoma, Leiomyosarcoma, medullary carcinoma, granulosa cell tumor, papillary carcinoma, NS Acute Lymphoblastic Leukemia, papillary transitional cell carcinoma, small cell adenocarcinoma, epithelial dysplasia, hyperplasia, tubular adenocarcinoma, metaplasia, papillary ductal carcinoma, chronic eosinophilic leukemia-hypereosinophilic syndrome, #N/A, malignant trichilemmal cyst, Medullary Breast Carcinoma, L2 Acute Lymphoblastic Leukemia, Osteoblastic Osteosarcoma\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cosmic id: 924101', 'cosmic id: 906800', 'cosmic id: 687452', 'cosmic id: 924100', 'cosmic id: 910924', 'cosmic id: 906798', 'cosmic id: 906797', 'cosmic id: 910922', 'cosmic id: 905947', 'cosmic id: 924102', 'cosmic id: 687562', 'cosmic id: 910921', 'cosmic id: 687563', 'cosmic id: 910784', 'cosmic id: 906792', 'cosmic id: 906794', 'cosmic id: 906804', 'cosmic id: 906793', 'cosmic id: 910935', 'cosmic id: 910851', 'cosmic id: 910925', 'cosmic id: 905948', 'cosmic id: 910934', 'cosmic id: 905949', 'cosmic id: 684052', 'cosmic id: 910920', 'cosmic id: 906791', 'cosmic id: 905950', 'cosmic id: 906803', 'cosmic id: 906790'], 1: ['disease state: L2 Acute Lymphoblastic Leukemia', 'disease state: NS Acute Lymphoblastic Leukemia', 'disease state: carcinoma', 'disease state: adenocarcinoma', 'disease state: transitional cell carcinoma', 'disease state: clear cell renal cell carcinoma', 'disease state: anaplastic carcinoma', 'disease state: glioblastoma multiforme', 'disease state: malignant melanoma', 'disease state: rhabdomyosarcoma', 'disease state: mucoepidermoid carcinoma', 'disease state: squamous cell carcinoma', 'disease state: renal cell carcinoma', 'disease state: neuroblastoma', 'disease state: Acute Lymphoblastic Leukemia', 'disease state: M5 acute myeloid leukemia', 'disease state: plasma cell myeloma', 'disease state: L1 Acute T-Cell Lymphoblastic Leukemia', 'disease state: astrocytoma', 'disease state: B Acute Lymphoblastic Leukemia', 'disease state: B cell lymphoma unspecified', 'disease state: papillary carcinoma', 'disease state: papillary transitional cell carcinoma', 'disease state: Burkitt lymphoma', 'disease state: hairy cell leukemia', 'disease state: hyperplasia', 'disease state: papillary ductal carcinoma', 'disease state: blast phase chronic myeloid leukemia', 'disease state: hepatocellular carcinoma', 'disease state: Adult T-Cell Leukemia/Lymphoma'], 2: ['disease location: Hematopoietic and Lymphoid Tissue', 'disease location: bladder', 'disease location: prostate', 'disease location: stomach', 'disease location: ureter', 'disease location: kidney', 'disease location: thyroid', 'disease location: frontal lobe', 'disease location: skin', 'disease location: brain', 'disease location: striated muscle', 'disease location: submaxillary', 'disease location: ovary', 'disease location: lung', 'disease location: autonomic ganglia', 'disease location: endometrium', 'disease location: pancreas', 'disease location: head neck', 'disease location: cervix', 'disease location: breast', 'disease location: colon', 'disease location: liver', 'disease location: gingiva', 'disease location: tongue', 'disease location: vulva', 'disease location: bone', 'disease location: rectum', 'disease location: esophagus', 'disease location: central nervous system', 'disease location: posterior fossa'], 3: ['organism part: Leukemia', 'organism part: Urinary tract', 'organism part: Prostate', 'organism part: Stomach', 'organism part: Kidney', 'organism part: Thyroid Gland', 'organism part: Brain', 'organism part: Skin', 'organism part: Muscle', 'organism part: Head and Neck', 'organism part: Ovary', 'organism part: Lung', 'organism part: Autonomic Ganglion', 'organism part: Endometrium', 'organism part: Pancreas', 'organism part: Cervix', 'organism part: Breast', 'organism part: Colorectal', 'organism part: Liver', 'organism part: Vulva', 'organism part: Bone', 'organism part: Oesophagus', 'organism part: BiliaryTract', 'organism part: Connective and Soft Tissue', 'organism part: Lymphoma', 'organism part: Pleura', 'organism part: Testis', 'organism part: Placenta', 'organism part: Adrenal Gland', 'organism part: Unknow'], 4: ['sample: 736', 'sample: 494', 'sample: 7', 'sample: 746', 'sample: 439', 'sample: 168', 'sample: 152', 'sample: 37', 'sample: 450', 'sample: 42', 'sample: 526', 'sample: 462', 'sample: 451', 'sample: 486', 'sample: 429', 'sample: 47', 'sample: 755', 'sample: 71', 'sample: 72', 'sample: 474', 'sample: 364', 'sample: 537', 'sample: 110', 'sample: 316', 'sample: 33', 'sample: 408', 'sample: 201', 'sample: 38', 'sample: 9', 'sample: 190'], 5: ['cell line code: 749', 'cell line code: 493', 'cell line code: 505', 'cell line code: 760', 'cell line code: 437', 'cell line code: 151', 'cell line code: 134', 'cell line code: 449', 'cell line code: 85', 'cell line code: 529', 'cell line code: 461', 'cell line code: 450', 'cell line code: 485', 'cell line code: 426', 'cell line code: 59', 'cell line code: 769', 'cell line code: 48', 'cell line code: 38', 'cell line code: 473', 'cell line code: 353', 'cell line code: 541', 'cell line code: 54', 'cell line code: 302', 'cell line code: 25', 'cell line code: 402', 'cell line code: 184', 'cell line code: 63', 'cell line code: 29', 'cell line code: 173', 'cell line code: 553'], 6: ['supplier: DSMZ', 'supplier: ATCC', 'supplier: Unspecified', 'supplier: DTP', 'supplier: HSRRB', 'supplier: ICLC', 'supplier: RIKEN', 'supplier: ECCC', 'supplier: JCRB'], 7: ['affy_batch: 1', 'affy_batch: 2'], 8: ['crna plate: 8', 'crna plate: 6', 'crna plate: 11', 'crna plate: 5', 'crna plate: 2', 'crna plate: 12', 'crna plate: 4', 'crna plate: 3', 'crna plate: 7']}\n" ] } ], "source": [ "from tools.preprocess import *\n", "# 1. Identify the paths to the SOFT file and the matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Read the matrix file to obtain background information and sample characteristics data\n", "background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']\n", "clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", "\n", "# 3. Obtain the sample characteristics dictionary from the clinical dataframe\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "\n", "# 4. Explicitly print out all the background information and the sample characteristics dictionary\n", "print(\"Background Information:\")\n", "print(background_info)\n", "print(\"Sample Characteristics Dictionary:\")\n", "print(sample_characteristics_dict)\n" ] }, { "cell_type": "markdown", "id": "96d253a9", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "7378c600", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:03.212554Z", "iopub.status.busy": "2025-03-25T03:50:03.212406Z", "iopub.status.idle": "2025-03-25T03:50:03.219607Z", "shell.execute_reply": "2025-03-25T03:50:03.219300Z" } }, "outputs": [], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Determine Gene Expression Data Availability\n", "# Based on the background information, this seems to be gene expression data using Affymetrix array\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Retinoblastoma)\n", "# Looking at disease state information in row 1 to see if Retinoblastoma is mentioned\n", "unique_diseases = set([value.split(': ')[1] for value in sample_characteristics_dict[1]])\n", "if 'Retinoblastoma' in unique_diseases:\n", " trait_row = 1 # disease state row\n", "else:\n", " # Check if the eye location might indicate retinoblastoma\n", " disease_locations = set([value.split(': ')[1] for value in sample_characteristics_dict[2]])\n", " organism_parts = set([value.split(': ')[1] for value in sample_characteristics_dict[3]])\n", " \n", " if 'Eye' in organism_parts or 'eye' in disease_locations:\n", " trait_row = 3 if 'Eye' in organism_parts else 2 # Use organism part or disease location as proxy\n", " else:\n", " trait_row = None # Trait data not available\n", "\n", "# For age - No age information in the sample characteristics\n", "age_row = None # Age data not available\n", "\n", "# For gender - No gender information in the sample characteristics\n", "gender_row = None # Gender data not available\n", "\n", "# 2.2 Data Type Conversion\n", "# Convert trait (Retinoblastoma)\n", "def convert_trait(value: str) -> int:\n", " \"\"\"\n", " Convert trait value to binary (1 for Retinoblastoma, 0 for other diseases)\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ': ' in value:\n", " value = value.split(': ')[1]\n", " \n", " # Direct match for Retinoblastoma\n", " if value.lower() == 'retinoblastoma':\n", " return 1\n", " \n", " # Match for Eye-related diseases that might be retinoblastoma\n", " if trait_row == 3 and value == 'Eye':\n", " return 1\n", " \n", " return 0\n", "\n", "# Convert age function (not used in this case but defined for completeness)\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"\n", " Convert age value to continuous float\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ': ' in value:\n", " value = value.split(': ')[1]\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "# Convert gender function (not used in this case but defined for completeness)\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"\n", " Convert gender value to binary (0 for female, 1 for male)\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ': ' in value:\n", " value = value.split(': ')[1]\n", " \n", " value = value.lower()\n", " if 'female' in value or 'f' == value:\n", " return 0\n", " elif 'male' in value or 'm' == value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Perform initial filtering\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary\n", " clinical_data = pd.DataFrame(sample_characteristics_dict)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the selected clinical data\n", " print(\"Preview of selected clinical data:\")\n", " preview_data = preview_df(selected_clinical_df)\n", " print(preview_data)\n", " \n", " # Save the clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "35e4bb69", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "e8a18e2a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:03.221307Z", "iopub.status.busy": "2025-03-25T03:50:03.221193Z", "iopub.status.idle": "2025-03-25T03:50:04.400641Z", "shell.execute_reply": "2025-03-25T03:50:04.400253Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n", " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n", " '1494_f_at', '1598_g_at', '160020_at', '1729_at', '1773_at', '177_at',\n", " '179_at', '1861_at'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the file paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "35bf0dd8", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d8507ab9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:04.402060Z", "iopub.status.busy": "2025-03-25T03:50:04.401930Z", "iopub.status.idle": "2025-03-25T03:50:04.403967Z", "shell.execute_reply": "2025-03-25T03:50:04.403670Z" } }, "outputs": [], "source": [ "# Analyze the gene identifiers\n", "# The identifiers in the format '1007_s_at', '1053_at', etc. appear to be Affymetrix probe IDs\n", "# These are not standard human gene symbols (which would be like BRCA1, TP53, etc.)\n", "# They need to be mapped to official gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "cee759ee", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "04f3e76f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:04.405064Z", "iopub.status.busy": "2025-03-25T03:50:04.404948Z", "iopub.status.idle": "2025-03-25T03:50:25.610882Z", "shell.execute_reply": "2025-03-25T03:50:25.610498Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': [nan, nan, nan, nan, nan], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor family, member 1', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box gene 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001954 /// NM_013993 /// NM_013994', 'NM_002914 /// NM_181471', 'NM_002155 /// XM_001134322', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409'], 'Gene Ontology Biological Process': ['0006468 // protein amino acid phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation', '0006260 // DNA replication // inferred from electronic annotation', '0006457 // protein folding // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0006986 // response to unfolded protein // inferred from electronic annotation', '0001656 // metanephros development // inferred from electronic annotation /// 0006183 // GTP biosynthesis // inferred from electronic annotation /// 0006228 // UTP biosynthesis // inferred from electronic annotation /// 0006241 // CTP biosynthesis // inferred from electronic annotation /// 0006350 // transcription // inferred from electronic annotation /// 0009887 // organ morphogenesis // inferred from electronic annotation /// 0030154 // cell differentiation // inferred from electronic annotation /// 0045893 // positive regulation of transcription, DNA-dependent // inferred from sequence or structural similarity /// 0006355 // regulation of transcription, DNA-dependent // inferred from electronic annotation /// 0007275 // development // inferred from electronic annotation /// 0009653 // morphogenesis // traceable author statement', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // traceable author statement /// 0050896 // response to stimulus // inferred from electronic annotation /// 0007601 // visual perception // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005615 // extracellular space // inferred from electronic annotation /// 0005887 // integral to plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation', '0005634 // nucleus // inferred from electronic annotation /// 0005663 // DNA replication factor C complex // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from electronic annotation', nan, '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005667 // transcription factor complex // inferred from electronic annotation', nan], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004674 // protein serine/threonine kinase activity // inferred from electronic annotation /// 0004713 // protein-tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0004872 // receptor activity // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // traceable author statement /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0003700 // transcription factor activity // traceable author statement /// 0004550 // nucleoside diphosphate kinase activity // inferred from electronic annotation /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from sequence or structural similarity /// 0005524 // ATP binding // inferred from electronic annotation /// 0016563 // transcriptional activator activity // inferred from sequence or structural similarity /// 0003677 // DNA binding // inferred from electronic annotation', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // traceable author statement']}\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "22b039d4", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "97ec3687", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:25.612734Z", "iopub.status.busy": "2025-03-25T03:50:25.612616Z", "iopub.status.idle": "2025-03-25T03:50:26.910346Z", "shell.execute_reply": "2025-03-25T03:50:26.909944Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data after mapping:\n", "Number of genes: 13046\n", "First 5 gene symbols:\n", "['A2BP1', 'A2M', 'A4GALT', 'A4GNT', 'AAAS']\n" ] } ], "source": [ "# 1. Identify the columns containing gene identifiers and gene symbols\n", "# Looking at the gene annotation preview, we can see:\n", "# - 'ID' column contains identifiers like '1007_s_at', which matches the gene expression data\n", "# - 'Gene Symbol' column contains the actual gene symbols like 'DDR1'\n", "\n", "# 2. Get a gene mapping dataframe by extracting these two columns\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Gene Symbol')\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Print some information about the resulting gene expression data\n", "print(\"Gene expression data after mapping:\")\n", "print(f\"Number of genes: {len(gene_data)}\")\n", "print(\"First 5 gene symbols:\")\n", "print(gene_data.index[:5].tolist())\n" ] }, { "cell_type": "markdown", "id": "80c8243c", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "3b7e5eb0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:50:26.912261Z", "iopub.status.busy": "2025-03-25T03:50:26.912135Z", "iopub.status.idle": "2025-03-25T03:50:32.329976Z", "shell.execute_reply": "2025-03-25T03:50:32.329594Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (12700, 798)\n", "First few normalized gene symbols: ['A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAK1', 'AAMDC', 'AAMP', 'AANAT']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Retinoblastoma/gene_data/GSE68950.csv\n", "WARNING: Could not find trait_row. Creating a minimal clinical dataframe.\n", "Linked data shape: (799, 12701)\n", "First few columns in linked data: ['Retinoblastoma', 'A2M', 'A4GALT', 'A4GNT', 'AAAS']\n", "Using trait column: Retinoblastoma\n", "Shape after handling missing values: (0, 1)\n", "No samples remain after handling missing values. The dataset cannot be processed further.\n", "Abnormality detected in the cohort: GSE68950. Preprocessing failed.\n", "Data quality check failed. The dataset is not suitable for association studies.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Link the clinical and genetic data\n", "# Extract clinical features directly using the information from previous steps\n", "if 'trait_row' in globals() and trait_row is not None:\n", " # Re-extract clinical features from the clinical data\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " print(f\"Clinical features extracted with shape: {selected_clinical_df.shape}\")\n", "else:\n", " # Fallback - create a dummy dataframe with just the trait column\n", " print(\"WARNING: Could not find trait_row. Creating a minimal clinical dataframe.\")\n", " selected_clinical_df = pd.DataFrame({trait: [1]}) # Dummy value\n", " is_trait_available = False\n", "\n", "# Transpose clinical features for linking\n", "selected_clinical_df_t = selected_clinical_df.T\n", "\n", "# Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df_t, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(f\"First few columns in linked data: {list(linked_data.columns[:5])}\")\n", "\n", "# 3. Handle missing values in the linked data\n", "# Determine the trait column (should be the first column)\n", "if trait in linked_data.columns:\n", " trait_column = trait\n", "else:\n", " # Just use the first column\n", " trait_column = linked_data.columns[0]\n", "print(f\"Using trait column: {trait_column}\")\n", "\n", "linked_data_processed = handle_missing_values(linked_data, trait_column)\n", "print(f\"Shape after handling missing values: {linked_data_processed.shape}\")\n", "\n", "# Add validation check - if no samples remain, note the issue\n", "if linked_data_processed.shape[0] == 0:\n", " print(\"No samples remain after handling missing values. The dataset cannot be processed further.\")\n", " is_trait_biased = True # Mark as biased since we can't use it\n", " unbiased_linked_data = linked_data_processed\n", "else:\n", " # 4. Determine whether the trait and demographic features are severely biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_processed, trait_column)\n", "\n", "# 5. Conduct quality check and save the cohort information\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True, \n", " cohort=cohort, \n", " info_path=json_path, \n", " is_gene_available=True, \n", " is_trait_available=True,\n", " is_biased=is_trait_biased, \n", " df=unbiased_linked_data,\n", " note=f\"Dataset contains gene expression data from cell lines with {trait} information.\"\n", ")\n", "\n", "# 6. Save the data if it's usable\n", "if is_usable:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " # Save the data\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Data quality check failed. The dataset is not suitable for association studies.\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }