{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "6941cb27", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:02.511523Z", "iopub.status.busy": "2025-03-25T07:36:02.511417Z", "iopub.status.idle": "2025-03-25T07:36:02.673181Z", "shell.execute_reply": "2025-03-25T07:36:02.672833Z" } }, "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 = \"Longevity\"\n", "cohort = \"GSE48264\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Longevity\"\n", "in_cohort_dir = \"../../input/GEO/Longevity/GSE48264\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Longevity/GSE48264.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Longevity/gene_data/GSE48264.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Longevity/clinical_data/GSE48264.csv\"\n", "json_path = \"../../output/preprocess/Longevity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "46642252", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "92abd42c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:02.674577Z", "iopub.status.busy": "2025-03-25T07:36:02.674434Z", "iopub.status.idle": "2025-03-25T07:36:02.761142Z", "shell.execute_reply": "2025-03-25T07:36:02.760829Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Uppsala Longitudinal Study of Adult Men (ULSAM)\"\n", "!Series_summary\t\"The Uppsala Longitudinal Study of Adult Men is a population-based study aimed at identifying risk factors for cardiovascular disease. At the time of biopsy all subjects were ~ 70yr of age\"\n", "!Series_overall_design\t\"We extracted RNA from muscle tissue taken from 129 subjects, when they were aged ~70yr and characterised as disease-free (note the above average longevity in Swedes born circa 1920 compared with US and UK populations). From these samples, 108 yielded RNA of sufficient quality to profile on Affymetrix gene-chips.\"\n", "!Series_overall_design\t\"Only survival data are used in the paper.\"\n", "!Series_overall_design\t\"There are no data from cardiovascular disease subjects; we only profiled the healthy subjects and followed for 20yrs.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease-free: disease-free'], 1: ['age(approx): 70 yr'], 2: ['tissue: skeletal muscle biopsy (baseline)'], 3: ['survival: None', 'survival: Hosp', 'survival: Death'], 4: ['patient id: 32', 'patient id: 117', 'patient id: 152', 'patient id: 211', 'patient id: 241', 'patient id: 254', 'patient id: 255', 'patient id: 296', 'patient id: 298', 'patient id: 300', 'patient id: 317', 'patient id: 349', 'patient id: 351', 'patient id: 355', 'patient id: 373', 'patient id: 377', 'patient id: 381', 'patient id: 397', 'patient id: 421', 'patient id: 465', 'patient id: 498', 'patient id: 521', 'patient id: 549', 'patient id: 554', 'patient id: 576', 'patient id: 621', 'patient id: 632', 'patient id: 634', 'patient id: 664', 'patient id: 674']}\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": "70307e3a", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "8e1b34bd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:02.762192Z", "iopub.status.busy": "2025-03-25T07:36:02.762086Z", "iopub.status.idle": "2025-03-25T07:36:02.773174Z", "shell.execute_reply": "2025-03-25T07:36:02.772884Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview:\n", "GSM1173505: [nan]\n", "GSM1173506: [1.0]\n", "GSM1173507: [0.0]\n", "GSM1173508: [1.0]\n", "GSM1173509: [1.0]\n", "GSM1173510: [0.0]\n", "GSM1173511: [nan]\n", "GSM1173512: [0.0]\n", "GSM1173513: [1.0]\n", "GSM1173514: [1.0]\n", "GSM1173515: [1.0]\n", "GSM1173516: [0.0]\n", "GSM1173517: [1.0]\n", "GSM1173518: [nan]\n", "GSM1173519: [0.0]\n", "GSM1173520: [1.0]\n", "GSM1173521: [nan]\n", "GSM1173522: [1.0]\n", "GSM1173523: [nan]\n", "GSM1173524: [0.0]\n", "GSM1173525: [1.0]\n", "GSM1173526: [1.0]\n", "GSM1173527: [1.0]\n", "GSM1173528: [1.0]\n", "GSM1173529: [nan]\n", "GSM1173530: [1.0]\n", "GSM1173531: [1.0]\n", "GSM1173532: [nan]\n", "GSM1173533: [1.0]\n", "GSM1173534: [1.0]\n", "GSM1173535: [0.0]\n", "GSM1173536: [1.0]\n", "GSM1173537: [nan]\n", "GSM1173538: [1.0]\n", "GSM1173539: [1.0]\n", "GSM1173540: [1.0]\n", "GSM1173541: [nan]\n", "GSM1173542: [0.0]\n", "GSM1173543: [1.0]\n", "GSM1173544: [1.0]\n", "GSM1173545: [1.0]\n", "GSM1173546: [nan]\n", "GSM1173547: [1.0]\n", "GSM1173548: [nan]\n", "GSM1173549: [0.0]\n", "GSM1173550: [nan]\n", "GSM1173551: [nan]\n", "GSM1173552: [1.0]\n", "GSM1173553: [1.0]\n", "GSM1173554: [1.0]\n", "GSM1173555: [1.0]\n", "GSM1173556: [1.0]\n", "GSM1173557: [1.0]\n", "GSM1173558: [1.0]\n", "GSM1173559: [1.0]\n", "GSM1173560: [1.0]\n", "GSM1173561: [nan]\n", "GSM1173562: [nan]\n", "GSM1173563: [1.0]\n", "GSM1173564: [1.0]\n", "GSM1173565: [nan]\n", "GSM1173566: [nan]\n", "GSM1173567: [nan]\n", "GSM1173568: [nan]\n", "GSM1173569: [nan]\n", "GSM1173570: [1.0]\n", "GSM1173571: [nan]\n", "GSM1173572: [1.0]\n", "GSM1173573: [nan]\n", "GSM1173574: [0.0]\n", "GSM1173575: [1.0]\n", "GSM1173576: [1.0]\n", "GSM1173577: [nan]\n", "GSM1173578: [1.0]\n", "GSM1173579: [1.0]\n", "GSM1173580: [1.0]\n", "GSM1173581: [1.0]\n", "GSM1173582: [nan]\n", "GSM1173583: [1.0]\n", "GSM1173584: [nan]\n", "GSM1173585: [nan]\n", "GSM1173586: [1.0]\n", "GSM1173587: [nan]\n", "GSM1173588: [1.0]\n", "GSM1173589: [1.0]\n", "GSM1173590: [1.0]\n", "GSM1173591: [1.0]\n", "GSM1173592: [1.0]\n", "GSM1173593: [nan]\n", "GSM1173594: [1.0]\n", "GSM1173595: [nan]\n", "GSM1173596: [nan]\n", "GSM1173597: [1.0]\n", "GSM1173598: [1.0]\n", "GSM1173599: [nan]\n", "GSM1173600: [1.0]\n", "GSM1173601: [1.0]\n", "GSM1173602: [1.0]\n", "GSM1173603: [1.0]\n", "GSM1173604: [0.0]\n", "GSM1173605: [1.0]\n", "GSM1173606: [0.0]\n", "GSM1173607: [1.0]\n", "GSM1173608: [1.0]\n", "GSM1173609: [1.0]\n", "GSM1173610: [1.0]\n", "GSM1173611: [1.0]\n", "GSM1173612: [nan]\n", "Clinical data saved to ../../output/preprocess/Longevity/clinical_data/GSE48264.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Background info mentions \"Affymetrix gene-chips\" which indicates this is gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Longevity):\n", "# The background information indicates this is a longevity study where subjects were followed for 20 years\n", "# From sample characteristics, key 3 shows 'survival' status which can represent longevity\n", "trait_row = 3\n", "\n", "# For age:\n", "# All subjects are approximately 70 years old (constant value as per background info)\n", "age_row = None # Since all subjects have the same age (70), it's not useful for our association study\n", "\n", "# For gender:\n", "# No information about gender is provided in the sample characteristics\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert survival status to binary classification for longevity.\"\"\"\n", " if value is None or \"None\" in value:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # In this study, 'Death' likely indicates lower longevity while 'Hosp' or 'None' \n", " # (still in hospital/alive) indicates higher longevity\n", " if value.lower() == \"death\":\n", " return 0 # Death = lower longevity\n", " elif value.lower() in [\"hosp\", \"none\"]:\n", " return 1 # Hospitalized or None (alive) = higher longevity\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous value.\"\"\"\n", " # Not used in this case as age is constant\n", " if value is None:\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " # Extract numeric part from strings like \"70 yr\"\n", " age_value = float(re.search(r'(\\d+)', value).group(1))\n", " return age_value\n", " except (ValueError, AttributeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0=female, 1=male).\"\"\"\n", " # Not used in this case as gender information is not available\n", " if value is None:\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if value.lower() in [\"female\", \"f\"]:\n", " return 0\n", " elif value.lower() in [\"male\", \"m\"]:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "is_trait_available = trait_row is not None\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", " # We've already determined trait data is available\n", " clinical_selected = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the clinical data\n", " preview = preview_df(clinical_selected)\n", " print(\"Clinical Data Preview:\")\n", " for col, values in preview.items():\n", " print(f\"{col}: {values}\")\n", " \n", " # Save the clinical data\n", " clinical_selected.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "7c838419", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "65dff786", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:02.774199Z", "iopub.status.busy": "2025-03-25T07:36:02.774097Z", "iopub.status.idle": "2025-03-25T07:36:02.937474Z", "shell.execute_reply": "2025-03-25T07:36:02.937104Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Uppsala Longitudinal Study of Adult Men (ULSAM)\"\n", "Line 1: !Series_geo_accession\t\"GSE48264\"\n", "Line 2: !Series_status\t\"Public on Aug 05 2015\"\n", "Line 3: !Series_submission_date\t\"Jun 25 2013\"\n", "Line 4: !Series_last_update_date\t\"May 30 2024\"\n", "Line 5: !Series_pubmed_id\t\"26343147\"\n", "Line 6: !Series_summary\t\"The Uppsala Longitudinal Study of Adult Men is a population-based study aimed at identifying risk factors for cardiovascular disease. At the time of biopsy all subjects were ~ 70yr of age\"\n", "Line 7: !Series_overall_design\t\"We extracted RNA from muscle tissue taken from 129 subjects, when they were aged ~70yr and characterised as disease-free (note the above average longevity in Swedes born circa 1920 compared with US and UK populations). From these samples, 108 yielded RNA of sufficient quality to profile on Affymetrix gene-chips.\"\n", "Line 8: !Series_overall_design\t\"Only survival data are used in the paper.\"\n", "Line 9: !Series_overall_design\t\"There are no data from cardiovascular disease subjects; we only profiled the healthy subjects and followed for 20yrs.\"\n", "Found table marker at line 68\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM1173505\"\t\"GSM1173506\"\t\"GSM1173507\"\t\"GSM1173508\"\t\"GSM1173509\"\t\"GSM1173510\"\t\"GSM1173511\"\t\"GSM1173512\"\t\"GSM1173513\"\t\"GSM1173514\"\t\"GSM1173515\"\t\"GSM1173516\"\t\"GSM1173517\"\t\"GSM1173518\"\t\"GSM1173519\"\t\"GSM1173520\"\t\"GSM1173521\"\t\"GSM1173522\"\t\"GSM1173523\"\t\"GSM1173524\"\t\"GSM1173525\"\t\"GSM1173526\"\t\"GSM1173527\"\t\"GSM1173528\"\t\"GSM1173529\"\t\"GSM1173530\"\t\"GSM1173531\"\t\"GSM1173532\"\t\"GSM1173533\"\t\"GSM1173534\"\t\"GSM1173535\"\t\"GSM1173536\"\t\"GSM1173537\"\t\"GSM1173538\"\t\"GSM1173539\"\t\"GSM1173540\"\t\"GSM1173541\"\t\"GSM1173542\"\t\"GSM1173543\"\t\"GSM1173544\"\t\"GSM1173545\"\t\"GSM1173546\"\t\"GSM1173547\"\t\"GSM1173548\"\t\"GSM1173549\"\t\"GSM1173550\"\t\"GSM1173551\"\t\"GSM1173552\"\t\"GSM1173553\"\t\"GSM1173554\"\t\"GSM1173555\"\t\"GSM1173556\"\t\"GSM1173557\"\t\"GSM1173558\"\t\"GSM1173559\"\t\"GSM1173560\"\t\"GSM1173561\"\t\"GSM1173562\"\t\"GSM1173563\"\t\"GSM1173564\"\t\"GSM1173565\"\t\"GSM1173566\"\t\"GSM1173567\"\t\"GSM1173568\"\t\"GSM1173569\"\t\"GSM1173570\"\t\"GSM1173571\"\t\"GSM1173572\"\t\"GSM1173573\"\t\"GSM1173574\"\t\"GSM1173575\"\t\"GSM1173576\"\t\"GSM1173577\"\t\"GSM1173578\"\t\"GSM1173579\"\t\"GSM1173580\"\t\"GSM1173581\"\t\"GSM1173582\"\t\"GSM1173583\"\t\"GSM1173584\"\t\"GSM1173585\"\t\"GSM1173586\"\t\"GSM1173587\"\t\"GSM1173588\"\t\"GSM1173589\"\t\"GSM1173590\"\t\"GSM1173591\"\t\"GSM1173592\"\t\"GSM1173593\"\t\"GSM1173594\"\t\"GSM1173595\"\t\"GSM1173596\"\t\"GSM1173597\"\t\"GSM1173598\"\t\"GSM1173599\"\t\"GSM1173600\"\t\"GSM1173601\"\t\"GSM1173602\"\t\"GSM1173603\"\t\"GSM1173604\"\t\"GSM1173605\"\t\"GSM1173606\"\t\"GSM1173607\"\t\"GSM1173608\"\t\"GSM1173609\"\t\"GSM1173610\"\t\"GSM1173611\"\t\"GSM1173612\"\n", "2315251\t1.6625\t2.51346\t2.36355\t1.91738\t1.82858\t1.85749\t1.24533\t1.31424\t1.66539\t3.67598\t3.00575\t2.09848\t3.42897\t3.00353\t1.35107\t2.16244\t1.43881\t3.74356\t3.65748\t2.09118\t2.83241\t2.10274\t1.84639\t2.57895\t2.96017\t1.74633\t2.27527\t2.3054\t2.6226\t2.59568\t2.60618\t2.01028\t1.27462\t2.44314\t0.94203\t2.00685\t2.08527\t1.48364\t2.60979\t1.65357\t2.67965\t2.52259\t1.69177\t1.87854\t1.32021\t1.51115\t3.19091\t2.32135\t2.12479\t2.26363\t1.64933\t3.43239\t2.27605\t1.83928\t1.92679\t3.20384\t1.53361\t1.72462\t3.35069\t2.10301\t1.8998\t2.51275\t1.93146\t1.18977\t1.3406\t1.58408\t2.12344\t1.69053\t2.4805\t1.53375\t1.56115\t2.29696\t1.44913\t1.91252\t1.37842\t2.25242\t1.89581\t2.25973\t1.54691\t1.93039\t2.15321\t2.80556\t1.58334\t0.72185\t1.18698\t1.96799\t0.48776\t2.27402\t2.60109\t1.593\t2.33917\t1.65513\t1.65221\t1.84232\t2.62009\t2.08524\t2.55304\t1.57812\t1.25171\t1.29531\t1.62561\t1.91207\t1.86378\t1.48925\t2.13879\t1.9227\t2.08824\t1.5927\n", "2315373\t3.50568\t4.3701\t4.65679\t4.00858\t4.58412\t4.3603\t4.41542\t4.34205\t4.14843\t4.64332\t3.49333\t3.93799\t4.41747\t3.53673\t4.54156\t3.77234\t4.47328\t4.12599\t3.45726\t4.38519\t4.79563\t3.83624\t4.45907\t4.19799\t4.40354\t4.58811\t4.65633\t4.37243\t3.92761\t5.0411\t3.75227\t4.57312\t4.78447\t4.8717\t4.86439\t3.58688\t3.98416\t4.19899\t4.33774\t4.04551\t4.16579\t4.06802\t4.98499\t4.29584\t3.98601\t4.06154\t3.671\t4.56422\t4.52809\t4.68446\t3.93118\t3.68203\t4.34013\t4.10425\t3.76499\t4.04342\t3.92433\t3.87268\t4.64779\t3.74486\t4.76143\t4.24988\t3.9635\t4.14533\t4.12101\t4.19695\t4.1222\t4.39882\t4.14096\t4.52043\t4.50402\t4.0903\t4.64056\t4.13182\t3.73438\t3.7124\t4.40603\t3.53301\t4.18143\t4.18906\t3.87816\t4.78147\t4.29978\t4.73193\t4.93363\t3.66046\t5.19922\t4.06943\t4.67873\t3.97599\t4.10228\t4.09797\t4.57418\t3.67079\t4.13481\t3.91291\t3.86234\t3.76643\t4.40242\t4.53476\t3.49467\t3.633\t4.05735\t4.06769\t3.89504\t3.89231\t3.83491\t3.86222\n", "2315554\t5.54892\t5.17464\t6.01821\t6.15828\t6.24022\t5.8784\t5.91033\t6.17278\t6.12394\t5.85066\t3.63529\t5.356\t5.73376\t5.61848\t6.08851\t5.77143\t5.80273\t5.39526\t4.10214\t5.61218\t6.19465\t5.74238\t6.05246\t6.02274\t6.13643\t5.98705\t5.63708\t6.04416\t5.62139\t6.17425\t6.05058\t5.79956\t6.19437\t5.89037\t6.23914\t5.68769\t5.98207\t6.06412\t5.65067\t5.99585\t5.58823\t5.68652\t5.97816\t5.62619\t5.52789\t5.87833\t5.39128\t5.89759\t5.82607\t6.1015\t5.29099\t5.88468\t5.73494\t5.23771\t5.10915\t4.92755\t5.14634\t5.90693\t5.61058\t5.6658\t6.12567\t5.31772\t5.30799\t5.67681\t5.20848\t5.84349\t5.48239\t5.38801\t5.17892\t6.07708\t5.87284\t5.34811\t5.79936\t5.40173\t5.04538\t5.30407\t5.24664\t5.55799\t5.25383\t5.38698\t5.79761\t5.95991\t5.84171\t6.08714\t6.23157\t5.73516\t5.87064\t5.40493\t5.94955\t5.80087\t5.31768\t5.51424\t5.80708\t5.26357\t5.72145\t5.27614\t5.56896\t4.98034\t5.7026\t5.63994\t5.127\t5.32574\t5.26253\t5.67304\t5.44871\t5.56227\t5.32473\t5.43893\n", "2315633\t4.76869\t4.05106\t4.73932\t5.06837\t5.11746\t4.91339\t4.83778\t4.73815\t4.98764\t4.29588\t2.77686\t4.17517\t4.58925\t4.38449\t4.90178\t4.01578\t4.93658\t4.34064\t3.93727\t4.93238\t4.66084\t4.64559\t4.76074\t4.61128\t4.56524\t4.82437\t4.52397\t4.64283\t3.76659\t4.33543\t4.43474\t4.64813\t4.90559\t4.58859\t4.66261\t4.96832\t5.26508\t4.73794\t4.04217\t5.16203\t4.42436\t4.39656\t4.96819\t4.61398\t4.75491\t4.96532\t4.17281\t4.42254\t4.54202\t4.61717\t4.04687\t4.71569\t4.54686\t4.151\t4.16337\t4.01645\t4.39985\t5.01517\t4.05244\t4.29146\t4.64252\t4.31357\t4.10874\t4.46299\t4.1784\t4.44936\t4.35727\t4.45397\t4.47852\t4.59027\t4.47219\t4.39506\t4.34317\t4.15718\t4.08462\t3.98081\t4.10179\t4.44616\t4.21755\t4.43664\t4.2901\t4.33283\t4.69657\t4.99713\t4.83096\t4.17814\t4.58521\t4.18866\t4.31463\t4.58201\t4.05039\t4.3086\t4.96537\t4.28192\t4.73299\t4.32513\t4.17873\t4.41806\t4.17794\t4.52559\t4.15158\t3.96169\t3.8278\t4.33307\t4.25036\t4.33786\t4.47358\t4.3229\n", "Total lines examined: 69\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 18738 rows\n", "First 20 gene IDs:\n", "Index(['2315251', '2315373', '2315554', '2315633', '2315674', '2315739',\n", " '2315894', '2315918', '2315951', '2316069', '2316218', '2316245',\n", " '2316379', '2316558', '2316605', '2316746', '2316905', '2316953',\n", " '2317246', '2317317'],\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": "f439d699", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "9a3b6934", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:02.938793Z", "iopub.status.busy": "2025-03-25T07:36:02.938674Z", "iopub.status.idle": "2025-03-25T07:36:02.940601Z", "shell.execute_reply": "2025-03-25T07:36:02.940330Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers in the gene expression data\n", "# The gene identifiers appear to be numeric values (e.g., 2315251, 2315373)\n", "# These are likely probe IDs from an Affymetrix microarray rather than standard human gene symbols\n", "# Based on Series_summary mentioning Affymetrix gene-chips and the numeric format,\n", "# these identifiers need to be mapped to human gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "ced68391", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "28b25c0a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:02.941764Z", "iopub.status.busy": "2025-03-25T07:36:02.941662Z", "iopub.status.idle": "2025-03-25T07:36:06.480623Z", "shell.execute_reply": "2025-03-25T07:36:06.480251Z" } }, "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 2340731 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['2315100', '2315106', '2315109', '2315111', '2315113'], 'GB_LIST': ['NR_024005,NR_034090,NR_024004,AK093685', 'DQ786314', nan, nan, 'DQ786265'], 'SPOT_ID': ['chr1:11884-14409', 'chr1:14760-15198', 'chr1:19408-19712', 'chr1:25142-25532', 'chr1:27563-27813'], 'seqname': ['chr1', 'chr1', 'chr1', 'chr1', 'chr1'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': ['11884', '14760', '19408', '25142', '27563'], 'RANGE_STOP': ['14409', '15198', '19712', '25532', '27813'], 'total_probes': ['20', '8', '4', '4', '4'], 'gene_assignment': ['NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771', '---', '---', '---', '---'], 'mrna_assignment': ['NR_024005 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 2, non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_034090 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 (DDX11L9), non-coding RNA. // chr1 // 100 // 80 // 16 // 16 // 0 /// NR_024004 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 (DDX11L2), transcript variant 1, non-coding RNA. // chr1 // 100 // 75 // 15 // 15 // 0 /// AK093685 // GenBank // Homo sapiens cDNA FLJ36366 fis, clone THYMU2007824. // chr1 // 94 // 80 // 15 // 16 // 0 /// ENST00000513886 // ENSEMBL // cdna:known chromosome:GRCh37:16:61555:64090:1 gene:ENSG00000233614 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000456328 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000223972 // chr1 // 100 // 80 // 16 // 16 // 0 /// ENST00000518655 // ENSEMBL // cdna:known chromosome:GRCh37:1:11869:14409:1 gene:ENSG00000253101 // chr1 // 100 // 80 // 16 // 16 // 0', 'DQ786314 // GenBank // Homo sapiens clone HLS_IMAGE_811138 mRNA sequence. // chr1 // 100 // 38 // 3 // 3 // 0', '---', '---', 'DQ786265 // GenBank // Homo sapiens clone HLS_IMAGE_298685 mRNA sequence. // chr1 // 100 // 100 // 4 // 4 // 0'], 'category': ['main', 'main', '---', '---', 'main']}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'GB_LIST', 'SPOT_ID', 'seqname', 'RANGE_GB', 'RANGE_STRAND', 'RANGE_START', 'RANGE_STOP', 'total_probes', 'gene_assignment', 'mrna_assignment', 'category']\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: chr1:11884-14409\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": "298fdd12", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "2e915ef3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:06.481991Z", "iopub.status.busy": "2025-03-25T07:36:06.481866Z", "iopub.status.idle": "2025-03-25T07:36:10.448070Z", "shell.execute_reply": "2025-03-25T07:36:10.447677Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Analyzing gene assignment data format...\n", "Sample gene assignments:\n", "1: NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// NR_034090 // DDX11L9 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 9 // 15q26.3 // 100288486 /// NR_024004 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771 /// AK093685 // DDX11L2 // DEAD/H (Asp-Glu-Ala-Asp/His) box polypeptide 11 like 2 // 2q13 // 84771\n", "2: ---\n", "3: ---\n", "\n", "Creating gene mapping dataframe...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Initial mapping dataframe shape: (33475, 2)\n", "Sample of mapping dataframe before processing:\n", " ID Gene\n", "0 2315100 NR_024005 // DDX11L2 // DEAD/H (Asp-Glu-Ala-As...\n", "10 2315125 NM_001005240 // OR4F17 // olfactory receptor, ...\n", "14 2315147 XM_002343043 // LOC100288692 // protein capicu...\n", "15 2315160 AK303004 // FLJ45445 // hypothetical LOC399844...\n", "16 2315163 AK302511 // LOC100132062 // hypothetical LOC10...\n", "\n", "Applying gene mapping to convert probe-level expression to gene-level expression...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Resulting gene expression dataframe shape: (50375, 108)\n", "First few gene symbols in gene expression data:\n", "['A-', 'A-2', 'A-52', 'A-E', 'A-I', 'A-II', 'A-IV', 'A-V', 'A0', 'A1']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Longevity/gene_data/GSE48264.csv\n" ] } ], "source": [ "# 1. From the gene annotation preview, I can see that:\n", "# - The 'ID' column in gene_annotation matches the probe IDs in gene_data\n", "# - The 'gene_assignment' column contains gene symbol information but needs parsing\n", "\n", "print(\"\\nAnalyzing gene assignment data format...\")\n", "# Examine the gene_assignment format to understand how to extract gene symbols\n", "gene_assignment_samples = gene_annotation['gene_assignment'].dropna().head(10).tolist()\n", "print(\"Sample gene assignments:\")\n", "for i, sample in enumerate(gene_assignment_samples[:3]): # Just show first 3 for brevity\n", " print(f\"{i+1}: {sample}\")\n", "\n", "# 2. Create a mapping between probe IDs and gene symbols\n", "print(\"\\nCreating gene mapping dataframe...\")\n", "\n", "# First, filter out rows without gene assignments or with placeholder assignments\n", "gene_annotation_filtered = gene_annotation[~gene_annotation['gene_assignment'].isin(['---', 'nan', ''])]\n", "gene_annotation_filtered = gene_annotation_filtered.dropna(subset=['gene_assignment'])\n", "\n", "# Create a mapping dataframe with ID and Gene columns\n", "mapping_df = pd.DataFrame()\n", "mapping_df['ID'] = gene_annotation_filtered['ID']\n", "mapping_df['Gene'] = gene_annotation_filtered['gene_assignment']\n", "\n", "# Convert the mapping dataframe to the required format\n", "print(f\"Initial mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"Sample of mapping dataframe before processing:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene-level expression\n", "print(\"\\nApplying gene mapping to convert probe-level expression to gene-level expression...\")\n", "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)\n", "print(f\"Resulting gene expression dataframe shape: {gene_data.shape}\")\n", "print(\"First few gene symbols in gene expression data:\")\n", "print(list(gene_data.index[:10]))\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" ] }, { "cell_type": "markdown", "id": "8fb64ea8", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "cfe50180", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:36:10.449487Z", "iopub.status.busy": "2025-03-25T07:36:10.449353Z", "iopub.status.idle": "2025-03-25T07:36:21.740358Z", "shell.execute_reply": "2025-03-25T07:36:21.740014Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols using NCBI Gene database...\n", "After normalization: 18910 unique gene symbols\n", "Sample of normalized gene symbols: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Longevity/gene_data/GSE48264.csv\n", "\n", "Loading clinical data...\n", "Loaded clinical data with shape: (1, 108)\n", "\n", "Linking clinical and genetic data...\n", "Linked data shape: (108, 18911)\n", "\n", "Handling missing values in linked data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data shape after handling missing values: (76, 18911)\n", "\n", "Evaluating trait and demographic feature bias...\n", "For the feature 'Longevity', the least common label is '0.0' with 12 occurrences. This represents 15.79% of the dataset.\n", "The distribution of the feature 'Longevity' in this dataset is fine.\n", "\n", "\n", "Saving linked data to ../../output/preprocess/Longevity/GSE48264.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved successfully!\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(\"\\nNormalizing gene symbols using NCBI Gene database...\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization: {normalized_gene_data.shape[0]} unique gene symbols\")\n", "print(f\"Sample of normalized gene symbols: {normalized_gene_data.index[:5].tolist()}\")\n", "\n", "# Save the normalized gene data\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load clinical data\n", "print(\"\\nLoading clinical data...\")\n", "try:\n", " clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(f\"Loaded clinical data with shape: {clinical_data.shape}\")\n", " is_trait_available = True\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {str(e)}\")\n", " is_trait_available = False\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", " linked_data = geo_link_clinical_genetic_data(clinical_data, normalized_gene_data)\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", " \n", " # 6. Final validation and saving\n", " note = \"This dataset contains gene expression data from skeletal muscle biopsies of elderly men (age ~70) with longevity as the trait of interest, determined by survival status over a 20-year follow-up period.\"\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", " # Save the linked data if it's usable\n", " if is_usable:\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.\")\n", "else:\n", " print(\"\\nCannot create linked data: missing clinical or gene data\")\n", " # Set up dummy linked_data for validation\n", " linked_data = pd.DataFrame()\n", " is_biased = True\n", " \n", " note = f\"Dataset contains {'gene expression data' if is_gene_available else 'no gene data'} but {'lacks' if not is_trait_available else 'has'} clinical information for {trait}.\"\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", " print(f\"\\nDataset usability for {trait} association studies: {is_usable}\")" ] } ], "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 }