{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "780f5bef", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:09:06.799941Z", "iopub.status.busy": "2025-03-25T07:09:06.799763Z", "iopub.status.idle": "2025-03-25T07:09:06.969403Z", "shell.execute_reply": "2025-03-25T07:09:06.969071Z" } }, "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 = \"Intellectual_Disability\"\n", "cohort = \"GSE100680\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Intellectual_Disability\"\n", "in_cohort_dir = \"../../input/GEO/Intellectual_Disability/GSE100680\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Intellectual_Disability/GSE100680.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Intellectual_Disability/gene_data/GSE100680.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Intellectual_Disability/clinical_data/GSE100680.csv\"\n", "json_path = \"../../output/preprocess/Intellectual_Disability/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "c9a6d4f1", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "9deac71f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:09:06.970785Z", "iopub.status.busy": "2025-03-25T07:09:06.970647Z", "iopub.status.idle": "2025-03-25T07:09:07.097372Z", "shell.execute_reply": "2025-03-25T07:09:07.097012Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"APP levels mediate beta-amyloid but not tau-related aspects of Alzheimer’s disease in a Down syndrome model of cortical neurogenesis.\"\n", "!Series_summary\t\"Early-onset Alzheimer’s disease-like pathology in Down syndrome (DS, trisomy 21) is commonly attributed to an increased dosage of the amyloid precursor protein (APP) gene. To test this central tenet of the amyloid-cascade hypothesis we deleted the supernumerary copy of the APP gene in trisomic DS iPSC, or upregulated APP expression in euploid human pluripotent stem cell lines with dCas9-VP64, and subjected these lines to prolonged cortical neural differentiation. Our data reveal that increased APP gene dosage and expression is necessary and sufficient for increased beta-amyloid production and pyroglutamate(E3)-containing plaque deposition, but is neither sufficient nor required for tau hyperphosphorylation, neurofibrillary tangle formation, or increased oxidative stress-induced apoptosis in neurons. Transcriptome comparisons of the isogenic neurons demonstrates that the supernumerary APP gene copy has profound temporally-modulated genome-wide effects on gene expression during differentiation and maturation of DS neuronal cultures that link APP function to regulation of genes involved in neuronal synaptic function and outgrowth of neuronal processes. Collectively, our data reveal that APP plays an important role in the amyloidogenic aspects of Alzheimer’s disease, but challenge the hypothesis that increased APP levels are solely responsible for hyperphosphorylation of tau or enhanced oxidative stress-induced neuronal cell death in Down syndrome associated AD-pathogenesis.\"\n", "!Series_overall_design\t\"34 samples\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cell type: Neuronal differentiation culture'], 1: ['cell line: 11', 'cell line: 86', 'cell line: 18', 'cell line: 87', 'cell line: A3', 'cell line: 79'], 2: ['age: Day 45', 'age: Day 65'], 3: ['description: DS Clone C11 Day 45', 'description: Euploid Clone C86 Day 45', 'description: DS Clone C11 Day 65', 'description: Euploid Clone C86 Day 65', 'description: DS Clone C18 Day 45', 'description: Euploid Clone C87 Day 45', 'description: DS Clone C18 Day 65', 'description: Euploid Clone C87 Day 65', 'description: APP copy number-corrected DS Clone A3 Day 45', 'description: Euploid Clone C79 Day 45', 'description: APP copy number-corrected DS Clone A3 Day 65', 'description: Euploid Clone C79 Day 65']}\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": "ba21fce5", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b863c600", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:09:07.099144Z", "iopub.status.busy": "2025-03-25T07:09:07.099007Z", "iopub.status.idle": "2025-03-25T07:09:07.120253Z", "shell.execute_reply": "2025-03-25T07:09:07.119949Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical data:\n", "{'GSM2691139': [1.0, 45.0], 'GSM2691140': [1.0, 45.0], 'GSM2691141': [0.0, 45.0], 'GSM2691142': [0.0, 45.0], 'GSM2691143': [0.0, 45.0], 'GSM2691144': [1.0, 65.0], 'GSM2691145': [1.0, 65.0], 'GSM2691146': [1.0, 65.0], 'GSM2691147': [0.0, 65.0], 'GSM2691148': [0.0, 65.0], 'GSM2691149': [0.0, 65.0], 'GSM2691150': [1.0, 45.0], 'GSM2691151': [1.0, 45.0], 'GSM2691152': [0.0, 45.0], 'GSM2691153': [0.0, 45.0], 'GSM2691154': [0.0, 45.0], 'GSM2691155': [1.0, 65.0], 'GSM2691156': [1.0, 65.0], 'GSM2691157': [1.0, 65.0], 'GSM2691158': [0.0, 65.0], 'GSM2691159': [0.0, 65.0], 'GSM2691160': [0.0, 65.0], 'GSM2691161': [1.0, 45.0], 'GSM2691162': [1.0, 45.0], 'GSM2691163': [1.0, 45.0], 'GSM2691164': [0.0, 45.0], 'GSM2691165': [0.0, 45.0], 'GSM2691166': [0.0, 45.0], 'GSM2691167': [1.0, 65.0], 'GSM2691168': [1.0, 65.0], 'GSM2691169': [1.0, 65.0], 'GSM2691170': [0.0, 65.0], 'GSM2691171': [0.0, 65.0], 'GSM2691172': [0.0, 65.0]}\n", "Clinical data saved to ../../output/preprocess/Intellectual_Disability/clinical_data/GSE100680.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# From the background information, this dataset involves neuronal cultures from Down syndrome and euploid samples,\n", "# which likely contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# From analyzing the Sample Characteristics Dictionary:\n", "\n", "# Trait (Intellectual Disability): The trait can be inferred from the description field (key 3)\n", "# Down Syndrome (DS) vs Euploid samples\n", "trait_row = 3\n", "\n", "# Age: Age information is available in key 2\n", "age_row = 2\n", "\n", "# Gender: Not available in the data\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"Convert trait value to binary (0=control, 1=case)\"\"\"\n", " if value is None or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip()\n", " \n", " # DS (Down Syndrome) samples are cases (1), Euploid are controls (0)\n", " if 'DS ' in value:\n", " return 1\n", " elif 'Euploid' in value:\n", " return 0\n", " elif 'APP copy number-corrected DS' in value:\n", " # These are genetically modified DS samples where APP copy number is corrected\n", " # For the intellectual disability trait, they still have DS but with APP correction\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous (days)\"\"\"\n", " if value is None or ':' not in value:\n", " return None\n", " \n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'Day ' in value:\n", " try:\n", " return int(value.replace('Day ', ''))\n", " except:\n", " return None\n", " else:\n", " return None\n", "\n", "# No gender information available, but still define the function in case needed\n", "def convert_gender(value):\n", " \"\"\"Convert gender value to binary (0=female, 1=male)\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial filtering results\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", " # Use the library function to extract clinical features\n", " 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 clinical data\n", " print(\"Preview of clinical data:\")\n", " print(preview_df(clinical_df))\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "80908caa", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "bcc71497", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:09:07.121833Z", "iopub.status.busy": "2025-03-25T07:09:07.121724Z", "iopub.status.idle": "2025-03-25T07:09:07.309693Z", "shell.execute_reply": "2025-03-25T07:09:07.309301Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene data from matrix file:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene data with 47323 rows\n", "First 20 gene IDs:\n", "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data available: True\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Extract gene expression data from the matrix file\n", "try:\n", " print(\"Extracting gene data from matrix file:\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n" ] }, { "cell_type": "markdown", "id": "ee589bb7", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "b5b96f0f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:09:07.311451Z", "iopub.status.busy": "2025-03-25T07:09:07.311311Z", "iopub.status.idle": "2025-03-25T07:09:07.313506Z", "shell.execute_reply": "2025-03-25T07:09:07.313185Z" } }, "outputs": [], "source": [ "# The gene identifiers observed in the gene expression data are in the format \"ILMN_XXXXXXX\"\n", "# These are Illumina probe IDs used in their microarray platforms, not human gene symbols\n", "# Illumina probe IDs need to be mapped to human gene symbols for proper analysis\n", "\n", "# Based on biomedical knowledge, these are Illumina BeadArray probe identifiers and not human gene symbols\n", "# These identifiers will need to be mapped to official gene symbols for meaningful biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "2df089c6", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "acf5ee07", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:09:07.315061Z", "iopub.status.busy": "2025-03-25T07:09:07.314944Z", "iopub.status.idle": "2025-03-25T07:09:11.329417Z", "shell.execute_reply": "2025-03-25T07:09:11.329015Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene annotation data with 1657123 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 47323 out of 1657123\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "b475881c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "8a4f73a1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:09:11.331376Z", "iopub.status.busy": "2025-03-25T07:09:11.331223Z", "iopub.status.idle": "2025-03-25T07:09:11.532839Z", "shell.execute_reply": "2025-03-25T07:09:11.532448Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining gene annotation columns for mapping...\n", "Using probe identifiers from column 'ID' and gene symbols from column 'Symbol'\n", "Creating gene mapping dataframe...\n", "Created mapping with 44837 probe-to-gene mappings\n", "\n", "Preview of gene mapping data:\n", " ID Gene\n", "0 ILMN_1343048 phage_lambda_genome\n", "1 ILMN_1343049 phage_lambda_genome\n", "2 ILMN_1343050 phage_lambda_genome:low\n", "3 ILMN_1343052 phage_lambda_genome:low\n", "4 ILMN_1343059 thrB\n", "\n", "Number of probes in expression data: 47323\n", "Number of probes in mapping data: 44837\n", "Number of common probes: 44053\n", "Percentage of expression probes with mapping: 93.09%\n", "\n", "Converting probe-level measurements to gene-level expression data...\n", "Converted to gene expression data with 21464 unique genes\n", "After filtering invalid gene names: 21464 genes\n", "\n", "Preview of gene expression data:\n", " GSM2691139 GSM2691140 GSM2691141 GSM2691142 GSM2691143 GSM2691144 \\\n", "Gene \n", "A1BG 3.386185 3.741574 4.444152 2.138936 4.235359 4.457894 \n", "A1CF 3.297111 4.144043 4.318145 4.585333 3.815035 5.303153 \n", "A26C3 4.344801 3.155623 2.802268 3.319847 3.532394 4.376008 \n", "A2BP1 4.729827 3.786035 5.946923 6.431660 6.126309 5.500373 \n", "A2LD1 1.514547 1.785969 2.145789 2.752055 2.016330 2.996562 \n", "\n", " GSM2691145 GSM2691146 GSM2691147 GSM2691148 ... GSM2691163 \\\n", "Gene ... \n", "A1BG 4.519041 3.513171 4.640722 4.425241 ... 4.164596 \n", "A1CF 4.018396 5.132490 3.629145 3.907379 ... 5.657749 \n", "A26C3 3.312404 3.621019 3.163887 3.957929 ... 3.523963 \n", "A2BP1 5.218515 6.811439 6.281199 7.096255 ... 13.020934 \n", "A2LD1 2.713930 3.702378 1.474151 1.574458 ... 1.660302 \n", "\n", " GSM2691164 GSM2691165 GSM2691166 GSM2691167 GSM2691168 GSM2691169 \\\n", "Gene \n", "A1BG 2.394874 4.860065 3.539867 3.208778 5.036604 3.801865 \n", "A1CF 5.596667 3.619013 3.784241 3.145954 2.879380 2.571520 \n", "A26C3 5.372538 5.188917 3.705529 4.478978 4.706186 3.505272 \n", "A2BP1 4.115227 5.513224 6.123940 7.524961 4.909962 6.054471 \n", "A2LD1 2.435365 2.113169 1.775329 3.239668 3.260433 4.096992 \n", "\n", " GSM2691170 GSM2691171 GSM2691172 \n", "Gene \n", "A1BG 3.747525 3.853939 3.870730 \n", "A1CF 3.227897 4.329409 3.896011 \n", "A26C3 4.213592 5.465881 4.043737 \n", "A2BP1 5.783457 5.252155 5.128967 \n", "A2LD1 3.393644 3.592446 2.305633 \n", "\n", "[5 rows x 34 columns]\n" ] } ], "source": [ "# 1. Identify which columns contain the probe identifiers and gene symbols\n", "print(\"Examining gene annotation columns for mapping...\")\n", "\n", "# The 'ID' column in gene_annotation contains the probe identifiers (ILMN_XXXXXXX)\n", "# The 'Symbol' column contains the gene symbols\n", "prob_col = 'ID'\n", "gene_col = 'Symbol'\n", "\n", "print(f\"Using probe identifiers from column '{prob_col}' and gene symbols from column '{gene_col}'\")\n", "\n", "# 2. Get a gene mapping dataframe\n", "print(\"Creating gene mapping dataframe...\")\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Created mapping with {len(mapping_df)} probe-to-gene mappings\")\n", "\n", "# Preview the mapping dataframe\n", "print(\"\\nPreview of gene mapping data:\")\n", "print(mapping_df.head())\n", "\n", "# Check if we have mappings for probes in our gene expression data\n", "probes_in_expression = set(gene_data.index)\n", "probes_in_mapping = set(mapping_df['ID'])\n", "common_probes = probes_in_expression.intersection(probes_in_mapping)\n", "print(f\"\\nNumber of probes in expression data: {len(probes_in_expression)}\")\n", "print(f\"Number of probes in mapping data: {len(probes_in_mapping)}\")\n", "print(f\"Number of common probes: {len(common_probes)}\")\n", "print(f\"Percentage of expression probes with mapping: {len(common_probes)/len(probes_in_expression)*100:.2f}%\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "print(\"\\nConverting probe-level measurements to gene-level expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Converted to gene expression data with {len(gene_data)} unique genes\")\n", "\n", "# Check for gene names that are null or empty strings\n", "valid_genes = gene_data.index.notnull() & (gene_data.index != '')\n", "gene_data = gene_data[valid_genes]\n", "print(f\"After filtering invalid gene names: {len(gene_data)} genes\")\n", "\n", "# Preview of the final gene expression data\n", "print(\"\\nPreview of gene expression data:\")\n", "print(gene_data.head())\n" ] }, { "cell_type": "markdown", "id": "47713e8f", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "de3c5f31", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:09:11.534708Z", "iopub.status.busy": "2025-03-25T07:09:11.534567Z", "iopub.status.idle": "2025-03-25T07:09:21.292352Z", "shell.execute_reply": "2025-03-25T07:09:21.291545Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization, gene data has 20259 genes\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to: ../../output/preprocess/Intellectual_Disability/gene_data/GSE100680.csv\n", "\n", "Loading clinical data and linking with genetic data...\n", "Loaded clinical data with shape: (2, 34)\n", "First few clinical sample columns: ['GSM2691139', 'GSM2691140', 'GSM2691141', 'GSM2691142', 'GSM2691143']\n", "First few genetic sample columns: ['GSM2691139', 'GSM2691140', 'GSM2691141', 'GSM2691142', 'GSM2691143']\n", "Linked data shape: (34, 20261)\n", "\n", "Handling missing values...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, data shape: (34, 20261)\n", "\n", "Checking for bias in features...\n", "For the feature 'Intellectual_Disability', the least common label is '1.0' with 16 occurrences. This represents 47.06% of the dataset.\n", "The distribution of the feature 'Intellectual_Disability' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 45.0\n", " 50% (Median): 65.0\n", " 75%: 65.0\n", "Min: 45.0\n", "Max: 65.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "\n", "Performing final validation...\n", "A new JSON file was created at: ../../output/preprocess/Intellectual_Disability/cohort_info.json\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Intellectual_Disability/GSE100680.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"\\nNormalizing gene symbols...\")\n", "try:\n", " gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization, gene data has {len(gene_data.index)} genes\")\n", " \n", " # Save the normalized gene data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to: {out_gene_data_file}\")\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error during gene symbol normalization: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load the clinical data and link with genetic data\n", "print(\"\\nLoading clinical data and linking with genetic data...\")\n", "try:\n", " # Load the clinical data\n", " clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", " \n", " # Print sample IDs from both datasets for debugging\n", " print(\"First few clinical sample columns:\", list(clinical_df.columns)[:5])\n", " print(\"First few genetic sample columns:\", list(gene_data.columns)[:5])\n", " \n", " # Convert column names in gene_data to match clinical_df format\n", " gene_data_renamed = gene_data.copy()\n", " sample_mapping = {}\n", " \n", " # Check if we need to transform sample IDs for matching\n", " if set(clinical_df.columns).isdisjoint(set(gene_data.columns)):\n", " print(\"Sample IDs don't match directly. Attempting to align based on position...\")\n", " # If the number of samples matches, assume they're in the same order\n", " if len(clinical_df.columns) == len(gene_data.columns):\n", " sample_mapping = dict(zip(gene_data.columns, clinical_df.columns))\n", " gene_data_renamed.columns = clinical_df.columns\n", " print(\"Aligned samples based on position (same count of samples)\")\n", " else:\n", " print(\"Cannot align samples - different counts in clinical and genetic data\")\n", " raise ValueError(\"Sample counts don't match between clinical and genetic data\")\n", " \n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data_renamed)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " is_trait_available = True\n", " \n", " # 3. Handle missing values systematically\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values, data shape: {linked_data.shape}\")\n", " \n", " # 4. Determine whether the trait and demographic features are biased\n", " print(\"\\nChecking for bias in features...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", "except Exception as e:\n", " print(f\"Error in linking clinical and genetic data: {e}\")\n", " is_trait_available = clinical_df is not None\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 5. Final quality validation\n", "print(\"\\nPerforming final validation...\")\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=\"ATR-X syndrome patients as intellectual disability cases\"\n", ")\n", "\n", "# 6. Save linked data if 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", " \n", " # Save linked data\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Dataset not usable for {trait} association studies. Data not saved.\")" ] } ], "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 }