{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "7a3c8734", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:38:45.992760Z", "iopub.status.busy": "2025-03-25T07:38:45.992598Z", "iopub.status.idle": "2025-03-25T07:38:46.158571Z", "shell.execute_reply": "2025-03-25T07:38:46.158220Z" } }, "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 = \"Lower_Grade_Glioma\"\n", "cohort = \"GSE35158\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Lower_Grade_Glioma\"\n", "in_cohort_dir = \"../../input/GEO/Lower_Grade_Glioma/GSE35158\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Lower_Grade_Glioma/GSE35158.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Lower_Grade_Glioma/gene_data/GSE35158.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Lower_Grade_Glioma/clinical_data/GSE35158.csv\"\n", "json_path = \"../../output/preprocess/Lower_Grade_Glioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "80087a11", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "fdedaea2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:38:46.160030Z", "iopub.status.busy": "2025-03-25T07:38:46.159883Z", "iopub.status.idle": "2025-03-25T07:38:46.250287Z", "shell.execute_reply": "2025-03-25T07:38:46.250012Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Expression profiling of lower-grade diffuse astrocytic glioma\"\n", "!Series_summary\t\"Diffuse gliomas represent the most prevalent class of primary brain tumor. Despite significant recent advances in the understanding of glioblastoma (WHO IV), its most malignant subtype, lower-grade (WHO II and III) glioma variants remain comparatively understudied, especially in light of their notably variable clinical behavior. To examine the foundations of this heterogeneity, we performed multidimensional molecular profiling, including global transcriptional analysis, on 101 lower-grade diffuse astrocytic gliomas collected at our own institution, and validated our findings using publically available gene expression and copy number data from large independent patient cohorts. We found that IDH mutational status delineated molecularly and clinically distinct glioma subsets, with IDH mutant (IDH mt) tumors exhibiting TP53 mutations, PDGFRA overexpression, and prolonged survival, and IDH wild-type (IDH wt) tumors exhibiting EGFR amplification, PTEN loss, and unfavorable disease outcome. Furthermore, global expression profiling revealed three robust molecular subclasses within lower-grade diffuse astrocytic gliomas, two of which were predominantly IDH mt and one almost entirely IDH wt. IDH mt subclasses were distinguished from each other on the basis of TP53 mutations, DNA copy number abnormalities, and links to distinct stages of neurogenesis in the subventricular zone (SVZ). This latter finding implicates discrete pools of neuroglial progenitors as cells of origin for the different subclasses of IDH mt tumors. In summary, we have elucidated molecularly distinct subclasses of lower-grade diffuse astrocytic glioma that dictate clinical behavior and demonstrate fundamental associations with both IDH mutational status and neuroglial developmental stage.\"\n", "!Series_overall_design\t\"80 tumor samples, one normal tissue sample (brain)\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tumor type: normal brain', 'tumor type: diffuse astrocytic glioma'], 1: [nan, 'who grade: III', 'who grade: II'], 2: [nan, 'subclass: PG', 'subclass: NB', 'subclass: EPL'], 3: [nan, 'idh mut status: wt', 'idh mut status: mut'], 4: [nan, 'pten methylation: U', 'pten methylation: M', 'pten methylation: NA'], 5: [nan, 'cdkn2a methylation: U', 'cdkn2a methylation: NA', 'cdkn2a methylation: M'], 6: [nan, 'tp53 seq: mut', 'tp53 seq: wt', 'tp53 seq: NA'], 7: [nan, 'pten del: No', 'pten del: NA', 'pten del: Yes'], 8: [nan, 'pdgfra ihc: -', 'pdgfra ihc: +'], 9: [nan, 'p53 ihc: +', 'p53 ihc: -'], 10: [nan, 'p-pras40 ihc: +', 'p-pras40 ihc: -', 'p-pras40 ihc: NA'], 11: [nan, 'egfr amp: No', 'egfr amp: Yes', 'egfr amp: NA']}\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": "5bad60eb", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "cd772ffb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:38:46.251385Z", "iopub.status.busy": "2025-03-25T07:38:46.251279Z", "iopub.status.idle": "2025-03-25T07:38:46.260133Z", "shell.execute_reply": "2025-03-25T07:38:46.259863Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical data:\n", "{'GSM864095': [nan], 'GSM864096': [1.0], 'GSM864097': [1.0], 'GSM864098': [1.0], 'GSM864099': [1.0], 'GSM864100': [1.0], 'GSM864101': [1.0], 'GSM864102': [1.0], 'GSM864103': [1.0], 'GSM864104': [1.0], 'GSM864105': [1.0], 'GSM864106': [1.0], 'GSM864107': [1.0], 'GSM864108': [1.0], 'GSM864109': [1.0], 'GSM864110': [1.0], 'GSM864111': [1.0], 'GSM864112': [1.0], 'GSM864113': [1.0], 'GSM864114': [1.0], 'GSM864115': [1.0], 'GSM864116': [1.0], 'GSM864117': [1.0], 'GSM864118': [1.0], 'GSM864119': [1.0], 'GSM864120': [1.0], 'GSM864121': [1.0], 'GSM864122': [1.0], 'GSM864123': [1.0], 'GSM864124': [1.0], 'GSM864125': [1.0], 'GSM864126': [1.0], 'GSM864127': [0.0], 'GSM864128': [0.0], 'GSM864129': [0.0], 'GSM864130': [0.0], 'GSM864131': [0.0], 'GSM864132': [0.0], 'GSM864133': [0.0], 'GSM864134': [1.0], 'GSM864135': [0.0], 'GSM864136': [0.0], 'GSM864137': [0.0], 'GSM864138': [0.0], 'GSM864139': [1.0], 'GSM864140': [0.0], 'GSM864141': [1.0], 'GSM864142': [1.0], 'GSM864143': [1.0], 'GSM864144': [0.0], 'GSM864145': [0.0], 'GSM864146': [1.0], 'GSM864147': [0.0], 'GSM864148': [1.0], 'GSM864149': [1.0], 'GSM864150': [0.0], 'GSM864151': [0.0], 'GSM864152': [0.0], 'GSM864153': [0.0], 'GSM864154': [0.0], 'GSM864155': [1.0], 'GSM864156': [1.0], 'GSM864157': [1.0], 'GSM864158': [1.0], 'GSM864159': [1.0], 'GSM864160': [1.0], 'GSM864161': [1.0], 'GSM864162': [1.0], 'GSM864163': [1.0], 'GSM864164': [0.0], 'GSM864165': [0.0], 'GSM864166': [1.0], 'GSM864167': [0.0], 'GSM864168': [0.0], 'GSM864169': [0.0], 'GSM864170': [1.0], 'GSM864171': [1.0], 'GSM864172': [0.0], 'GSM864173': [0.0], 'GSM864174': [0.0], 'GSM864175': [0.0]}\n", "Clinical data saved to ../../output/preprocess/Lower_Grade_Glioma/clinical_data/GSE35158.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains expression profiling\n", "# of lower-grade diffuse astrocytic glioma, which indicates gene expression data availability\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Lower_Grade_Glioma), WHO grade could be used as it represents glioma grade\n", "# Index 1 contains WHO grade information\n", "trait_row = 1 \n", "\n", "# Age information is not available in the sample characteristics\n", "age_row = None\n", "\n", "# Gender information is not available in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert WHO grade information to binary format\"\"\"\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value:\n", " grade = value.split(':', 1)[1].strip()\n", " if grade == 'II':\n", " return 0 # Lower grade\n", " elif grade == 'III':\n", " return 1 # Higher grade\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous format\"\"\"\n", " # Since age data is not available, define a placeholder function\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary format\"\"\"\n", " # Since gender data is not available, define a placeholder function\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available since trait_row is not None\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info (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", "# Since trait_row is not None, we proceed with clinical feature extraction\n", "if trait_row is not None:\n", " # Extract clinical features using the library function\n", " clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data, # Assumes clinical_data is available from previous step\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 extracted clinical data\n", " preview = preview_df(clinical_df)\n", " print(\"Preview of clinical data:\")\n", " print(preview)\n", " \n", " # Save the clinical data as CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " 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": "6a58a33e", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "7dd7cf40", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:38:46.261178Z", "iopub.status.busy": "2025-03-25T07:38:46.261073Z", "iopub.status.idle": "2025-03-25T07:38:46.406858Z", "shell.execute_reply": "2025-03-25T07:38:46.406498Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Expression profiling of lower-grade diffuse astrocytic glioma\"\n", "Line 1: !Series_geo_accession\t\"GSE35158\"\n", "Line 2: !Series_status\t\"Public on Feb 24 2012\"\n", "Line 3: !Series_submission_date\t\"Jan 17 2012\"\n", "Line 4: !Series_last_update_date\t\"Dec 22 2017\"\n", "Line 5: !Series_pubmed_id\t\"22415316\"\n", "Line 6: !Series_summary\t\"Diffuse gliomas represent the most prevalent class of primary brain tumor. Despite significant recent advances in the understanding of glioblastoma (WHO IV), its most malignant subtype, lower-grade (WHO II and III) glioma variants remain comparatively understudied, especially in light of their notably variable clinical behavior. To examine the foundations of this heterogeneity, we performed multidimensional molecular profiling, including global transcriptional analysis, on 101 lower-grade diffuse astrocytic gliomas collected at our own institution, and validated our findings using publically available gene expression and copy number data from large independent patient cohorts. We found that IDH mutational status delineated molecularly and clinically distinct glioma subsets, with IDH mutant (IDH mt) tumors exhibiting TP53 mutations, PDGFRA overexpression, and prolonged survival, and IDH wild-type (IDH wt) tumors exhibiting EGFR amplification, PTEN loss, and unfavorable disease outcome. Furthermore, global expression profiling revealed three robust molecular subclasses within lower-grade diffuse astrocytic gliomas, two of which were predominantly IDH mt and one almost entirely IDH wt. IDH mt subclasses were distinguished from each other on the basis of TP53 mutations, DNA copy number abnormalities, and links to distinct stages of neurogenesis in the subventricular zone (SVZ). This latter finding implicates discrete pools of neuroglial progenitors as cells of origin for the different subclasses of IDH mt tumors. In summary, we have elucidated molecularly distinct subclasses of lower-grade diffuse astrocytic glioma that dictate clinical behavior and demonstrate fundamental associations with both IDH mutational status and neuroglial developmental stage.\"\n", "Line 7: !Series_overall_design\t\"80 tumor samples, one normal tissue sample (brain)\"\n", "Line 8: !Series_type\t\"Expression profiling by array\"\n", "Line 9: !Series_contributor\t\"Jason,T,Huse\"\n", "Found table marker at line 67\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM864095\"\t\"GSM864096\"\t\"GSM864097\"\t\"GSM864098\"\t\"GSM864099\"\t\"GSM864100\"\t\"GSM864101\"\t\"GSM864102\"\t\"GSM864103\"\t\"GSM864104\"\t\"GSM864105\"\t\"GSM864106\"\t\"GSM864107\"\t\"GSM864108\"\t\"GSM864109\"\t\"GSM864110\"\t\"GSM864111\"\t\"GSM864112\"\t\"GSM864113\"\t\"GSM864114\"\t\"GSM864115\"\t\"GSM864116\"\t\"GSM864117\"\t\"GSM864118\"\t\"GSM864119\"\t\"GSM864120\"\t\"GSM864121\"\t\"GSM864122\"\t\"GSM864123\"\t\"GSM864124\"\t\"GSM864125\"\t\"GSM864126\"\t\"GSM864127\"\t\"GSM864128\"\t\"GSM864129\"\t\"GSM864130\"\t\"GSM864131\"\t\"GSM864132\"\t\"GSM864133\"\t\"GSM864134\"\t\"GSM864135\"\t\"GSM864136\"\t\"GSM864137\"\t\"GSM864138\"\t\"GSM864139\"\t\"GSM864140\"\t\"GSM864141\"\t\"GSM864142\"\t\"GSM864143\"\t\"GSM864144\"\t\"GSM864145\"\t\"GSM864146\"\t\"GSM864147\"\t\"GSM864148\"\t\"GSM864149\"\t\"GSM864150\"\t\"GSM864151\"\t\"GSM864152\"\t\"GSM864153\"\t\"GSM864154\"\t\"GSM864155\"\t\"GSM864156\"\t\"GSM864157\"\t\"GSM864158\"\t\"GSM864159\"\t\"GSM864160\"\t\"GSM864161\"\t\"GSM864162\"\t\"GSM864163\"\t\"GSM864164\"\t\"GSM864165\"\t\"GSM864166\"\t\"GSM864167\"\t\"GSM864168\"\t\"GSM864169\"\t\"GSM864170\"\t\"GSM864171\"\t\"GSM864172\"\t\"GSM864173\"\t\"GSM864174\"\t\"GSM864175\"\n", "\"ILMN_1651209\"\t7.08126\t7.02804\t7.04731\t6.89578\t7.54783\t7.05696\t7.02078\t7.08857\t6.93991\t7.23049\t6.60437\t7.38482\t7.18075\t7.11735\t6.88227\t7.1962\t7.2447\t7.38821\t6.94583\t6.76593\t7.43787\t7.00214\t7.51365\t7.10996\t7.23082\t7.53687\t7.04329\t6.8416\t7.23549\t6.84703\t6.99488\t7.13909\t7.61287\t6.87346\t7.36228\t6.79926\t7.35473\t7.30736\t7.54357\t7.38545\t7.049\t7.06068\t7.23653\t7.74003\t7.46165\t7.44614\t7.53181\t7.29711\t7.49217\t7.48644\t6.85227\t7.08256\t6.89634\t7.40867\t7.38585\t7.64998\t7.16561\t7.15036\t7.3021\t7.63221\t7.36321\t6.84507\t7.37929\t7.6357\t7.62147\t6.80186\t7.47936\t7.4296\t6.7716\t7.60652\t7.13021\t8.39485\t8.31617\t7.57317\t6.61048\t7.14696\t6.64119\t6.9018\t7.34592\t6.85502\t6.88195\n", "\"ILMN_1651228\"\t12.2664\t11.8163\t12.2526\t12.7677\t12.5551\t12.591\t12.4412\t12.6828\t12.068\t12.2492\t12.0479\t12.4303\t12.2107\t12.461\t12.3968\t12.2514\t12.1392\t12.4451\t12.5055\t12.2688\t12.3488\t12.1465\t12.7872\t12.6682\t12.591\t12.6699\t12.6931\t12.6182\t12.5941\t12.1694\t12.2322\t12.4907\t12.0774\t12.3359\t12.4724\t12.3886\t12.4343\t12.408\t12.4291\t12.3655\t12.5126\t12.5398\t12.5185\t12.5466\t12.3457\t12.3432\t12.5835\t12.5014\t12.3298\t12.2107\t12.418\t12.3819\t12.1339\t12.7227\t12.8848\t12.5084\t12.8652\t12.7923\t12.7432\t12.7084\t11.886\t11.9479\t12.0045\t12.5221\t12.4982\t12.145\t12.1628\t12.5892\t11.8123\t12.6845\t12.4313\t12.7194\t12.8489\t12.8557\t12.7538\t11.3313\t11.6043\t11.2992\t11.6019\t7.72358\t11.1593\n", "\"ILMN_1651229\"\t11.5187\t11.1847\t10.522\t10.8389\t10.725\t11.0925\t11.2993\t9.72791\t10.8801\t10.725\t11.2359\t11.2669\t11.1058\t11.4103\t11.0338\t10.6141\t10.6586\t10.1458\t9.95467\t10.6019\t10.1596\t10.7588\t10.4447\t10.5559\t10.7298\t10.1463\t10.4749\t10.8339\t10.4853\t10.5889\t10.6348\t10.488\t10.9438\t11.6005\t11.2008\t11.136\t10.808\t11.0526\t10.2388\t10.9734\t10.9477\t10.7754\t10.0276\t10.8622\t10.3862\t11.2159\t10.7322\t10.9208\t11.2407\t11.4821\t10.0173\t11.1699\t11.1571\t10.3179\t11.1183\t10.7435\t10.6582\t10.6113\t10.71\t9.70335\t10.4554\t10.7201\t8.86099\t9.67662\t10.4608\t10.0249\t10.145\t9.80835\t10.8593\t9.99555\t10.4162\t10.158\t9.88498\t9.72949\t9.72235\t8.09054\t8.93811\t9.89586\t7.60621\t8.16145\t8.77942\n", "\"ILMN_1651235\"\t11.0662\t11.1127\t12.095\t12.0406\t11.6247\t11.7356\t11.4617\t12.1964\t11.8319\t11.6046\t11.2818\t11.7259\t11.7324\t11.632\t11.8523\t11.8107\t11.4201\t11.6561\t11.577\t11.376\t11.6476\t11.5522\t11.6431\t11.4429\t11.652\t11.5537\t11.3551\t11.3603\t11.1919\t11.2188\t11.0548\t11.7071\t11.4637\t11.0931\t11.2296\t11.3194\t11.5612\t11.2729\t11.8978\t11.3025\t11.6984\t11.3947\t11.3532\t11.6922\t11.4064\t11.0851\t11.6175\t11.4512\t11.5573\t11.046\t11.4998\t11.5194\t10.9714\t12.0396\t11.3986\t11.2249\t11.8768\t11.7767\t11.7419\t11.4742\t11.3269\t11.1655\t11.5237\t11.3819\t11.3502\t11.3811\t11.5698\t11.5556\t11.0031\t11.5815\t11.2501\t11.2291\t11.577\t11.6054\t11.6087\t7.03031\t7.28178\t7.3876\t7.25692\t10.2219\t7.19244\n", "Total lines examined: 68\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 20792 rows\n", "First 20 gene IDs:\n", "Index(['ILMN_1651209', 'ILMN_1651228', 'ILMN_1651229', 'ILMN_1651235',\n", " 'ILMN_1651236', 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651254',\n", " 'ILMN_1651262', 'ILMN_1651268', 'ILMN_1651278', 'ILMN_1651285',\n", " 'ILMN_1651292', 'ILMN_1651303', 'ILMN_1651315', 'ILMN_1651316',\n", " 'ILMN_1651336', 'ILMN_1651343', 'ILMN_1651346', 'ILMN_1651347'],\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", "# Add diagnostic code to check file content and structure\n", "print(\"Examining matrix file structure...\")\n", "with gzip.open(matrix_file, 'rt') as file:\n", " table_marker_found = False\n", " lines_read = 0\n", " for i, line in enumerate(file):\n", " lines_read += 1\n", " if '!series_matrix_table_begin' in line:\n", " table_marker_found = True\n", " print(f\"Found table marker at line {i}\")\n", " # Read a few lines after the marker to check data structure\n", " next_lines = [next(file, \"\").strip() for _ in range(5)]\n", " print(\"First few lines after marker:\")\n", " for next_line in next_lines:\n", " print(next_line)\n", " break\n", " if i < 10: # Print first few lines to see file structure\n", " print(f\"Line {i}: {line.strip()}\")\n", " if i > 100: # Don't read the entire file\n", " break\n", " \n", " if not table_marker_found:\n", " print(\"Table marker '!series_matrix_table_begin' not found in first 100 lines\")\n", " print(f\"Total lines examined: {lines_read}\")\n", "\n", "# 2. Try extracting gene expression data from the matrix file again with better diagnostics\n", "try:\n", " print(\"\\nAttempting to extract 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: {str(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", "\n", "# If data extraction failed, try an alternative approach using pandas directly\n", "if not is_gene_available:\n", " print(\"\\nTrying alternative approach to read gene expression data...\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Skip lines until we find the marker\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Try to read the data directly with pandas\n", " gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n", " \n", " if not gene_data.empty:\n", " print(f\"Successfully extracted gene data with alternative method: {gene_data.shape}\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", " else:\n", " print(\"Alternative extraction method also produced empty data\")\n", " except Exception as e:\n", " print(f\"Alternative extraction failed: {str(e)}\")\n" ] }, { "cell_type": "markdown", "id": "d09efb10", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "5d59506c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:38:46.408248Z", "iopub.status.busy": "2025-03-25T07:38:46.408129Z", "iopub.status.idle": "2025-03-25T07:38:46.410009Z", "shell.execute_reply": "2025-03-25T07:38:46.409737Z" } }, "outputs": [], "source": [ "# Based on the information provided, I need to determine if gene mapping is needed\n", "\n", "# The gene identifiers in the expression data are in the format ILMN_1651209, ILMN_1651228, etc.\n", "# These are Illumina probe IDs, not standard human gene symbols.\n", "# Illumina probe IDs need to be mapped to human gene symbols for more meaningful analysis.\n", "\n", "# Illumina IDs typically start with \"ILMN_\" followed by numbers, which is what we see here.\n", "# These are not directly interpretable as gene names and require mapping to standard gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "32a492c6", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "94b7ad66", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:38:46.411212Z", "iopub.status.busy": "2025-03-25T07:38:46.411104Z", "iopub.status.idle": "2025-03-25T07:38:50.024609Z", "shell.execute_reply": "2025-03-25T07:38:50.024212Z" } }, "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 1713610 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Transcript': ['ILMN_333737', 'ILMN_333646', 'ILMN_333584', 'ILMN_333628', 'ILMN_333719'], 'Species': ['ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls', 'ILMN Controls'], 'Source': ['ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls', 'ILMN_Controls'], 'Search_Key': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'ILMN_Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Source_Reference_ID': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995'], 'Symbol': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144'], 'Protein_Product': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5270161.0, 4260594.0, 7610424.0, 5260356.0, 2030196.0], 'Probe_Type': ['S', 'S', 'S', 'S', 'S'], 'Probe_Start': [12.0, 224.0, 868.0, 873.0, 130.0], 'SEQUENCE': ['CCCATGTGTCCAATTCTGAATATCTTTCCAGCTAAGTGCTTCTGCCCACC', 'GGATTAACTGCTGTGGTGTGTCATACTCGGCTACCTCCTGGTTTGGCGTC', 'GACCACGCCTTGTAATCGTATGACACGCGCTTGACACGACTGAATCCAGC', 'CTGCAATGCCATTAACAACCTTAGCACGGTATTTCCAGTAGCTGGTGAGC', 'CGTGCAGACAGGGATCGTAAGGCGATCCAGCCGGTATACCTTAGTCACAT'], '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': ['Methanocaldococcus jannaschii spike-in control MJ-500-33 genomic sequence', 'Synthetic construct clone NISTag13 external RNA control sequence', 'Synthetic construct clone TagJ microarray control', 'Methanocaldococcus jannaschii spike-in control MJ-1000-68 genomic sequence', 'Synthetic construct clone AG006.1100 external RNA control sequence'], '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': ['DQ516750', 'DQ883654', 'DQ668364', 'DQ516785', 'DQ854995']}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'Transcript', 'Species', 'Source', 'Search_Key', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', '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: 29377 out of 1713610\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": "7b45326c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "4043770a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:38:50.026056Z", "iopub.status.busy": "2025-03-25T07:38:50.025916Z", "iopub.status.idle": "2025-03-25T07:38:51.012930Z", "shell.execute_reply": "2025-03-25T07:38:51.012545Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Created gene mapping with 29377 rows\n", "Gene mapping preview:\n", "{'ID': ['ILMN_3166687', 'ILMN_3165566', 'ILMN_3164811', 'ILMN_3165363', 'ILMN_3166511'], 'Gene': ['ERCC-00162', 'ERCC-00071', 'ERCC-00009', 'ERCC-00053', 'ERCC-00144']}\n", "Converted gene expression data from 20210 genes\n", "First few gene symbols after mapping:\n", "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n", " 'A4GALT', 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AADAC', 'AADACL1',\n", " 'AADACL2', 'AADACL4', 'AADAT', 'AAGAB', 'AAK1'],\n", " dtype='object', name='Gene')\n", "Normalizing gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization, gene data contains 19449 unique genes\n", "First few normalized gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT',\n", " 'A4GNT', 'AAA1', 'AAAS', 'AACS', 'AADAC', 'AADACL2', 'AADACL4', 'AADAT',\n", " 'AAGAB', 'AAK1', 'AAMDC', 'AAMP', 'AANAT'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Lower_Grade_Glioma/gene_data/GSE35158.csv\n" ] } ], "source": [ "# 1. Decide which columns to use for mapping\n", "# From the gene annotation data, we need ID and Symbol columns\n", "# ID column in gene_annotation corresponds to ID index in gene_data\n", "# Symbol column contains gene symbols we want to map to\n", "\n", "# 2. Get gene mapping dataframe by extracting relevant columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "print(f\"Created gene mapping with {len(gene_mapping)} rows\")\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene-level expression\n", "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping)\n", "print(f\"Converted gene expression data from {len(gene_data.index)} genes\")\n", "print(\"First few gene symbols after mapping:\")\n", "print(gene_data.index[:20])\n", "\n", "# Normalize gene symbols to standard format\n", "print(\"Normalizing gene symbols...\")\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization, gene data contains {len(gene_data.index)} unique genes\")\n", "print(\"First few normalized gene symbols:\")\n", "print(gene_data.index[:20])\n", "\n", "# Save gene expression 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\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "ae07c720", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "deaf3435", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:38:51.014454Z", "iopub.status.busy": "2025-03-25T07:38:51.014327Z", "iopub.status.idle": "2025-03-25T07:39:02.132567Z", "shell.execute_reply": "2025-03-25T07:39:02.131902Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols using NCBI Gene database...\n", "After normalization: 19449 unique genes remain\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene expression data saved to ../../output/preprocess/Lower_Grade_Glioma/gene_data/GSE35158.csv\n", "\n", "Extracting clinical data directly from the matrix file...\n", "\n", "Processing clinical data...\n", "Extracted clinical data with shape: (1, 81)\n", "Clinical data saved to: ../../output/preprocess/Lower_Grade_Glioma/clinical_data/GSE35158.csv\n", "\n", "Linking clinical and genetic data...\n", "Found 81 common samples between clinical and genetic data\n", "Linked data shape: (81, 19450)\n", "\n", "Handling missing values in linked data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (80, 19450)\n", "\n", "Evaluating trait and demographic feature bias...\n", "For the feature 'Lower_Grade_Glioma', the least common label is '0.0' with 29 occurrences. This represents 36.25% of the dataset.\n", "The distribution of the feature 'Lower_Grade_Glioma' in this dataset is fine.\n", "\n", "\n", "Saving linked data to ../../output/preprocess/Lower_Grade_Glioma/GSE35158.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved successfully!\n" ] } ], "source": [ "# 1. Normalize gene symbols using NCBI Gene database\n", "print(\"\\nNormalizing gene symbols using NCBI Gene database...\")\n", "try:\n", " gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"After normalization: {len(gene_data_normalized)} unique genes remain\")\n", " gene_data_cleaned = gene_data_normalized\n", " \n", " # Save the normalized gene expression data\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " gene_data_cleaned.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene expression data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error during gene symbol normalization: {str(e)}\")\n", " print(\"Falling back to original gene data\")\n", " gene_data_cleaned = gene_data.copy()\n", "\n", "# 2. We need to recreate the clinical data from the original matrix file\n", "print(\"\\nExtracting clinical data directly from the matrix file...\")\n", "# Extract clinical data from the matrix file again\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", "# Process clinical data\n", "print(\"\\nProcessing clinical data...\")\n", "# Create clinical features dataframe \n", "if trait_row is not None:\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", " \n", " print(f\"Extracted clinical data with shape: {selected_clinical_df.shape}\")\n", " # Save clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n", " \n", " is_trait_available = True\n", "else:\n", " selected_clinical_df = pd.DataFrame()\n", " is_trait_available = False\n", " print(\"No trait data available in clinical information.\")\n", "\n", "# 3. Link clinical and genetic data\n", "if is_trait_available and is_gene_available:\n", " print(\"\\nLinking clinical and genetic data...\")\n", " try:\n", " # Ensure the sample IDs match between clinical and genetic data\n", " common_samples = list(set(selected_clinical_df.columns).intersection(set(gene_data_cleaned.columns)))\n", " \n", " if len(common_samples) == 0:\n", " print(\"Warning: No common samples between clinical and genetic data\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", " else:\n", " print(f\"Found {len(common_samples)} common samples between clinical and genetic data\")\n", " \n", " # Filter data to include only common samples\n", " clinical_subset = selected_clinical_df[common_samples]\n", " genetic_subset = gene_data_cleaned[common_samples]\n", " \n", " # Link the data\n", " linked_data = pd.concat([clinical_subset, genetic_subset], axis=0).T\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # 4. Handle missing values\n", " print(\"\\nHandling missing values in linked data...\")\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 5. Determine if trait and demographic features are severely biased\n", " print(\"\\nEvaluating trait and demographic feature bias...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " except Exception as e:\n", " print(f\"Error during data linking: {str(e)}\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "else:\n", " print(\"\\nCannot create linked data: missing clinical or gene data\")\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", "\n", "# 6. Final validation and saving\n", "note = \"This dataset contains gene expression data from astrocytoma cell lines with modified GFAP isoform expression. The trait represents different experimental conditions related to the GFAPδ/GFAPα ratio.\"\n", "\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 if len(linked_data) > 0 else True,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# Save the linked data if it's usable\n", "if is_usable and len(linked_data) > 0:\n", " print(f\"\\nSaving linked data to {out_data_file}\")\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved successfully!\")\n", "else:\n", " print(f\"\\nDataset not usable for {trait} association studies due to bias or quality issues.\")" ] } ], "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 }