{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "c8af996b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:12.017870Z", "iopub.status.busy": "2025-03-25T07:27:12.017398Z", "iopub.status.idle": "2025-03-25T07:27:12.180439Z", "shell.execute_reply": "2025-03-25T07:27:12.180121Z" } }, "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 = \"GSE197977\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Large_B-cell_Lymphoma\"\n", "in_cohort_dir = \"../../input/GEO/Large_B-cell_Lymphoma/GSE197977\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/GSE197977.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE197977.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE197977.csv\"\n", "json_path = \"../../output/preprocess/Large_B-cell_Lymphoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "7f146e28", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "fba14596", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:12.181791Z", "iopub.status.busy": "2025-03-25T07:27:12.181661Z", "iopub.status.idle": "2025-03-25T07:27:12.208804Z", "shell.execute_reply": "2025-03-25T07:27:12.208531Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Tumour immune contexture is a determinant of anti-CD19 CAR T-cell efficacy in large B cell lymphoma\"\n", "!Series_summary\t\"Axicabtagene ciloleucel (axi-cel), an anti-CD19 chimeric antigen receptor (CAR) T-cell therapy approved for treatment of relapsed/refractory large B-cell lymphoma (LBCL), has comparable efficacy across conventional LBCL markers. We analysed whether pre- and posttreatment tumour immune contexture determines clinical outcomes for axi cel–treated patients in the ZUMA-1 pivotal study. Longitudinal evaluation of the tumour microenvironment (TME) uncovered dynamic patterns that occurred rapidly after axi-cel (within 2 weeks) in responders—pronounced enhancement of T- and myeloid cell signatures and diminution of B cell signature. Clinical response and overall survival associated with high CD8+ T-cell density (Immunoscore) and immune gene expression (Immunosign21) in TME pretreatment, which was paralleled by blood CAR T-cell levels posttreatment. High density of regulatory T cells in TME pretreatment associated with reduced axi-cel–related neurologic toxicity. At relapse, the TME evolved toward an immune-detrimental contexture with decreased T-cell–related and increased counterregulatory immune signatures and B cell lineage antigens. A TME rich in T-cell attractive chemokines (CCL5, CCL22), gamma-chain receptor cytokines (IL-15, IL-7, IL-21), and interferon regulated molecules associated with T-cell infiltration and markers of activity, a result validated in 2 independent datasets totalling ≈300 LBCL samples.\"\n", "!Series_summary\t\"These findings advance mechanistic understanding of CAR T-cell therapy and foster biomarker development and treatment optimizations.\"\n", "!Series_overall_design\t\"71 samples were analyzed for 65 patients with screening, baseline, DAY7-14, FCBWK4 and PROGFCB time points.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['visit: SCREENING', 'visit: BASELINE', 'visit: DAY7-14', 'visit: FCBWK4', 'visit: PROGFCB'], 1: ['molecular subgroup: GCB', 'molecular subgroup: NA', 'molecular subgroup: ABC', 'molecular subgroup: UNCLASSIFIED'], 2: ['bestresponse: PR', 'bestresponse: CR', 'bestresponse: SD', 'bestresponse: PD', 'bestresponse: ND'], 3: ['baseline tumour burden (mm2): 8877', 'baseline tumour burden (mm2): 667', 'baseline tumour burden (mm2): 2441', 'baseline tumour burden (mm2): 7700', 'baseline tumour burden (mm2): 4248', 'baseline tumour burden (mm2): 3916', 'baseline tumour burden (mm2): 4205', 'baseline tumour burden (mm2): 5056', 'baseline tumour burden (mm2): 355', 'baseline tumour burden (mm2): 7161', 'baseline tumour burden (mm2): NA', 'baseline tumour burden (mm2): 2794', 'baseline tumour burden (mm2): 792', 'baseline tumour burden (mm2): 5456', 'baseline tumour burden (mm2): 39658', 'baseline tumour burden (mm2): 1997', 'baseline tumour burden (mm2): 1133', 'baseline tumour burden (mm2): 2924', 'baseline tumour burden (mm2): 6557', 'baseline tumour burden (mm2): 1600', 'baseline tumour burden (mm2): 4371', 'baseline tumour burden (mm2): 2200', 'baseline tumour burden (mm2): 7952', 'baseline tumour burden (mm2): 6262', 'baseline tumour burden (mm2): 14354', 'baseline tumour burden (mm2): 396', 'baseline tumour burden (mm2): 2069', 'baseline tumour burden (mm2): 1022', 'baseline tumour burden (mm2): 8162', 'baseline tumour burden (mm2): 735'], 4: ['worst grade of ne: 3', 'worst grade of ne: 1', 'worst grade of ne: 2', 'worst grade of ne: 0', 'worst grade of ne: 4']}\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": "4023f14b", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "ba21a6ae", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:12.209795Z", "iopub.status.busy": "2025-03-25T07:27:12.209696Z", "iopub.status.idle": "2025-03-25T07:27:12.217675Z", "shell.execute_reply": "2025-03-25T07:27:12.217408Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data preview: {0: [1.0], 1: [1.0], 2: [0.0], 3: [0.0], 4: [0.0], 5: [nan], 6: [nan], 7: [nan], 8: [nan], 9: [nan], 10: [nan], 11: [nan], 12: [nan], 13: [nan], 14: [nan], 15: [nan], 16: [nan], 17: [nan], 18: [nan], 19: [nan], 20: [nan], 21: [nan], 22: [nan], 23: [nan], 24: [nan], 25: [nan], 26: [nan], 27: [nan], 28: [nan], 29: [nan]}\n", "Clinical data saved to ../../output/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE197977.csv\n" ] } ], "source": [ "import os\n", "import json\n", "import pandas as pd\n", "from typing import Any, Dict, Optional, Callable, List\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the Series_summary and Series_overall_design, this appears to be a dataset studying Large B-cell Lymphoma \n", "# with gene expression data (immune contexture, TME analysis)\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 & 2.2 For trait (Large B-cell Lymphoma)\n", "# From the sample characteristics, \"bestresponse\" at index 2 indicates clinical outcomes\n", "# which is relevant to the trait (lymphoma response to treatment)\n", "trait_row = 2\n", "\n", "def convert_trait(value):\n", " if pd.isna(value) or value == 'NA':\n", " return None\n", " # Extract the value after colon and trim whitespace\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert response to binary (favorable vs unfavorable)\n", " # CR (Complete Response) and PR (Partial Response) are considered favorable outcomes\n", " # SD (Stable Disease), PD (Progressive Disease), ND (Not Determined) are unfavorable\n", " if value in ['CR', 'PR']:\n", " return 1 # Favorable response\n", " elif value in ['SD', 'PD', 'ND']:\n", " return 0 # Unfavorable response\n", " else:\n", " return None\n", "\n", "# For age: Not available in the sample characteristics\n", "age_row = None\n", "convert_age = None\n", "\n", "# For gender: Not available in the sample characteristics\n", "gender_row = None\n", "convert_gender = None\n", "\n", "# 3. Save Metadata\n", "# trait data is available if trait_row is not None\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering using 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", "# As trait_row is not None, we proceed with clinical data extraction\n", "if trait_row is not None:\n", " # For GEO datasets, clinical data is typically extracted from the sample characteristics\n", " # observed in the previous step's output rather than from a separate file\n", " \n", " # Create a dataframe from the Sample Characteristics Dictionary provided in the previous output\n", " sample_data = {\n", " 0: ['visit: SCREENING', 'visit: BASELINE', 'visit: DAY7-14', 'visit: FCBWK4', 'visit: PROGFCB'],\n", " 1: ['molecular subgroup: GCB', 'molecular subgroup: NA', 'molecular subgroup: ABC', 'molecular subgroup: UNCLASSIFIED'],\n", " 2: ['bestresponse: PR', 'bestresponse: CR', 'bestresponse: SD', 'bestresponse: PD', 'bestresponse: ND'],\n", " 3: ['baseline tumour burden (mm2): 8877', 'baseline tumour burden (mm2): 667', 'baseline tumour burden (mm2): 2441',\n", " 'baseline tumour burden (mm2): 7700', 'baseline tumour burden (mm2): 4248', 'baseline tumour burden (mm2): 3916',\n", " 'baseline tumour burden (mm2): 4205', 'baseline tumour burden (mm2): 5056', 'baseline tumour burden (mm2): 355',\n", " 'baseline tumour burden (mm2): 7161', 'baseline tumour burden (mm2): NA', 'baseline tumour burden (mm2): 2794',\n", " 'baseline tumour burden (mm2): 792', 'baseline tumour burden (mm2): 5456', 'baseline tumour burden (mm2): 39658',\n", " 'baseline tumour burden (mm2): 1997', 'baseline tumour burden (mm2): 1133', 'baseline tumour burden (mm2): 2924',\n", " 'baseline tumour burden (mm2): 6557', 'baseline tumour burden (mm2): 1600', 'baseline tumour burden (mm2): 4371',\n", " 'baseline tumour burden (mm2): 2200', 'baseline tumour burden (mm2): 7952', 'baseline tumour burden (mm2): 6262',\n", " 'baseline tumour burden (mm2): 14354', 'baseline tumour burden (mm2): 396', 'baseline tumour burden (mm2): 2069',\n", " 'baseline tumour burden (mm2): 1022', 'baseline tumour burden (mm2): 8162', 'baseline tumour burden (mm2): 735'],\n", " 4: ['worst grade of ne: 3', 'worst grade of ne: 1', 'worst grade of ne: 2', 'worst grade of ne: 0', 'worst grade of ne: 4']\n", " }\n", " \n", " # Convert to DataFrame format suitable for geo_select_clinical_features\n", " clinical_data = pd.DataFrame.from_dict(sample_data, orient='index')\n", " \n", " # Extract clinical features using the provided function\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(\"Clinical data preview:\", preview)\n", " \n", " # Create 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", "else:\n", " print(\"Trait data not available, skipping clinical feature extraction\")\n" ] }, { "cell_type": "markdown", "id": "8a69f571", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "a4f2457d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:12.218651Z", "iopub.status.busy": "2025-03-25T07:27:12.218553Z", "iopub.status.idle": "2025-03-25T07:27:12.234285Z", "shell.execute_reply": "2025-03-25T07:27:12.234013Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Tumour immune contexture is a determinant of anti-CD19 CAR T-cell efficacy in large B cell lymphoma\"\n", "Line 1: !Series_geo_accession\t\"GSE197977\"\n", "Line 2: !Series_status\t\"Public on Sep 23 2022\"\n", "Line 3: !Series_submission_date\t\"Mar 05 2022\"\n", "Line 4: !Series_last_update_date\t\"Sep 25 2022\"\n", "Line 5: !Series_pubmed_id\t\"36038629\"\n", "Line 6: !Series_summary\t\"Axicabtagene ciloleucel (axi-cel), an anti-CD19 chimeric antigen receptor (CAR) T-cell therapy approved for treatment of relapsed/refractory large B-cell lymphoma (LBCL), has comparable efficacy across conventional LBCL markers. We analysed whether pre- and posttreatment tumour immune contexture determines clinical outcomes for axi cel–treated patients in the ZUMA-1 pivotal study. Longitudinal evaluation of the tumour microenvironment (TME) uncovered dynamic patterns that occurred rapidly after axi-cel (within 2 weeks) in responders—pronounced enhancement of T- and myeloid cell signatures and diminution of B cell signature. Clinical response and overall survival associated with high CD8+ T-cell density (Immunoscore) and immune gene expression (Immunosign21) in TME pretreatment, which was paralleled by blood CAR T-cell levels posttreatment. High density of regulatory T cells in TME pretreatment associated with reduced axi-cel–related neurologic toxicity. At relapse, the TME evolved toward an immune-detrimental contexture with decreased T-cell–related and increased counterregulatory immune signatures and B cell lineage antigens. A TME rich in T-cell attractive chemokines (CCL5, CCL22), gamma-chain receptor cytokines (IL-15, IL-7, IL-21), and interferon regulated molecules associated with T-cell infiltration and markers of activity, a result validated in 2 independent datasets totalling ≈300 LBCL samples.\"\n", "Line 7: !Series_summary\t\"These findings advance mechanistic understanding of CAR T-cell therapy and foster biomarker development and treatment optimizations.\"\n", "Line 8: !Series_overall_design\t\"71 samples were analyzed for 65 patients with screening, baseline, DAY7-14, FCBWK4 and PROGFCB time points.\"\n", "Line 9: !Series_type\t\"Expression profiling by array\"\n", "Found table marker at line 62\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM5935018\"\t\"GSM5935019\"\t\"GSM5935020\"\t\"GSM5935021\"\t\"GSM5935022\"\t\"GSM5935023\"\t\"GSM5935024\"\t\"GSM5935025\"\t\"GSM5935026\"\t\"GSM5935027\"\t\"GSM5935028\"\t\"GSM5935029\"\t\"GSM5935030\"\t\"GSM5935031\"\t\"GSM5935032\"\t\"GSM5935033\"\t\"GSM5935034\"\t\"GSM5935035\"\t\"GSM5935036\"\t\"GSM5935037\"\t\"GSM5935038\"\t\"GSM5935039\"\t\"GSM5935040\"\t\"GSM5935041\"\t\"GSM5935042\"\t\"GSM5935043\"\t\"GSM5935044\"\t\"GSM5935045\"\t\"GSM5935046\"\t\"GSM5935047\"\t\"GSM5935048\"\t\"GSM5935049\"\t\"GSM5935050\"\t\"GSM5935051\"\t\"GSM5935052\"\t\"GSM5935053\"\t\"GSM5935054\"\t\"GSM5935055\"\t\"GSM5935056\"\t\"GSM5935057\"\t\"GSM5935058\"\t\"GSM5935059\"\t\"GSM5935060\"\t\"GSM5935061\"\t\"GSM5935062\"\t\"GSM5935063\"\t\"GSM5935064\"\t\"GSM5935065\"\t\"GSM5935066\"\t\"GSM5935067\"\t\"GSM5935068\"\t\"GSM5935069\"\t\"GSM5935070\"\t\"GSM5935071\"\t\"GSM5935072\"\t\"GSM5935073\"\t\"GSM5935074\"\t\"GSM5935075\"\t\"GSM5935076\"\t\"GSM5935077\"\t\"GSM5935078\"\t\"GSM5935079\"\t\"GSM5935080\"\t\"GSM5935081\"\t\"GSM5935082\"\t\"GSM5935083\"\t\"GSM5935084\"\t\"GSM5935085\"\t\"GSM5935086\"\t\"GSM5935087\"\t\"GSM5935088\"\t\"GSM5935089\"\t\"GSM5935090\"\t\"GSM5935091\"\n", "1\t1758.44\t1370.35\t738.43\t1368.94\t1473.55\t1599.26\t1634.00\t1313.76\t2905.59\t2388.75\t4471.62\t854.05\t1785.68\t2295.62\t1131.21\t642.59\t1031.42\t228.90\t722.98\t2758.88\t563.85\t618.28\t501.65\t2211.44\t574.44\t906.56\t865.00\t465.15\t760.30\t1713.60\t1105.63\t708.19\t585.44\t1080.44\t604.52\t1215.53\t1335.56\t945.06\t1679.49\t1796.70\t1523.57\t1736.05\t1514.54\t1297.61\t1490.62\t1446.69\t2208.16\t3984.72\t786.34\t1364.53\t1598.28\t1309.58\t960.41\t10305.96\t6688.71\t8567.83\t923.32\t2386.39\t10498.13\t3595.97\t10326.69\t2327.57\t7199.84\t477.97\t989.01\t1031.16\t25270.46\t8902.58\t1765.66\t2804.63\t12446.22\t2538.75\t1196.21\t2293.09\n", "2\t249.72\t236.35\t167.63\t654.96\t59.57\t204.32\t120.19\t0.00\t216.34\t226.64\t734.27\t88.53\t83.93\t278.68\t44.18\t71.32\t32.21\t0.00\t385.19\t232.95\t45.50\t0.00\t476.40\t226.58\t84.52\t0.00\t58.97\t151.25\t0.00\t34.99\t111.33\t35.29\t268.25\t290.22\t74.65\t0.00\t0.00\t58.57\t135.39\t413.83\t198.03\t119.11\t177.82\t467.56\t35.78\t70.17\t167.00\t172.75\t59.56\t34.75\t87.12\t252.73\t0.00\t672.29\t98.77\t603.52\t0.00\t66.79\t0.00\t0.00\t263.05\t0.00\t235.61\t0.00\t0.00\t0.00\t287.00\t110.74\t0.00\t71.81\t0.00\t87.84\t25.30\t124.49\n", "3\t288.10\t513.03\t310.33\t313.61\t282.08\t229.36\t534.17\t530.56\t396.87\t406.93\t232.63\t230.08\t244.24\t284.70\t486.91\t251.78\t305.07\t319.39\t669.65\t481.89\t268.11\t236.00\t394.77\t347.15\t487.06\t292.16\t235.46\t281.78\t363.62\t453.82\t287.82\t395.17\t273.69\t193.22\t166.61\t381.74\t241.90\t668.80\t375.31\t339.29\t305.07\t223.33\t637.70\t505.65\t279.23\t239.20\t422.60\t764.35\t397.47\t368.08\t298.70\t490.13\t371.77\t549.73\t487.28\t362.33\t507.74\t410.67\t534.72\t493.63\t840.30\t240.38\t567.86\t494.07\t224.05\t318.89\t471.01\t470.88\t280.99\t623.41\t567.91\t279.40\t333.18\t471.31\n", "4\t626.42\t308.31\t1564.71\t252.45\t277.77\t1598.12\t1124.63\t931.18\t174.79\t488.05\t542.25\t894.34\t76.38\t1034.53\t729.06\t411.34\t1085.11\t1320.14\t829.65\t696.57\t1387.68\t1889.94\t75.19\t1591.34\t1445.42\t730.40\t161.86\t869.17\t2304.23\t209.96\t585.39\t350.04\t936.16\t1840.70\t2901.51\t281.28\t248.71\t925.83\t1625.51\t2344.19\t1821.51\t270.98\t1214.08\t1006.04\t2537.75\t176.69\t1522.19\t498.70\t496.55\t93.64\t449.09\t505.45\t919.10\t702.62\t467.96\t821.64\t1419.29\t348.57\t438.10\t1331.94\t290.93\t356.79\t421.08\t350.83\t168.45\t1567.88\t605.60\t500.25\t307.09\t580.45\t555.98\t443.40\t298.10\t314.97\n", "Total lines examined: 63\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 724 rows\n", "First 20 gene IDs:\n", "Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',\n", " '14', '15', '16', '17', '18', '19', '20'],\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": "2700bbbb", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "e4dc87e5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:12.235257Z", "iopub.status.busy": "2025-03-25T07:27:12.235159Z", "iopub.status.idle": "2025-03-25T07:27:12.236762Z", "shell.execute_reply": "2025-03-25T07:27:12.236506Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers in the expression data\n", "# Based on the preview, the identifiers appear to be numeric IDs (1, 2, 3, etc.) \n", "# rather than standard human gene symbols like TP53, BRCA1, etc.\n", "# These are platform-specific probe IDs that need to be mapped to gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "32c6ece2", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "a1116b28", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:12.237678Z", "iopub.status.busy": "2025-03-25T07:27:12.237583Z", "iopub.status.idle": "2025-03-25T07:27:12.295819Z", "shell.execute_reply": "2025-03-25T07:27:12.295530Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Extracting gene annotation data from SOFT file...\n", "Successfully extracted gene annotation data with 54374 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['1', '2', '3', '4', '5'], 'ORF': ['A2M', 'ABCB1', 'ABL1', 'ADA', 'AICDA'], 'Accession': ['NM_000014.4', 'NM_000927.3', 'NM_005157.3', 'NM_000022.2', 'NM_020661.1']}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'ORF', 'Accession']\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": "5a0f3b9a", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "080059b8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:12.296885Z", "iopub.status.busy": "2025-03-25T07:27:12.296786Z", "iopub.status.idle": "2025-03-25T07:27:12.423367Z", "shell.execute_reply": "2025-03-25T07:27:12.423062Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapping from ID to ORF\n", "Generated mapping dataframe with 54374 entries\n", "Mapping preview:\n", "{'ID': ['1', '2', '3', '4', '5'], 'Gene': ['A2M', 'ABCB1', 'ABL1', 'ADA', 'AICDA']}\n", "Converting probe data to gene expression data...\n", "Generated gene expression data with 721 genes and 74 samples\n", "Gene expression data preview:\n", "{'GSM5935018': [1758.44, 249.72, 288.1, 626.42, 1224.42], 'GSM5935019': [1370.35, 236.35, 513.03, 308.31, 187.35], 'GSM5935020': [738.43, 167.63, 310.33, 1564.71, 196.91], 'GSM5935021': [1368.94, 654.96, 313.61, 252.45, 750.25], 'GSM5935022': [1473.55, 59.57, 282.08, 277.77, 114.84], 'GSM5935023': [1599.26, 204.32, 229.36, 1598.12, 31.3], 'GSM5935024': [1634.0, 120.19, 534.17, 1124.63, 148.81], 'GSM5935025': [1313.76, 0.0, 530.56, 931.18, 0.0], 'GSM5935026': [2905.59, 216.34, 396.87, 174.79, 7.88], 'GSM5935027': [2388.75, 226.64, 406.93, 488.05, 0.0], 'GSM5935028': [4471.62, 734.27, 232.63, 542.25, 67.67], 'GSM5935029': [854.05, 88.53, 230.08, 894.34, 492.49], 'GSM5935030': [1785.68, 83.93, 244.24, 76.38, 1116.99], 'GSM5935031': [2295.62, 278.68, 284.7, 1034.53, 427.05], 'GSM5935032': [1131.21, 44.18, 486.91, 729.06, 27.81], 'GSM5935033': [642.59, 71.32, 251.78, 411.34, 637.54], 'GSM5935034': [1031.42, 32.21, 305.07, 1085.11, 1147.64], 'GSM5935035': [228.9, 0.0, 319.39, 1320.14, 0.0], 'GSM5935036': [722.98, 385.19, 669.65, 829.65, 0.0], 'GSM5935037': [2758.88, 232.95, 481.89, 696.57, 271.78], 'GSM5935038': [563.85, 45.5, 268.11, 1387.68, 115.37], 'GSM5935039': [618.28, 0.0, 236.0, 1889.94, 294.51], 'GSM5935040': [501.65, 476.4, 394.77, 75.19, 11.82], 'GSM5935041': [2211.44, 226.58, 347.15, 1591.34, 151.05], 'GSM5935042': [574.44, 84.52, 487.06, 1445.42, 668.99], 'GSM5935043': [906.56, 0.0, 292.16, 730.4, 2646.63], 'GSM5935044': [865.0, 58.97, 235.46, 161.86, 176.5], 'GSM5935045': [465.15, 151.25, 281.78, 869.17, 881.6], 'GSM5935046': [760.3, 0.0, 363.62, 2304.23, 58.34], 'GSM5935047': [1713.6, 34.99, 453.82, 209.96, 789.55], 'GSM5935048': [1105.63, 111.33, 287.82, 585.39, 343.74], 'GSM5935049': [708.19, 35.29, 395.17, 350.04, 174.15], 'GSM5935050': [585.44, 268.25, 273.69, 936.16, 752.19], 'GSM5935051': [1080.44, 290.22, 193.22, 1840.7, 37.07], 'GSM5935052': [604.52, 74.65, 166.61, 2901.51, 2573.76], 'GSM5935053': [1215.53, 0.0, 381.74, 281.28, 306.4], 'GSM5935054': [1335.56, 0.0, 241.9, 248.71, 149.91], 'GSM5935055': [945.06, 58.57, 668.8, 925.83, 143.38], 'GSM5935056': [1679.49, 135.39, 375.31, 1625.51, 75.41], 'GSM5935057': [1796.7, 413.83, 339.29, 2344.19, 0.0], 'GSM5935058': [1523.57, 198.03, 305.07, 1821.51, 872.4], 'GSM5935059': [1736.05, 119.11, 223.33, 270.98, 0.0], 'GSM5935060': [1514.54, 177.82, 637.7, 1214.08, 557.99], 'GSM5935061': [1297.61, 467.56, 505.65, 1006.04, 59.1], 'GSM5935062': [1490.62, 35.78, 279.23, 2537.75, 5480.86], 'GSM5935063': [1446.69, 70.17, 239.2, 176.69, 23.6], 'GSM5935064': [2208.16, 167.0, 422.6, 1522.19, 41.9], 'GSM5935065': [3984.72, 172.75, 764.35, 498.7, 0.0], 'GSM5935066': [786.34, 59.56, 397.47, 496.55, 1841.28], 'GSM5935067': [1364.53, 34.75, 368.08, 93.64, 703.76], 'GSM5935068': [1598.28, 87.12, 298.7, 449.09, 0.0], 'GSM5935069': [1309.58, 252.73, 490.13, 505.45, 0.0], 'GSM5935070': [960.41, 0.0, 371.77, 919.1, 996.55], 'GSM5935071': [10305.96, 672.29, 549.73, 702.62, 0.0], 'GSM5935072': [6688.71, 98.77, 487.28, 467.96, 0.0], 'GSM5935073': [8567.83, 603.52, 362.33, 821.64, 0.0], 'GSM5935074': [923.32, 0.0, 507.74, 1419.29, 132.3], 'GSM5935075': [2386.39, 66.79, 410.67, 348.57, 0.0], 'GSM5935076': [10498.13, 0.0, 534.72, 438.1, 0.0], 'GSM5935077': [3595.97, 0.0, 493.63, 1331.94, 439.86], 'GSM5935078': [10326.69, 263.05, 840.3, 290.93, 0.0], 'GSM5935079': [2327.57, 0.0, 240.38, 356.79, 0.0], 'GSM5935080': [7199.84, 235.61, 567.86, 421.08, 0.0], 'GSM5935081': [477.97, 0.0, 494.07, 350.83, 0.0], 'GSM5935082': [989.01, 0.0, 224.05, 168.45, 0.0], 'GSM5935083': [1031.16, 0.0, 318.89, 1567.88, 50.55], 'GSM5935084': [25270.46, 287.0, 471.01, 605.6, 0.0], 'GSM5935085': [8902.58, 110.74, 470.88, 500.25, 0.0], 'GSM5935086': [1765.66, 0.0, 280.99, 307.09, 494.44], 'GSM5935087': [2804.63, 71.81, 623.41, 580.45, 0.0], 'GSM5935088': [12446.22, 0.0, 567.91, 555.98, 0.0], 'GSM5935089': [2538.75, 87.84, 279.4, 443.4, 17.84], 'GSM5935090': [1196.21, 25.3, 333.18, 298.1, 2433.2], 'GSM5935091': [2293.09, 124.49, 471.31, 314.97, 449.17]}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE197977.csv\n" ] } ], "source": [ "# 1. Identify mapping columns\n", "# From the gene annotation preview, we can see:\n", "# - 'ID' column contains numeric identifiers (1, 2, 3...) matching the gene expression data\n", "# - 'ORF' column contains gene symbols (A2M, ABCB1, ABL1...)\n", "\n", "prob_col = 'ID' # Column with probe IDs matching gene expression data\n", "gene_col = 'ORF' # Column with gene symbols\n", "\n", "print(f\"Mapping from {prob_col} to {gene_col}\")\n", "\n", "# 2. Get gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Generated mapping dataframe with {len(mapping_df)} entries\")\n", "print(\"Mapping preview:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene expression data\n", "print(\"Converting probe data to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Generated gene expression data with {len(gene_data)} genes and {gene_data.shape[1]} samples\")\n", "\n", "# Preview the gene data (first few genes)\n", "print(\"Gene expression data preview:\")\n", "print(preview_df(gene_data))\n", "\n", "# Save the gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "df0d8a5b", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "c0f5a99b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:12.424787Z", "iopub.status.busy": "2025-03-25T07:27:12.424678Z", "iopub.status.idle": "2025-03-25T07:27:12.527850Z", "shell.execute_reply": "2025-03-25T07:27:12.527456Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "After normalization: 0 genes\n", "Normalized gene data saved to ../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE197977.csv\n", "\n", "Loading previously saved clinical data...\n", "Loaded clinical data with shape: (1, 30)\n", "\n", "Linking clinical and genetic data...\n", "Created linked data with 75 samples and 29 features\n", "\n", "Handling missing values...\n", "After handling missing values: 1 samples and 4 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 4 features\n", "\n", "Performing final validation...\n", "Abnormality detected in the cohort: GSE197977. Preprocessing failed.\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 }