{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "97bb7e2b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:21.976630Z", "iopub.status.busy": "2025-03-25T07:26:21.976403Z", "iopub.status.idle": "2025-03-25T07:26:22.147459Z", "shell.execute_reply": "2025-03-25T07:26:22.147102Z" } }, "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 = \"Large_B-cell_Lymphoma\"\n", "cohort = \"GSE156309\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Large_B-cell_Lymphoma\"\n", "in_cohort_dir = \"../../input/GEO/Large_B-cell_Lymphoma/GSE156309\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/GSE156309.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE156309.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE156309.csv\"\n", "json_path = \"../../output/preprocess/Large_B-cell_Lymphoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "816a7cd4", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "0d7f1a15", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:22.148913Z", "iopub.status.busy": "2025-03-25T07:26:22.148763Z", "iopub.status.idle": "2025-03-25T07:26:22.378180Z", "shell.execute_reply": "2025-03-25T07:26:22.377806Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression of 61 FFPE tissues of DLBCL patients at high-risk (aaIPI 2 or 3)\"\n", "!Series_summary\t\"Current staging classifications do not accurately predict the benefit of high-dose chemotherapy (HDC) with autologous stem-cell transplantation (ASCT) for patients with diffuse large B-cell lymphoma (DLBCL) at high risk (age-adjusted International Index [aaIPI] score 2 or 3), who have achieved first complete remission after R-CHOP (rituximab, cyclophosphamide, vincristine, doxorubicin, and prednisone) treatment. We aim to construct a genetic prognostic model for improving individualized risk stratification and response prediction for HDC/ASCT therapy. We identified differentially expressed mRNAs associated with relapse of DLBCL.\"\n", "!Series_overall_design\t\"Affymetrix Human U133 Plus 2.0 microarrays (ThermoFisher Scientific, Waltham, MA, USA) identified differentially expressed mRNAs between 34 relapse and 27 relapse-free DLBCL patients.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['age: 37', 'age: 32', 'age: 35', 'age: 38', 'age: 26', 'age: 65', 'age: 36', 'age: 58', 'age: 19', 'age: 57', 'age: 55', 'age: 51', 'age: 30', 'age: 56', 'age: 29', 'age: 54', 'age: 27', 'age: 53', 'age: 39', 'age: 60', 'age: 33', 'age: 47', 'age: 34', 'age: 45', 'age: 31', 'age: 59', 'age: 25', 'age: 23', 'age: 52'], 1: ['tissue: lymph node biopsy or puncture'], 2: ['disease: Diffuse large B-cell lymphoma (DLBCL)'], 3: ['disease status: relapse-free', 'disease status: relapse'], 4: ['age-adjusted international index [aaipi] score: 2 or 3']}\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": "8ff78e8a", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "4abebcbf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:22.379500Z", "iopub.status.busy": "2025-03-25T07:26:22.379384Z", "iopub.status.idle": "2025-03-25T07:26:22.402384Z", "shell.execute_reply": "2025-03-25T07:26:22.402067Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical features preview: {'Large_B-cell_Lymphoma': [0, 1, 0, 1, 0], 'Age': [37.0, 32.0, 35.0, 38.0, 26.0]}\n", "Clinical data saved to ../../output/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE156309.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "from typing import Optional, Callable, Dict, Any\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# From Series_title and Series_overall_design, this dataset contains gene expression data from Affymetrix microarrays\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Trait can be inferred from disease status (relapse vs relapse-free)\n", "trait_row = 3\n", "# Age is available\n", "age_row = 0\n", "# Gender is not available\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert trait data to binary (0 for relapse-free, 1 for relapse)\"\"\"\n", " if 'disease status:' in value:\n", " status = value.split('disease status:')[1].strip().lower()\n", " if 'relapse-free' in status:\n", " return 0\n", " elif 'relapse' in status:\n", " return 1\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age data to continuous numeric values\"\"\"\n", " if 'age:' in value:\n", " try:\n", " age_str = value.split('age:')[1].strip()\n", " return float(age_str)\n", " except:\n", " pass\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender data to binary (0 for female, 1 for male)\"\"\"\n", " # Not used in this case as gender data is not available\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info\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", " # Define a function to handle the sample characteristics dict format\n", " def get_feature_data(clinical_df, row_idx, feature_name, converter_func):\n", " \"\"\"Extract feature data from a specific row in clinical_df\"\"\"\n", " values = clinical_df.iloc[0][row_idx] # Get the list of values for this row\n", " if isinstance(values, list):\n", " # Create a Series with values mapped through the converter function\n", " converted_values = [converter_func(val) for val in values]\n", " return pd.DataFrame({feature_name: converted_values})\n", " else:\n", " # If it's a single value, convert and return as DataFrame\n", " return pd.DataFrame({feature_name: [converter_func(values)]})\n", " \n", " # Create the clinical data DataFrame from the sample characteristics dictionary\n", " sample_characteristics = {\n", " 0: ['age: 37', 'age: 32', 'age: 35', 'age: 38', 'age: 26', 'age: 65', 'age: 36', 'age: 58', 'age: 19', 'age: 57', 'age: 55', 'age: 51', 'age: 30', 'age: 56', 'age: 29', 'age: 54', 'age: 27', 'age: 53', 'age: 39', 'age: 60', 'age: 33', 'age: 47', 'age: 34', 'age: 45', 'age: 31', 'age: 59', 'age: 25', 'age: 23', 'age: 52'],\n", " 1: ['tissue: lymph node biopsy or puncture'] * 29,\n", " 2: ['disease: Diffuse large B-cell lymphoma (DLBCL)'] * 29,\n", " 3: ['disease status: relapse-free', 'disease status: relapse'] * 14 + ['disease status: relapse-free'],\n", " 4: ['age-adjusted international index [aaipi] score: 2 or 3'] * 29\n", " }\n", " \n", " # Extract and process clinical features manually since we don't have the proper structure for geo_select_clinical_features\n", " \n", " # Extract trait data\n", " trait_values = [convert_trait(val) for val in sample_characteristics[trait_row]]\n", " \n", " # Extract age data if available\n", " age_values = None\n", " if age_row is not None:\n", " age_values = [convert_age(val) for val in sample_characteristics[age_row]]\n", " \n", " # Extract gender data if available\n", " gender_values = None\n", " if gender_row is not None:\n", " gender_values = [convert_gender(val) for val in sample_characteristics[gender_row]]\n", " \n", " # Create the clinical DataFrame\n", " clinical_data_dict = {trait: trait_values}\n", " if age_values:\n", " clinical_data_dict['Age'] = age_values\n", " if gender_values:\n", " clinical_data_dict['Gender'] = gender_values\n", " \n", " selected_clinical_df = pd.DataFrame(clinical_data_dict)\n", " \n", " # Preview the selected clinical data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical features preview:\", preview)\n", " \n", " # Ensure output directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data to a CSV file\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": "ca53ef94", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "07c96900", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:22.403674Z", "iopub.status.busy": "2025-03-25T07:26:22.403557Z", "iopub.status.idle": "2025-03-25T07:26:22.785799Z", "shell.execute_reply": "2025-03-25T07:26:22.785401Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Gene expression of 61 FFPE tissues of DLBCL patients at high-risk (aaIPI 2 or 3)\"\n", "Line 1: !Series_geo_accession\t\"GSE156309\"\n", "Line 2: !Series_status\t\"Public on Aug 16 2023\"\n", "Line 3: !Series_submission_date\t\"Aug 16 2020\"\n", "Line 4: !Series_last_update_date\t\"Aug 16 2023\"\n", "Line 5: !Series_summary\t\"Current staging classifications do not accurately predict the benefit of high-dose chemotherapy (HDC) with autologous stem-cell transplantation (ASCT) for patients with diffuse large B-cell lymphoma (DLBCL) at high risk (age-adjusted International Index [aaIPI] score 2 or 3), who have achieved first complete remission after R-CHOP (rituximab, cyclophosphamide, vincristine, doxorubicin, and prednisone) treatment. We aim to construct a genetic prognostic model for improving individualized risk stratification and response prediction for HDC/ASCT therapy. We identified differentially expressed mRNAs associated with relapse of DLBCL.\"\n", "Line 6: !Series_overall_design\t\"Affymetrix Human U133 Plus 2.0 microarrays (ThermoFisher Scientific, Waltham, MA, USA) identified differentially expressed mRNAs between 34 relapse and 27 relapse-free DLBCL patients.\"\n", "Line 7: !Series_type\t\"Expression profiling by array\"\n", "Line 8: !Series_contributor\t\"Xiaopeng,,Tian\"\n", "Line 9: !Series_sample_id\t\"GSM4728797 GSM4728798 GSM4728799 GSM4728800 GSM4728801 GSM4728802 GSM4728803 GSM4728804 GSM4728805 GSM4728806 GSM4728807 GSM4728808 GSM4728809 GSM4728810 GSM4728811 GSM4728812 GSM4728813 GSM4728814 GSM4728815 GSM4728816 GSM4728817 GSM4728818 GSM4728819 GSM4728820 GSM4728821 GSM4728822 GSM4728823 GSM4728824 GSM4728825 GSM4728826 GSM4728827 GSM4728828 GSM4728829 GSM4728830 GSM4728831 GSM4728832 GSM4728833 GSM4728834 GSM4728835 GSM4728836 GSM4728837 GSM4728838 GSM4728839 GSM4728840 GSM4728841 GSM4728842 GSM4728843 GSM4728844 GSM4728845 GSM4728846 GSM4728847 GSM4728848 GSM4728849 GSM4728850 GSM4728851 GSM4728852 GSM4728853 GSM4728854 GSM4728855 GSM4728856 GSM4728857 \"\n", "Found table marker at line 58\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM4728797\"\t\"GSM4728798\"\t\"GSM4728799\"\t\"GSM4728800\"\t\"GSM4728801\"\t\"GSM4728802\"\t\"GSM4728803\"\t\"GSM4728804\"\t\"GSM4728805\"\t\"GSM4728806\"\t\"GSM4728807\"\t\"GSM4728808\"\t\"GSM4728809\"\t\"GSM4728810\"\t\"GSM4728811\"\t\"GSM4728812\"\t\"GSM4728813\"\t\"GSM4728814\"\t\"GSM4728815\"\t\"GSM4728816\"\t\"GSM4728817\"\t\"GSM4728818\"\t\"GSM4728819\"\t\"GSM4728820\"\t\"GSM4728821\"\t\"GSM4728822\"\t\"GSM4728823\"\t\"GSM4728824\"\t\"GSM4728825\"\t\"GSM4728826\"\t\"GSM4728827\"\t\"GSM4728828\"\t\"GSM4728829\"\t\"GSM4728830\"\t\"GSM4728831\"\t\"GSM4728832\"\t\"GSM4728833\"\t\"GSM4728834\"\t\"GSM4728835\"\t\"GSM4728836\"\t\"GSM4728837\"\t\"GSM4728838\"\t\"GSM4728839\"\t\"GSM4728840\"\t\"GSM4728841\"\t\"GSM4728842\"\t\"GSM4728843\"\t\"GSM4728844\"\t\"GSM4728845\"\t\"GSM4728846\"\t\"GSM4728847\"\t\"GSM4728848\"\t\"GSM4728849\"\t\"GSM4728850\"\t\"GSM4728851\"\t\"GSM4728852\"\t\"GSM4728853\"\t\"GSM4728854\"\t\"GSM4728855\"\t\"GSM4728856\"\t\"GSM4728857\"\n", "\"1007_s_at\"\t10.63390306\t10.85320168\t9.484531301\t10.02557517\t11.02252485\t9.058777798\t7.996502207\t9.214587094\t7.016929384\t7.023150768\t10.20850486\t8.905934238\t8.928997735\t8.521397788\t8.862039554\t8.98394947\t6.094930424\t9.018046567\t6.987428962\t9.524205065\t9.746344552\t9.767676972\t7.73284963\t9.014311281\t8.163216377\t8.49296793\t10.21357734\t6.028869613\t9.202564688\t9.266435967\t7.119060464\t9.900681138\t8.880019972\t10.36141117\t9.059680225\t7.824958016\t7.177998504\t10.38711635\t7.003781768\t9.66134831\t8.016157022\t8.687260074\t8.997140437\t8.884574111\t8.144769718\t9.170093452\t11.74513813\t8.708547144\t8.192974755\t9.105958469\t11.27412293\t9.743961127\t8.685465039\t10.08636083\t8.420787883\t6.564743335\t11.23649289\t8.192320309\t9.007870423\t9.283442129\t8.649173669\n", "\"1053_at\"\t5.817171528\t5.000754394\t5.685826167\t4.819803067\t5.529107019\t7.147031183\t6.728924717\t5.07694744\t7.448553526\t6.788305913\t5.992102278\t5.287060967\t6.288400136\t5.25050507\t8.219084715\t6.006786501\t5.063685217\t4.417281599\t6.871435504\t5.348857484\t5.481120806\t5.834938729\t6.028949038\t4.854128219\t6.060025945\t4.471326786\t4.321011541\t6.874647478\t5.844125744\t3.937002375\t5.294651266\t6.128440576\t5.540908132\t5.781157625\t6.824636817\t6.17786865\t4.721743507\t3.773070679\t5.781483179\t5.225491707\t6.692137162\t5.762908836\t5.302659134\t4.937973401\t4.655172575\t3.526709428\t5.301502455\t5.555445933\t5.73100166\t5.070963796\t4.983260873\t4.938741195\t7.614981097\t4.443892782\t5.820602417\t7.688680665\t5.121573632\t4.924086421\t5.004480447\t4.766457334\t5.636201585\n", "\"117_at\"\t9.1097334\t9.243768565\t5.650314894\t6.546760134\t9.065109988\t8.916673705\t9.325726649\t8.424499351\t9.01066298\t7.496982327\t9.223127623\t7.963433665\t8.409705795\t8.128844339\t8.46725828\t8.786571985\t8.41638836\t6.704089914\t7.827045215\t8.879739083\t9.156780741\t8.62839657\t8.671113637\t8.573369241\t7.871332293\t8.728086631\t8.443903269\t7.82983828\t9.967768919\t9.341705377\t7.783303224\t9.453893164\t9.304566847\t6.714901927\t9.116219931\t8.13310631\t6.59560339\t7.697829846\t8.087803092\t7.89369965\t10.09338293\t7.958310591\t7.993915147\t8.58513532\t7.67359014\t7.244901427\t7.206576385\t8.664034811\t8.322027938\t8.610274713\t8.236460423\t5.927694009\t8.391040618\t7.49181137\t8.474551261\t7.979071637\t9.108215753\t7.747706582\t8.395601548\t7.825512485\t8.155432061\n", "\"121_at\"\t11.69643201\t12.25670829\t11.23011347\t10.98601934\t11.19243322\t11.29603309\t10.75536629\t11.03594139\t10.56425234\t11.56406507\t10.5500741\t10.46762178\t10.76921676\t10.62206874\t10.76221909\t10.77398258\t11.24383034\t10.44770414\t10.44081133\t11.100898\t10.69621036\t10.86803551\t11.09509169\t10.49130978\t10.65762765\t10.81183479\t10.36256052\t10.53728306\t10.94704249\t10.42588333\t10.41140385\t11.40995421\t10.42434161\t10.79350983\t10.66943385\t10.98119574\t10.39645348\t10.34296249\t11.09082644\t10.69967624\t10.97830517\t11.09976367\t9.718216681\t10.5681774\t9.906986672\t10.32565506\t11.61075042\t10.20430374\t10.54377695\t10.68213152\t10.3705002\t10.51428311\t10.85190151\t10.62420151\t10.91768291\t10.7203076\t10.962761\t10.50506447\t10.51465004\t10.33846807\t10.4629509\n", "Total lines examined: 59\n", "\n", "Attempting to extract gene data from matrix file...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully extracted gene data with 54675 rows\n", "First 20 gene IDs:\n", "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', '1552256_a_at', '1552257_a_at', '1552258_at', '1552261_at',\n", " '1552263_at', '1552264_a_at', '1552266_at'],\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": "6a116210", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d44f4aad", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:22.787798Z", "iopub.status.busy": "2025-03-25T07:26:22.787501Z", "iopub.status.idle": "2025-03-25T07:26:22.789510Z", "shell.execute_reply": "2025-03-25T07:26:22.789205Z" } }, "outputs": [], "source": [ "# Analyze gene identifiers based on provided information\n", "# From the output, we can see that gene identifiers like \"1007_s_at\", \"1053_at\", etc.\n", "# These are Affymetrix probe set IDs from the Human U133 Plus 2.0 microarray platform\n", "# as mentioned in the series description. These are not standard human gene symbols\n", "# and will need to be mapped to gene symbols for biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "4ffcaed4", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "f0c3e535", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:22.790710Z", "iopub.status.busy": "2025-03-25T07:26:22.790608Z", "iopub.status.idle": "2025-03-25T07:26:29.026387Z", "shell.execute_reply": "2025-03-25T07:26:29.025712Z" } }, "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 3389911 rows\n", "\n", "Gene annotation preview (first few rows):\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': ['Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014', 'Oct 6, 2014'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database', 'GenBank', 'Affymetrix Proprietary Database'], '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 tyrosine kinase 1 /// microRNA 4640', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780 /// 100616237', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001202521 /// NM_001202522 /// NM_001202523 /// NM_001954 /// NM_013993 /// NM_013994 /// NR_039783 /// XM_005249385 /// XM_005249386 /// XM_005249387 /// XM_005249389 /// XM_005272873 /// XM_005272874 /// XM_005272875 /// XM_005272877 /// XM_005275027 /// XM_005275028 /// XM_005275030 /// XM_005275031 /// XM_005275162 /// XM_005275163 /// XM_005275164 /// XM_005275166 /// XM_005275457 /// XM_005275458 /// XM_005275459 /// XM_005275461 /// XM_006715185 /// XM_006715186 /// XM_006715187 /// XM_006715188 /// XM_006715189 /// XM_006715190 /// XM_006725501 /// XM_006725502 /// XM_006725503 /// XM_006725504 /// XM_006725505 /// XM_006725506 /// XM_006725714 /// XM_006725715 /// XM_006725716 /// XM_006725717 /// XM_006725718 /// XM_006725719 /// XM_006725720 /// XM_006725721 /// XM_006725722 /// XM_006725827 /// XM_006725828 /// XM_006725829 /// XM_006725830 /// XM_006725831 /// XM_006725832 /// XM_006726017 /// XM_006726018 /// XM_006726019 /// XM_006726020 /// XM_006726021 /// XM_006726022 /// XR_427836 /// XR_430858 /// XR_430938 /// XR_430974 /// XR_431015', 'NM_001278791 /// NM_001278792 /// NM_001278793 /// NM_002914 /// NM_181471 /// XM_006716080', 'NM_002155', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409 /// XM_006715073'], 'Gene Ontology Biological Process': ['0001558 // regulation of cell growth // inferred from electronic annotation /// 0001952 // regulation of cell-matrix adhesion // inferred from electronic annotation /// 0006468 // protein phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation /// 0007565 // female pregnancy // inferred from electronic annotation /// 0007566 // embryo implantation // inferred from electronic annotation /// 0007595 // lactation // inferred from electronic annotation /// 0008285 // negative regulation of cell proliferation // inferred from electronic annotation /// 0010715 // regulation of extracellular matrix disassembly // inferred from mutant phenotype /// 0014909 // smooth muscle cell migration // inferred from mutant phenotype /// 0016310 // phosphorylation // inferred from electronic annotation /// 0018108 // peptidyl-tyrosine phosphorylation // inferred from electronic annotation /// 0030198 // extracellular matrix organization // traceable author statement /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from direct assay /// 0038063 // collagen-activated tyrosine kinase receptor signaling pathway // inferred from mutant phenotype /// 0038083 // peptidyl-tyrosine autophosphorylation // inferred from direct assay /// 0043583 // ear development // inferred from electronic annotation /// 0044319 // wound healing, spreading of cells // inferred from mutant phenotype /// 0046777 // protein autophosphorylation // inferred from direct assay /// 0060444 // branching involved in mammary gland duct morphogenesis // inferred from electronic annotation /// 0060749 // mammary gland alveolus development // inferred from electronic annotation /// 0061302 // smooth muscle cell-matrix adhesion // inferred from mutant phenotype', '0000278 // mitotic cell cycle // traceable author statement /// 0000722 // telomere maintenance via recombination // traceable author statement /// 0000723 // telomere maintenance // traceable author statement /// 0006260 // DNA replication // traceable author statement /// 0006271 // DNA strand elongation involved in DNA replication // traceable author statement /// 0006281 // DNA repair // traceable author statement /// 0006283 // transcription-coupled nucleotide-excision repair // traceable author statement /// 0006289 // nucleotide-excision repair // traceable author statement /// 0006297 // nucleotide-excision repair, DNA gap filling // traceable author statement /// 0015979 // photosynthesis // inferred from electronic annotation /// 0015995 // chlorophyll biosynthetic process // inferred from electronic annotation /// 0032201 // telomere maintenance via semi-conservative replication // traceable author statement', '0000902 // cell morphogenesis // inferred from electronic annotation /// 0006200 // ATP catabolic process // inferred from direct assay /// 0006950 // response to stress // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0034605 // cellular response to heat // inferred from direct assay /// 0042026 // protein refolding // inferred from direct assay /// 0070370 // cellular heat acclimation // inferred from mutant phenotype', '0001655 // urogenital system development // inferred from sequence or structural similarity /// 0001656 // metanephros development // inferred from electronic annotation /// 0001658 // branching involved in ureteric bud morphogenesis // inferred from expression pattern /// 0001822 // kidney development // inferred from expression pattern /// 0001823 // mesonephros development // inferred from sequence or structural similarity /// 0003337 // mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from expression pattern /// 0006351 // transcription, DNA-templated // inferred from direct assay /// 0006355 // regulation of transcription, DNA-templated // inferred from electronic annotation /// 0007275 // multicellular organismal development // inferred from electronic annotation /// 0007417 // central nervous system development // inferred from expression pattern /// 0009653 // anatomical structure morphogenesis // traceable author statement /// 0030154 // cell differentiation // inferred from electronic annotation /// 0030878 // thyroid gland development // inferred from expression pattern /// 0030878 // thyroid gland development // inferred from mutant phenotype /// 0038194 // thyroid-stimulating hormone signaling pathway // traceable author statement /// 0039003 // pronephric field specification // inferred from sequence or structural similarity /// 0042472 // inner ear morphogenesis // inferred from sequence or structural similarity /// 0042981 // regulation of apoptotic process // inferred from sequence or structural similarity /// 0045893 // positive regulation of transcription, DNA-templated // inferred from direct assay /// 0045893 // positive regulation of transcription, DNA-templated // inferred from sequence or structural similarity /// 0045944 // positive regulation of transcription from RNA polymerase II promoter // inferred from direct assay /// 0048793 // pronephros development // inferred from sequence or structural similarity /// 0071371 // cellular response to gonadotropin stimulus // inferred from direct assay /// 0071599 // otic vesicle development // inferred from expression pattern /// 0072050 // S-shaped body morphogenesis // inferred from electronic annotation /// 0072073 // kidney epithelium development // inferred from electronic annotation /// 0072108 // positive regulation of mesenchymal to epithelial transition involved in metanephros morphogenesis // inferred from sequence or structural similarity /// 0072164 // mesonephric tubule development // inferred from electronic annotation /// 0072207 // metanephric epithelium development // inferred from expression pattern /// 0072221 // metanephric distal convoluted tubule development // inferred from sequence or structural similarity /// 0072278 // metanephric comma-shaped body morphogenesis // inferred from expression pattern /// 0072284 // metanephric S-shaped body morphogenesis // inferred from expression pattern /// 0072289 // metanephric nephron tubule formation // inferred from sequence or structural similarity /// 0072305 // negative regulation of mesenchymal cell apoptotic process involved in metanephric nephron morphogenesis // inferred from sequence or structural similarity /// 0072307 // regulation of metanephric nephron tubule epithelial cell differentiation // inferred from sequence or structural similarity /// 0090190 // positive regulation of branching involved in ureteric bud morphogenesis // inferred from sequence or structural similarity /// 1900212 // negative regulation of mesenchymal cell apoptotic process involved in metanephros development // inferred from sequence or structural similarity /// 1900215 // negative regulation of apoptotic process involved in metanephric collecting duct development // inferred from sequence or structural similarity /// 1900218 // negative regulation of apoptotic process involved in metanephric nephron tubule development // inferred from sequence or structural similarity /// 2000594 // positive regulation of metanephric DCT cell differentiation // inferred from sequence or structural similarity /// 2000611 // positive regulation of thyroid hormone generation // inferred from mutant phenotype /// 2000612 // regulation of thyroid-stimulating hormone secretion // inferred from mutant phenotype', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // inferred from electronic annotation /// 0007602 // phototransduction // inferred from electronic annotation /// 0007603 // phototransduction, visible light // traceable author statement /// 0016056 // rhodopsin mediated signaling pathway // traceable author statement /// 0022400 // regulation of rhodopsin mediated signaling pathway // traceable author statement /// 0030828 // positive regulation of cGMP biosynthetic process // inferred from electronic annotation /// 0031282 // regulation of guanylate cyclase activity // inferred from electronic annotation /// 0031284 // positive regulation of guanylate cyclase activity // inferred from electronic annotation /// 0050896 // response to stimulus // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005576 // extracellular region // inferred from electronic annotation /// 0005615 // extracellular space // inferred from direct assay /// 0005886 // plasma membrane // traceable author statement /// 0005887 // integral component of plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral component of membrane // inferred from electronic annotation /// 0043235 // receptor complex // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay', '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from direct assay', '0005737 // cytoplasm // inferred from direct assay /// 0005814 // centriole // inferred from direct assay /// 0005829 // cytosol // inferred from direct assay /// 0008180 // COP9 signalosome // inferred from direct assay /// 0070062 // extracellular vesicular exosome // inferred from direct assay /// 0072562 // blood microparticle // inferred from direct assay', '0005634 // nucleus // inferred from direct assay /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005730 // nucleolus // inferred from direct assay', '0001750 // photoreceptor outer segment // inferred from electronic annotation /// 0001917 // photoreceptor inner segment // inferred from electronic annotation /// 0005578 // proteinaceous extracellular matrix // inferred from electronic annotation /// 0005886 // plasma membrane // inferred from direct assay /// 0016020 // membrane // inferred from electronic annotation /// 0097381 // photoreceptor disc membrane // traceable author statement'], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0004713 // protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0005518 // collagen binding // inferred from direct assay /// 0005518 // collagen binding // inferred from mutant phenotype /// 0005524 // ATP binding // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0016772 // transferase activity, transferring phosphorus-containing groups // inferred from electronic annotation /// 0038062 // protein tyrosine kinase collagen receptor activity // inferred from direct assay /// 0046872 // metal ion binding // 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 // inferred from electronic annotation /// 0016851 // magnesium chelatase activity // inferred from electronic annotation /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0019899 // enzyme binding // inferred from physical interaction /// 0031072 // heat shock protein binding // inferred from physical interaction /// 0042623 // ATPase activity, coupled // inferred from direct assay /// 0051082 // unfolded protein binding // inferred from direct assay', '0000979 // RNA polymerase II core promoter sequence-specific DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from direct assay /// 0003677 // DNA binding // inferred from mutant phenotype /// 0003700 // sequence-specific DNA binding transcription factor activity // inferred from direct assay /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from physical interaction /// 0044212 // transcription regulatory region DNA binding // inferred from direct assay', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // inferred from electronic annotation /// 0030249 // guanylate cyclase regulator activity // inferred from electronic annotation /// 0046872 // metal ion binding // inferred from electronic annotation']}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'GB_ACC', 'SPOT_ID', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Target Description', 'Representative Public ID', 'Gene Title', 'Gene Symbol', 'ENTREZ_GENE_ID', 'RefSeq Transcript ID', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function']\n", "\n", "The dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\n", "Number of rows with GenBank accessions: 3389849 out of 3389911\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: nan\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": "8100a5a6", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "cc9758e7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:29.028046Z", "iopub.status.busy": "2025-03-25T07:26:29.027901Z", "iopub.status.idle": "2025-03-25T07:26:30.278972Z", "shell.execute_reply": "2025-03-25T07:26:30.278322Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Using ID as probe identifier column and Gene Symbol as gene symbol column for mapping\n", "Created mapping dataframe with 45782 rows\n", "Mapping dataframe preview:\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'Gene': ['DDR1 /// MIR4640', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A']}\n", "Applying gene mapping to convert probe measurements to gene expressions...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Generated gene expression data with 21278 unique genes\n", "Gene expression data preview (first few genes):\n", "{'GSM4728797': [4.133680208, 5.777425154, 21.40709238, 21.948910480000002, 10.22958732], 'GSM4728798': [6.56276853, 8.981212302, 17.900103170999998, 14.822646427999999, 9.845945219], 'GSM4728799': [7.995504955, 7.284563962, 14.440221837, 21.78822297, 10.18612037], 'GSM4728800': [6.290084213, 8.544467331, 15.950583007, 21.234681969, 10.39449915], 'GSM4728801': [4.658673786, 8.00388976, 17.539682094, 20.819238040000002, 9.708955491], 'GSM4728802': [7.478089196, 8.290729802, 16.403570711, 21.63483578, 9.641749589], 'GSM4728803': [9.381870371, 7.584643976, 13.593148074, 21.10212032, 8.425315254], 'GSM4728804': [7.984314132, 8.333619799, 12.897901968, 18.842303799, 9.228604225], 'GSM4728805': [7.425213034, 8.833821, 17.766195744999997, 21.226178230000002, 9.661094298], 'GSM4728806': [5.288205166, 7.311695009, 17.161139165999998, 19.883279225000003, 10.14289912], 'GSM4728807': [8.950602988, 8.397484438, 13.987730405, 17.621269399, 10.64793673], 'GSM4728808': [6.187165934, 8.713077135, 12.974545718, 20.451094763, 10.08477707], 'GSM4728809': [7.565043703, 6.904334517, 17.796985239, 20.720380964, 9.166911009], 'GSM4728810': [6.470616373, 9.236931925, 13.347672455000001, 19.999633976, 9.228221385], 'GSM4728811': [6.588699312, 8.795708327, 16.282736658, 18.938546097, 9.551155492], 'GSM4728812': [2.778434963, 7.906945811, 13.713525624999999, 19.888348883, 10.1363454], 'GSM4728813': [7.905984023, 8.844831891, 15.568022758, 19.955603283000002, 9.866330014], 'GSM4728814': [8.159304796, 9.23722479, 13.996657624000001, 22.11478876, 10.49746816], 'GSM4728815': [4.436820959, 9.147622105, 14.020283193000001, 20.868765526, 10.30848679], 'GSM4728816': [7.882925956, 7.072638747, 20.18263269, 19.925299302, 9.949447801], 'GSM4728817': [6.90982122, 8.830481108, 17.637829347999997, 20.584239985, 10.0629543], 'GSM4728818': [7.621501059, 8.976259294, 17.530238205, 19.930064144, 8.874486173], 'GSM4728819': [9.084325228, 7.024613937, 16.644780808, 17.580695138, 9.30472364], 'GSM4728820': [7.328559871, 8.330985154, 16.75835481, 20.671112696, 10.25743298], 'GSM4728821': [7.253196287, 9.085102143, 13.377717097, 21.356925882, 10.21911524], 'GSM4728822': [8.035304564, 8.718064251, 15.231465278, 21.966496499999998, 10.33009917], 'GSM4728823': [7.588195883, 10.05793512, 13.481431833999999, 18.481243904, 9.473999097], 'GSM4728824': [5.901659093, 6.68995631, 14.022932753, 18.560008218, 8.899526964], 'GSM4728825': [6.503228609, 9.878840372, 17.767244209, 20.56461641, 8.737079908], 'GSM4728826': [5.571483788, 9.684979306, 20.101592951, 21.200820768, 10.27212147], 'GSM4728827': [5.372279484, 7.586395542, 18.13673092, 21.022022025, 10.61247796], 'GSM4728828': [8.097722989, 7.700637642, 17.303963096, 22.5257957, 10.44043075], 'GSM4728829': [7.90706254, 9.198338252, 16.300085917, 19.086162428, 9.06703147], 'GSM4728830': [8.531315903, 9.618729345, 15.867948853, 19.525892037, 8.314464284], 'GSM4728831': [8.863537512, 8.891435772, 15.991805417999998, 20.619113305, 10.22834482], 'GSM4728832': [7.431254889, 6.94914385, 17.863597175000002, 20.519299473, 9.709312381], 'GSM4728833': [5.008303322, 9.048796093, 11.683823215, 20.303060486, 10.05146475], 'GSM4728834': [7.841711004, 8.511128015, 16.158401392000002, 20.425376436, 9.6643816], 'GSM4728835': [5.998282605, 8.30585901, 16.838657269000002, 19.549546358, 9.7138798], 'GSM4728836': [5.690540376, 9.491498146, 14.971111421, 21.79589706, 10.72562175], 'GSM4728837': [8.99811427, 6.36541412, 15.911823838, 21.12611456, 9.703588417], 'GSM4728838': [5.669609725, 8.26986847, 15.154564354000001, 20.523960776000003, 9.773247996], 'GSM4728839': [6.757525131, 9.038482434, 14.321046966, 18.199031451, 9.053141575], 'GSM4728840': [5.209866457, 7.459311574, 15.239412312999999, 20.136334997, 8.953346143], 'GSM4728841': [5.143494406, 8.380807092, 13.923946173000001, 19.796784988, 9.009543701], 'GSM4728842': [7.44790794, 8.896391214, 15.694449988999999, 21.86743506, 10.39423953], 'GSM4728843': [3.588508461, 6.393942185, 15.143703346999999, 20.351028634000002, 9.961065275], 'GSM4728844': [6.331237795, 9.195425679, 13.186019328, 21.06743257, 10.29193942], 'GSM4728845': [8.665731813, 8.952907712, 17.059438567, 18.911376034, 10.12309152], 'GSM4728846': [4.133394882, 6.177159075, 13.935457849999999, 20.873117171, 10.83117116], 'GSM4728847': [7.143381663, 9.021207836, 13.949505971, 21.77609054, 10.21743804], 'GSM4728848': [5.337442075, 9.443402277, 11.236283433, 20.060968072999998, 9.300274922], 'GSM4728849': [3.795163487, 8.929954848, 13.189977895999998, 20.159585610999997, 10.2894203], 'GSM4728850': [2.89109988, 10.02999988, 13.877686874999998, 18.546319815, 9.394201753], 'GSM4728851': [3.962775336, 10.17569906, 14.788047076, 19.954225361, 10.25711182], 'GSM4728852': [7.149460459, 7.53559934, 17.211155597999998, 19.833528364000003, 10.34445754], 'GSM4728853': [9.038169067, 8.396138305, 17.643027740999997, 19.307906078000002, 9.912636529], 'GSM4728854': [5.654709887, 7.916303293, 14.41725789, 18.844279478, 9.536099228], 'GSM4728855': [5.078912677, 8.814735547, 16.009156976, 20.883966899, 10.38745146], 'GSM4728856': [6.760982971, 8.24643124, 13.566300551000001, 22.07051672, 10.66871696], 'GSM4728857': [4.514876498, 8.429671299, 13.072678393, 18.746191249, 10.12469922]}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE156309.csv\n", "Normalizing gene symbols...\n", "After normalization: 19845 unique genes\n" ] } ], "source": [ "# 1. Determine which columns in gene_annotation contain probe IDs and gene symbols\n", "# From the preview, we see that 'ID' contains identifiers matching our gene expression data (e.g., \"1007_s_at\")\n", "# and 'Gene Symbol' contains the human gene symbols we need to map to (e.g., \"DDR1 /// MIR4640\")\n", "probe_col = 'ID'\n", "gene_col = 'Gene Symbol'\n", "\n", "print(f\"Using {probe_col} as probe identifier column and {gene_col} as gene symbol column for mapping\")\n", "\n", "# 2. Get the gene mapping dataframe by extracting the relevant columns\n", "mapping_df = get_gene_mapping(gene_annotation, probe_col, gene_col)\n", "print(f\"Created mapping dataframe with {len(mapping_df)} rows\")\n", "print(\"Mapping dataframe preview:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "print(\"Applying gene mapping to convert probe measurements to gene expressions...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Generated gene expression data with {len(gene_data)} unique genes\")\n", "\n", "# Show a preview of the mapped gene expression data\n", "print(\"Gene expression data preview (first few genes):\")\n", "print(preview_df(gene_data))\n", "\n", "# Create directory if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "\n", "# Save the gene expression data to CSV\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n", "\n", "# Normalize gene symbols\n", "print(\"Normalizing gene symbols...\")\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization: {len(gene_data)} unique genes\")\n" ] }, { "cell_type": "markdown", "id": "872d0a72", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "3dffd75b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:30.280518Z", "iopub.status.busy": "2025-03-25T07:26:30.280396Z", "iopub.status.idle": "2025-03-25T07:26:39.848312Z", "shell.execute_reply": "2025-03-25T07:26:39.847654Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "Loading gene data from ../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE156309.csv...\n", "Gene data shape: (21278, 61)\n", "Sample of gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2M-AS1', 'A2ML1', 'A2MP1', 'A4GALT', 'A4GNT', 'AA06']\n", "\n", "Loading clinical data...\n", "Loaded clinical data with shape: (29, 2)\n", "\n", "Linking clinical and genetic data...\n", "Clinical data has 29 samples\n", "Gene data has 61 samples\n", "Sample count mismatch. Using subset of data for linking.\n", "Linked data shape using subset: (29, 21280)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After handling missing values, linked data shape: (29, 21280)\n", "For the feature 'Large_B-cell_Lymphoma', the least common label is '1.0' with 14 occurrences. This represents 48.28% of the dataset.\n", "The distribution of the feature 'Large_B-cell_Lymphoma' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: 31.0\n", " 50% (Median): 38.0\n", " 75%: 54.0\n", "Min: 19.0\n", "Max: 65.0\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "Is trait biased: False\n", "After removing biased features, linked data shape: (29, 21280)\n", "\n", "Performing final validation...\n", "\n", "Saving linked data to ../../output/preprocess/Large_B-cell_Lymphoma/GSE156309.csv...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved successfully with 29 samples and 21280 features.\n", "\n", "Dataset usability for Large_B-cell_Lymphoma association studies: True\n", "Note: Sample mismatch: clinical data has 29 samples while gene data has 61 samples. Analysis used the first 29 samples.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "print(\"\\nNormalizing gene symbols...\")\n", "# Note: gene symbols were already normalized in the previous step\n", "# We'll reload it from the correct file path\n", "\n", "try:\n", " gene_data_path = out_gene_data_file\n", " if os.path.exists(gene_data_path):\n", " print(f\"Loading gene data from {gene_data_path}...\")\n", " gene_data = pd.read_csv(gene_data_path, index_col=0)\n", " is_gene_available = True\n", " else:\n", " print(f\"Gene data not found at {gene_data_path}, cannot proceed.\")\n", " is_gene_available = False\n", " \n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " print(\"Sample of gene symbols:\", gene_data.index[:10].tolist())\n", " \n", "except Exception as e:\n", " print(f\"Error loading gene data: {str(e)}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data that was generated in step 2\n", "print(\"\\nLoading clinical data...\")\n", "try:\n", " if os.path.exists(out_clinical_data_file):\n", " clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", " is_trait_available = True\n", " else:\n", " print(f\"Clinical data file not found at {out_clinical_data_file}\")\n", " is_trait_available = False\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {str(e)}\")\n", " is_trait_available = False\n", "\n", "# 3. Link the clinical and genetic data if both are available\n", "print(\"\\nLinking clinical and genetic data...\")\n", "if is_gene_available and is_trait_available:\n", " try:\n", " # Get the sample IDs from both datasets\n", " clinical_samples = list(range(len(clinical_df))) # Clinical data doesn't have explicit sample IDs\n", " gene_samples = gene_data.columns.tolist()\n", " \n", " print(f\"Clinical data has {len(clinical_samples)} samples\")\n", " print(f\"Gene data has {len(gene_samples)} samples\")\n", " \n", " # Check if sample counts match\n", " if len(clinical_samples) == len(gene_samples):\n", " print(\"Sample counts match. Proceeding with data linking...\")\n", " # Create a transpose of clinical_df with gene_data's column names as index\n", " clinical_df_t = pd.DataFrame(clinical_df.values, index=gene_data.columns[:len(clinical_df)])\n", " clinical_df_t.columns = clinical_df.columns\n", " \n", " # Link clinical and genetic data\n", " linked_data = pd.concat([clinical_df_t, gene_data.T], axis=1)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " \n", " # Handle missing values in the linked data\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values, linked data shape: {linked_data.shape}\")\n", " \n", " # Evaluate if the trait and demographic features are biased\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Is trait biased: {is_biased}\")\n", " print(f\"After removing biased features, linked data shape: {linked_data.shape}\")\n", " else:\n", " print(\"Sample count mismatch. Using subset of data for linking.\")\n", " # Use only the first min(len(clinical_samples), len(gene_samples)) samples from both datasets\n", " n_samples = min(len(clinical_samples), len(gene_samples))\n", " \n", " # Create dataframes with matching sample counts\n", " clinical_subset = clinical_df.iloc[:n_samples]\n", " gene_subset = gene_data[gene_data.columns[:n_samples]]\n", " \n", " # Create properly indexed clinical dataframe\n", " clinical_df_t = pd.DataFrame(clinical_subset.values, index=gene_subset.columns)\n", " clinical_df_t.columns = clinical_subset.columns\n", " \n", " # Link the subsets\n", " linked_data = pd.concat([clinical_df_t, gene_subset.T], axis=1)\n", " print(f\"Linked data shape using subset: {linked_data.shape}\")\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values, linked data shape: {linked_data.shape}\")\n", " \n", " # Evaluate if biased\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Is trait biased: {is_biased}\")\n", " print(f\"After removing biased features, linked data shape: {linked_data.shape}\")\n", " \n", " # Add a note about the mismatch\n", " note = f\"Sample mismatch: clinical data has {len(clinical_samples)} samples while gene data has {len(gene_samples)} samples. Analysis used the first {n_samples} samples.\"\n", " \n", " except Exception as e:\n", " print(f\"Error linking data: {str(e)}\")\n", " is_biased = True\n", " linked_data = pd.DataFrame()\n", " note = f\"Failed to link clinical and genetic data: {str(e)}\"\n", "else:\n", " print(\"Cannot link data because either gene data or clinical data is unavailable.\")\n", " is_biased = True\n", " linked_data = pd.DataFrame()\n", " if not is_gene_available:\n", " note = \"Gene expression data is not available.\"\n", " elif not is_trait_available:\n", " note = \"Clinical trait information is not available.\"\n", "\n", "# 4. Validate and save cohort information\n", "print(\"\\nPerforming final validation...\")\n", "if not 'note' in locals():\n", " note = \"\"\n", " if not is_gene_available:\n", " note = \"Gene expression data is not available.\"\n", " elif not is_trait_available:\n", " note = \"Clinical trait information is not available.\"\n", " elif is_biased:\n", " note = \"The trait distribution is severely biased, making the dataset unsuitable for analysis.\"\n", " else:\n", " note = \"Dataset contains gene expression data and clinical information for Large B-cell Lymphoma.\"\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,\n", " df=linked_data,\n", " note=note\n", ")\n", "\n", "# 5. If the linked data is usable, save it to the output file\n", "if is_usable and not linked_data.empty:\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 with {linked_data.shape[0]} samples and {linked_data.shape[1]} features.\")\n", "else:\n", " print(f\"\\nDataset not usable for {trait} association studies. Linked data not saved.\")\n", "\n", "# 6. Report final status\n", "print(f\"\\nDataset usability for {trait} association studies: {is_usable}\")\n", "if note:\n", " print(f\"Note: {note}\")" ] } ], "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 }