{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "44d8b5ef", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:13.320471Z", "iopub.status.busy": "2025-03-25T07:27:13.320287Z", "iopub.status.idle": "2025-03-25T07:27:13.482627Z", "shell.execute_reply": "2025-03-25T07:27:13.482303Z" } }, "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 = \"GSE243973\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Large_B-cell_Lymphoma\"\n", "in_cohort_dir = \"../../input/GEO/Large_B-cell_Lymphoma/GSE243973\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/GSE243973.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE243973.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE243973.csv\"\n", "json_path = \"../../output/preprocess/Large_B-cell_Lymphoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ad305405", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "5912099e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:13.483952Z", "iopub.status.busy": "2025-03-25T07:27:13.483816Z", "iopub.status.idle": "2025-03-25T07:27:13.502786Z", "shell.execute_reply": "2025-03-25T07:27:13.502415Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Circulating monocyte counts coupled with a 4-gene signature at leukapheresis predict survival of lymphoma patients treated with CAR T\"\n", "!Series_summary\t\"CD19-directed chimeric antigen receptor (CAR) T cells can induce durable remissions in relapsed/refractory large B-cell lymphomas (R/R LBCL), but 60% of patients still relapse. Biological mechanisms explaining lack of disease-response are largely unknown. To identify mechanisms of response and survival before CAR T manufacturing in 95 R/R LBCL receiving tisagenlecleucel or axicabtagene ciloleucel, we performed phenotypic, transcriptomic and functional evaluations of leukapheresis products (LK). Transcriptomic profiling of T cells in LK, revealed a signature composed of 4 myeloid genes able to identify patients with very short progression-free survival, highlighting the role of monocytes in CAR T therapy response. Accordingly, response and survival were negatively influenced by high circulating absolute monocyte counts at the time of leukapheresis, and the combined evaluation of peripheral blood monocytes and the four-gene signature in LK, identifies LBCL patients at very high risk of progression after CAR T.\"\n", "!Series_overall_design\t\"The transcriptomic analysis was performed on a cohort of 77 relapsed/refractory large B-cell lymphoma patients. CD3+ T cells selected from 77 patient leukapheresis and 8 leftover lymphocytes from donor lymphocyte infusions (healthy controls) were profiled using the nCounter 780 gene CAR-T characterization panel.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: large B-cell lymphoma', 'disease state: healthy control'], 1: ['model (1: EXP, 2: poor-EXP): 2', 'model (1: EXP, 2: poor-EXP): 1', 'model (1: EXP, 2: poor-EXP): n/a'], 2: ['cell type: CD3+ selected leukapheresis, patient', 'cell type: CD3+ selected donor lymphocyte infusion, healthy control']}\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": "f97f58af", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "3c324123", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:13.504082Z", "iopub.status.busy": "2025-03-25T07:27:13.503969Z", "iopub.status.idle": "2025-03-25T07:27:13.513064Z", "shell.execute_reply": "2025-03-25T07:27:13.512749Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'GSM7802550': [1.0], 'GSM7802551': [1.0], 'GSM7802552': [1.0], 'GSM7802553': [1.0], 'GSM7802554': [1.0], 'GSM7802555': [1.0], 'GSM7802556': [1.0], 'GSM7802557': [1.0], 'GSM7802558': [1.0], 'GSM7802559': [1.0], 'GSM7802560': [1.0], 'GSM7802561': [1.0], 'GSM7802562': [1.0], 'GSM7802563': [1.0], 'GSM7802564': [1.0], 'GSM7802565': [1.0], 'GSM7802566': [1.0], 'GSM7802567': [1.0], 'GSM7802568': [1.0], 'GSM7802569': [1.0], 'GSM7802570': [0.0], 'GSM7802571': [0.0], 'GSM7802572': [1.0], 'GSM7802573': [1.0], 'GSM7802574': [1.0], 'GSM7802575': [1.0], 'GSM7802576': [1.0], 'GSM7802577': [0.0], 'GSM7802578': [0.0], 'GSM7802579': [0.0], 'GSM7802580': [1.0], 'GSM7802581': [1.0], 'GSM7802582': [1.0], 'GSM7802583': [1.0], 'GSM7802584': [1.0], 'GSM7802585': [1.0], 'GSM7802586': [1.0], 'GSM7802587': [1.0], 'GSM7802588': [1.0], 'GSM7802589': [1.0], 'GSM7802590': [1.0], 'GSM7802591': [0.0], 'GSM7802592': [0.0], 'GSM7802593': [0.0], 'GSM7802594': [1.0], 'GSM7802595': [1.0], 'GSM7802596': [1.0], 'GSM7802597': [1.0], 'GSM7802598': [1.0], 'GSM7802599': [1.0], 'GSM7802600': [1.0], 'GSM7802601': [1.0], 'GSM7802602': [1.0], 'GSM7802603': [1.0], 'GSM7802604': [1.0], 'GSM7802605': [1.0], 'GSM7802606': [1.0], 'GSM7802607': [1.0], 'GSM7802608': [1.0], 'GSM7802609': [1.0], 'GSM7802610': [1.0], 'GSM7802611': [1.0], 'GSM7802612': [1.0], 'GSM7802613': [1.0], 'GSM7802614': [1.0], 'GSM7802615': [1.0], 'GSM7802616': [1.0], 'GSM7802617': [1.0], 'GSM7802618': [1.0], 'GSM7802619': [1.0], 'GSM7802620': [1.0], 'GSM7802621': [1.0], 'GSM7802622': [1.0], 'GSM7802623': [1.0], 'GSM7802624': [1.0], 'GSM7802625': [1.0], 'GSM7802626': [1.0], 'GSM7802627': [1.0], 'GSM7802628': [1.0], 'GSM7802629': [1.0], 'GSM7802630': [1.0], 'GSM7802631': [1.0], 'GSM7802632': [1.0], 'GSM7802633': [1.0], 'GSM7802634': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE243973.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# Review the output from previous step:\n", "# 1. Gene Expression Data Availability\n", "# Based on the description, this dataset contains transcriptomic data of CD3+ T cells\n", "# from LBCL patients and healthy controls. This indicates gene expression data.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability:\n", "# From the sample characteristics dictionary:\n", "\n", "# For trait: Row 0 contains 'disease state' which indicates health status\n", "trait_row = 0\n", "\n", "# For age: No information on age is provided in the sample characteristics dictionary\n", "age_row = None\n", "\n", "# For gender: No information on gender is provided in the sample characteristics dictionary\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion:\n", "# For trait: Convert from disease state to binary (healthy control = 0, large B-cell lymphoma = 1)\n", "def convert_trait(value):\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"healthy control\" in value.lower():\n", " return 0\n", " elif \"large b-cell lymphoma\" in value.lower():\n", " return 1\n", " else:\n", " return None\n", "\n", "# Since age and gender are not available, we define placeholder conversion functions\n", "def convert_age(value):\n", " return None\n", "\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Conduct initial filtering using the validate_and_save_cohort_info function\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 (if trait data available)\n", "if trait_row is not None and 'clinical_data' in locals():\n", " # Extract clinical features using the existing clinical_data\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Create output directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data to CSV\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": "eab81ea6", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "e837f298", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:13.514162Z", "iopub.status.busy": "2025-03-25T07:27:13.514055Z", "iopub.status.idle": "2025-03-25T07:27:13.530995Z", "shell.execute_reply": "2025-03-25T07:27:13.530683Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Circulating monocyte counts coupled with a 4-gene signature at leukapheresis predict survival of lymphoma patients treated with CAR T\"\n", "Line 1: !Series_geo_accession\t\"GSE243973\"\n", "Line 2: !Series_status\t\"Public on Apr 24 2024\"\n", "Line 3: !Series_submission_date\t\"Sep 25 2023\"\n", "Line 4: !Series_last_update_date\t\"Apr 25 2024\"\n", "Line 5: !Series_pubmed_id\t\"38359407\"\n", "Line 6: !Series_summary\t\"CD19-directed chimeric antigen receptor (CAR) T cells can induce durable remissions in relapsed/refractory large B-cell lymphomas (R/R LBCL), but 60% of patients still relapse. Biological mechanisms explaining lack of disease-response are largely unknown. To identify mechanisms of response and survival before CAR T manufacturing in 95 R/R LBCL receiving tisagenlecleucel or axicabtagene ciloleucel, we performed phenotypic, transcriptomic and functional evaluations of leukapheresis products (LK). Transcriptomic profiling of T cells in LK, revealed a signature composed of 4 myeloid genes able to identify patients with very short progression-free survival, highlighting the role of monocytes in CAR T therapy response. Accordingly, response and survival were negatively influenced by high circulating absolute monocyte counts at the time of leukapheresis, and the combined evaluation of peripheral blood monocytes and the four-gene signature in LK, identifies LBCL patients at very high risk of progression after CAR T.\"\n", "Line 7: !Series_overall_design\t\"The transcriptomic analysis was performed on a cohort of 77 relapsed/refractory large B-cell lymphoma patients. CD3+ T cells selected from 77 patient leukapheresis and 8 leftover lymphocytes from donor lymphocyte infusions (healthy controls) were profiled using the nCounter 780 gene CAR-T characterization panel.\"\n", "Line 8: !Series_type\t\"Expression profiling by array\"\n", "Line 9: !Series_contributor\t\"Cristiana,,Carniti\"\n", "Found table marker at line 73\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM7802550\"\t\"GSM7802551\"\t\"GSM7802552\"\t\"GSM7802553\"\t\"GSM7802554\"\t\"GSM7802555\"\t\"GSM7802556\"\t\"GSM7802557\"\t\"GSM7802558\"\t\"GSM7802559\"\t\"GSM7802560\"\t\"GSM7802561\"\t\"GSM7802562\"\t\"GSM7802563\"\t\"GSM7802564\"\t\"GSM7802565\"\t\"GSM7802566\"\t\"GSM7802567\"\t\"GSM7802568\"\t\"GSM7802569\"\t\"GSM7802570\"\t\"GSM7802571\"\t\"GSM7802572\"\t\"GSM7802573\"\t\"GSM7802574\"\t\"GSM7802575\"\t\"GSM7802576\"\t\"GSM7802577\"\t\"GSM7802578\"\t\"GSM7802579\"\t\"GSM7802580\"\t\"GSM7802581\"\t\"GSM7802582\"\t\"GSM7802583\"\t\"GSM7802584\"\t\"GSM7802585\"\t\"GSM7802586\"\t\"GSM7802587\"\t\"GSM7802588\"\t\"GSM7802589\"\t\"GSM7802590\"\t\"GSM7802591\"\t\"GSM7802592\"\t\"GSM7802593\"\t\"GSM7802594\"\t\"GSM7802595\"\t\"GSM7802596\"\t\"GSM7802597\"\t\"GSM7802598\"\t\"GSM7802599\"\t\"GSM7802600\"\t\"GSM7802601\"\t\"GSM7802602\"\t\"GSM7802603\"\t\"GSM7802604\"\t\"GSM7802605\"\t\"GSM7802606\"\t\"GSM7802607\"\t\"GSM7802608\"\t\"GSM7802609\"\t\"GSM7802610\"\t\"GSM7802611\"\t\"GSM7802612\"\t\"GSM7802613\"\t\"GSM7802614\"\t\"GSM7802615\"\t\"GSM7802616\"\t\"GSM7802617\"\t\"GSM7802618\"\t\"GSM7802619\"\t\"GSM7802620\"\t\"GSM7802621\"\t\"GSM7802622\"\t\"GSM7802623\"\t\"GSM7802624\"\t\"GSM7802625\"\t\"GSM7802626\"\t\"GSM7802627\"\t\"GSM7802628\"\t\"GSM7802629\"\t\"GSM7802630\"\t\"GSM7802631\"\t\"GSM7802632\"\t\"GSM7802633\"\t\"GSM7802634\"\n", "\"ABCF1\"\t9.535\t9.309\t9.543\t9.201\t9.589\t9.453\t9.318\t9.435\t9.539\t9.357\t9.19\t9.378\t10.01\t9.513\t9.595\t9.157\t9.476\t9.463\t9.072\t9.208\t8.862\t9.175\t9.197\t9.717\t9.24\t9.289\t9.706\t9.3\t8.732\t9.152\t9.299\t9.549\t9.514\t9.435\t9.608\t9.339\t9.567\t9.809\t9.413\t9.353\t9.242\t9.267\t9.304\t9.212\t9.515\t9.531\t9.777\t9.714\t8.923\t9.317\t9.319\t9.384\t9.459\t9.598\t9.477\t9.789\t9.676\t9.073\t9.031\t9.419\t9.814\t9.621\t9.395\t9.436\t9.351\t9.504\t10.05\t9.067\t9.31\t9.48\t9.424\t9.189\t9.512\t9.33\t9.11\t9.092\t9.442\t9.298\t9.33\t9.434\t9.755\t8.847\t9.257\t9.66\t9.193\n", "\"ACACA\"\t4.769\t4.022\t4.367\t4.495\t4.039\t4.091\t4.312\t4.044\t4.513\t4.305\t4.191\t2.964\t0\t0\t0\t3.997\t2.213\t0\t0\t3.369\t3.809\t0\t0.08948\t0\t0\t0\t0\t1.71\t4.181\t3.939\t4.536\t3.025\t0.9805\t3.019\t0\t1.983\t3.895\t0\t4.51\t4.874\t4.796\t4.494\t3.49\t5.122\t3.667\t3.267\t2.653\t0\t3.627\t0\t5.051\t4.068\t3.172\t3.648\t0\t0\t4.28\t0\t0\t0\t0\t0\t3.553\t3.744\t4.885\t0\t4.778\t0\t3.314\t1.481\t3.406\t2.5\t3.528\t0\t0\t3.742\t4.756\t1.074\t2.811\t4.372\t4.508\t0\t4.221\t4.075\t3.8\n", "\"ACAD10\"\t7.961\t7.394\t7.748\t7.593\t7.499\t7.012\t7.68\t7.738\t7.428\t7.362\t7.304\t7.445\t7.29\t7.467\t6.797\t7.301\t7.907\t7.601\t6.275\t7.615\t7.632\t5.815\t7.274\t7.524\t7.704\t7.662\t6.179\t7.535\t7.865\t8.148\t7.757\t7.326\t7.267\t7.49\t7.647\t6.971\t7.037\t6.437\t7.257\t7.622\t7.751\t7.438\t8.097\t8.045\t6.501\t6.941\t8.512\t6.769\t7.387\t7.352\t7.698\t6.833\t8.078\t8.044\t7.698\t5.121\t8.072\t6.507\t6.729\t7.478\t7.371\t6.397\t7.811\t8.026\t8.018\t7.296\t7.805\t7.819\t7.022\t7.104\t7.841\t7.711\t8.095\t7.615\t7.376\t7.041\t8.093\t7.259\t7.596\t7.579\t7.9\t7.12\t7.419\t7.413\t7.716\n", "\"ACADVL\"\t10.62\t10.8\t10.65\t10.46\t10.83\t10.52\t10.34\t10.84\t10.47\t10.72\t10.78\t10.47\t10.97\t10.47\t10.31\t10.58\t10.26\t10.86\t9.967\t10.5\t10.41\t9.937\t10.7\t10.89\t10.46\t10.9\t10.56\t10.98\t10.22\t10.32\t10.45\t10.63\t10.19\t10.65\t10.89\t10.72\t10.61\t10.55\t10.86\t10.57\t10.51\t10.31\t10.89\t10.67\t10.46\t10.78\t11.81\t10.64\t10.33\t11.74\t10.52\t10.33\t10.42\t10.37\t10.84\t11.16\t10.64\t11.52\t11.13\t10.93\t11.85\t11.25\t10.35\t10.87\t10.54\t10.59\t11.22\t10.29\t10.45\t10.88\t10.31\t10.2\t10.48\t11.07\t10.69\t10.25\t10.11\t10.44\t10.6\t10.49\t10.66\t11.13\t10.45\t10.53\t10.21\n", "Total lines examined: 74\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 794 rows\n", "First 20 gene IDs:\n", "Index(['ABCF1', 'ACACA', 'ACAD10', 'ACADVL', 'ACOT2', 'ACSF2', 'ACSL5',\n", " 'ACTN1', 'ACVR1B', 'ACVR1C', 'ACVR2A', 'ADAR', 'ADD1', 'ADORA2A',\n", " 'AFDN', 'AHR', 'AKT1', 'AKT2', 'ALDH1L1', 'ALDH1L2'],\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": "e25f9c3f", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "9a3c3a5e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:13.532060Z", "iopub.status.busy": "2025-03-25T07:27:13.531949Z", "iopub.status.idle": "2025-03-25T07:27:13.533956Z", "shell.execute_reply": "2025-03-25T07:27:13.533653Z" } }, "outputs": [], "source": [ "# Review gene identifiers\n", "# Looking at the gene IDs from the output: ABCF1, ACACA, ACAD10, ACADVL, etc.\n", "# These appear to be standard human gene symbols. They follow the official gene symbol nomenclature\n", "# with uppercase letters and occasionally numbers. They match known human genes.\n", "# Examples:\n", "# - ABCF1: ATP Binding Cassette Subfamily F Member 1\n", "# - ACACA: Acetyl-CoA Carboxylase Alpha\n", "# - AKT1: AKT Serine/Threonine Kinase 1\n", "# - ADAR: Adenosine Deaminase RNA Specific\n", "\n", "# The data appears to be from the nCounter 780 gene CAR-T characterization panel,\n", "# which typically uses standard gene symbols.\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "327e87c2", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "d7d860f9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:13.535047Z", "iopub.status.busy": "2025-03-25T07:27:13.534935Z", "iopub.status.idle": "2025-03-25T07:27:13.675211Z", "shell.execute_reply": "2025-03-25T07:27:13.674770Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "After normalization: 762 genes\n", "Normalized gene data saved to ../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE243973.csv\n", "\n", "Loading previously saved clinical data...\n", "Loaded clinical data with shape: (1, 85)\n", "\n", "Linking clinical and genetic data...\n", "Created linked data with 86 samples and 846 features\n", "\n", "Handling missing values...\n", "After handling missing values: 1 samples and 84 features\n", "\n", "Evaluating feature bias...\n", "Quartiles for 'Large_B-cell_Lymphoma':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1.0\n", "Max: 1.0\n", "The distribution of the feature 'Large_B-cell_Lymphoma' in this dataset is severely biased.\n", "\n", "Trait bias determination: True\n", "Final linked data shape: 1 samples and 84 features\n", "\n", "Performing final validation...\n", "\n", "Dataset usability for Large_B-cell_Lymphoma association studies: False\n", "Reason: Dataset has severe bias in the trait distribution\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "print(\"\\nNormalizing gene symbols...\")\n", "# Get the gene data from previous step\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# Use the normalize_gene_symbols_in_index function to standardize gene symbols\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"After normalization: {len(normalized_gene_data.index)} genes\")\n", "\n", "# Save the normalized gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Load the clinical data that was already saved in step 2\n", "print(\"\\nLoading previously saved clinical data...\")\n", "if os.path.exists(out_clinical_data_file):\n", " clinical_df = pd.read_csv(out_clinical_data_file)\n", " is_trait_available = True\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", "else:\n", " print(\"Clinical data file not found. Attempting to recreate it.\")\n", " # Re-extract clinical features using correct parameters from Step 2\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Use the correct parameters from Step 2\n", " trait_row = 0\n", " \n", " def convert_trait(value):\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"healthy control\" in value.lower():\n", " return 0\n", " elif \"large b-cell lymphoma\" in value.lower():\n", " return 1\n", " else:\n", " return None\n", " \n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=None,\n", " convert_age=None,\n", " gender_row=None,\n", " convert_gender=None\n", " )\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Re-created clinical data saved to {out_clinical_data_file}\")\n", " \n", " clinical_df = selected_clinical_df\n", " is_trait_available = True if trait_row is not None else False\n", "\n", "# 3. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "try:\n", " if is_trait_available and not clinical_df.empty:\n", " # Convert clinical_df to format expected by geo_link_clinical_genetic_data\n", " # If clinical_df is already in the right format, just use it directly\n", " if not isinstance(clinical_df.index, pd.Index) or clinical_df.index.name != 'Large_B-cell_Lymphoma':\n", " # If we loaded from CSV, we need to transpose and set the index\n", " # First check if the trait is in the columns\n", " if trait in clinical_df.columns:\n", " # Just use the dataframe directly - it's already in the right format\n", " pass\n", " else:\n", " # Convert to the right format: transpose dataframe\n", " clinical_df_transposed = clinical_df.set_index(clinical_df.columns[0]).T\n", " clinical_df = clinical_df_transposed\n", "\n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\n", " print(f\"Created linked data with {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n", " else:\n", " print(\"Cannot link data: clinical data is not available\")\n", " linked_data = pd.DataFrame()\n", " is_trait_available = False\n", "except Exception as e:\n", " print(f\"Error linking clinical and genetic data: {e}\")\n", " is_trait_available = False\n", " linked_data = pd.DataFrame()\n", "\n", "# 4. Handle missing values in the linked data\n", "if is_trait_available and not linked_data.empty:\n", " print(\"\\nHandling missing values...\")\n", " try:\n", " # Rename the first column to the trait name for consistency\n", " if linked_data.columns[0] != trait:\n", " linked_data = linked_data.rename(columns={linked_data.columns[0]: trait})\n", " \n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"After handling missing values: {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n", " except Exception as e:\n", " print(f\"Error handling missing values: {e}\")\n", " \n", " # 5. Determine whether the trait and demographic features are biased\n", " print(\"\\nEvaluating feature bias...\")\n", " try:\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Trait bias determination: {is_biased}\")\n", " print(f\"Final linked data shape: {linked_data.shape[0]} samples and {linked_data.shape[1]} features\")\n", " except Exception as e:\n", " print(f\"Error evaluating feature bias: {e}\")\n", " is_biased = True\n", "else:\n", " print(\"\\nSkipping missing value handling and bias evaluation as linked data is not available\")\n", " is_biased = True\n", "\n", "# 6. Validate and save cohort information\n", "print(\"\\nPerforming final validation...\")\n", "note = \"\"\n", "if not is_trait_available:\n", " note = \"Dataset does not contain required trait information\"\n", "elif is_biased:\n", " note = \"Dataset has severe bias in the trait distribution\"\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", "# 7. Save the linked data if usable\n", "print(f\"\\nDataset usability for {trait} association studies: {is_usable}\")\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Final linked data saved to {out_data_file}\")\n", "else:\n", " if note:\n", " print(f\"Reason: {note}\")\n", " else:\n", " print(\"Dataset does not meet quality criteria for the specified trait\")" ] } ], "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 }