{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "17a66da1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:59.007342Z", "iopub.status.busy": "2025-03-25T07:26:59.007174Z", "iopub.status.idle": "2025-03-25T07:26:59.175076Z", "shell.execute_reply": "2025-03-25T07:26:59.174719Z" } }, "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 = \"GSE173263\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Large_B-cell_Lymphoma\"\n", "in_cohort_dir = \"../../input/GEO/Large_B-cell_Lymphoma/GSE173263\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/GSE173263.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE173263.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE173263.csv\"\n", "json_path = \"../../output/preprocess/Large_B-cell_Lymphoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "2d4c2e73", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "217ba098", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:59.176545Z", "iopub.status.busy": "2025-03-25T07:26:59.176396Z", "iopub.status.idle": "2025-03-25T07:26:59.300775Z", "shell.execute_reply": "2025-03-25T07:26:59.300415Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression profile in DLBCL cases according to response to R-CHOP\"\n", "!Series_summary\t\"Gene expression profile (GEP) was analyzed in DLBCL cases to compare early failure patients (10) vs. responding patients (29), to identify features associated to primary chemoresistance\"\n", "!Series_overall_design\t\"We used frozen samples of DLBCL cases to analyze GEP in 2 groups: early failure (EF) cases (10), defined as refractory to induction treatment or early relapsing (<12 months from diagnosis); and responding patients (29). Data was then analyzed with GSEA program\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: Frozen lymph node biopsy'], 1: ['disease state: Diffuse large B-cell lymphoma (DLBCL)'], 2: ['response to r-chop: remission', 'response to r-chop: Early failure']}\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": "134646b1", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "7ed9db2d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:59.302050Z", "iopub.status.busy": "2025-03-25T07:26:59.301931Z", "iopub.status.idle": "2025-03-25T07:26:59.309046Z", "shell.execute_reply": "2025-03-25T07:26:59.308751Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical features preview:\n", "{'GSM5264464': [0.0], 'GSM5264465': [0.0], 'GSM5264466': [0.0], 'GSM5264467': [0.0], 'GSM5264468': [0.0], 'GSM5264469': [0.0], 'GSM5264470': [0.0], 'GSM5264471': [0.0], 'GSM5264472': [0.0], 'GSM5264473': [0.0], 'GSM5264474': [0.0], 'GSM5264475': [0.0], 'GSM5264476': [0.0], 'GSM5264477': [0.0], 'GSM5264478': [0.0], 'GSM5264479': [0.0], 'GSM5264480': [0.0], 'GSM5264481': [0.0], 'GSM5264482': [0.0], 'GSM5264483': [0.0], 'GSM5264484': [0.0], 'GSM5264485': [0.0], 'GSM5264486': [0.0], 'GSM5264487': [0.0], 'GSM5264488': [0.0], 'GSM5264489': [0.0], 'GSM5264490': [0.0], 'GSM5264491': [0.0], 'GSM5264492': [0.0], 'GSM5264493': [1.0], 'GSM5264494': [1.0], 'GSM5264495': [1.0], 'GSM5264496': [1.0], 'GSM5264497': [1.0], 'GSM5264498': [1.0], 'GSM5264499': [1.0], 'GSM5264500': [1.0], 'GSM5264501': [1.0], 'GSM5264502': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Large_B-cell_Lymphoma/clinical_data/GSE173263.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "is_gene_available = True # Based on the Series title and summary, this dataset contains gene expression data\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "trait_row = 2 # \"response to r-chop\" is our trait of interest (remission vs. Early failure)\n", "age_row = None # Age data is not available in the sample characteristics\n", "gender_row = None # Gender data is not available in the sample characteristics\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " if \":\" not in value:\n", " return None\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " if \"remission\" in value:\n", " return 0 # Remission as control group\n", " elif \"early failure\" in value:\n", " return 1 # Early failure as case group\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " # Not used as age data is not available\n", " return None\n", "\n", "def convert_gender(value):\n", " # Not used as gender data is not available\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", " # Extract clinical features\n", " 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 extracted clinical features\n", " preview = preview_df(clinical_df)\n", " print(\"Clinical features preview:\")\n", " print(preview)\n", " \n", " # Save the clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "881ce12d", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "966afcf0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:59.310175Z", "iopub.status.busy": "2025-03-25T07:26:59.310064Z", "iopub.status.idle": "2025-03-25T07:26:59.487984Z", "shell.execute_reply": "2025-03-25T07:26:59.487588Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Examining matrix file structure...\n", "Line 0: !Series_title\t\"Gene expression profile in DLBCL cases according to response to R-CHOP\"\n", "Line 1: !Series_geo_accession\t\"GSE173263\"\n", "Line 2: !Series_status\t\"Public on Apr 01 2022\"\n", "Line 3: !Series_submission_date\t\"Apr 25 2021\"\n", "Line 4: !Series_last_update_date\t\"Jul 01 2022\"\n", "Line 5: !Series_pubmed_id\t\"34632572\"\n", "Line 6: !Series_summary\t\"Gene expression profile (GEP) was analyzed in DLBCL cases to compare early failure patients (10) vs. responding patients (29), to identify features associated to primary chemoresistance\"\n", "Line 7: !Series_overall_design\t\"We used frozen samples of DLBCL cases to analyze GEP in 2 groups: early failure (EF) cases (10), defined as refractory to induction treatment or early relapsing (<12 months from diagnosis); and responding patients (29). Data was then analyzed with GSEA program\"\n", "Line 8: !Series_type\t\"Expression profiling by array\"\n", "Line 9: !Series_contributor\t\"Ivan,,Dlouhy\"\n", "Found table marker at line 59\n", "First few lines after marker:\n", "\"ID_REF\"\t\"GSM5264464\"\t\"GSM5264465\"\t\"GSM5264466\"\t\"GSM5264467\"\t\"GSM5264468\"\t\"GSM5264469\"\t\"GSM5264470\"\t\"GSM5264471\"\t\"GSM5264472\"\t\"GSM5264473\"\t\"GSM5264474\"\t\"GSM5264475\"\t\"GSM5264476\"\t\"GSM5264477\"\t\"GSM5264478\"\t\"GSM5264479\"\t\"GSM5264480\"\t\"GSM5264481\"\t\"GSM5264482\"\t\"GSM5264483\"\t\"GSM5264484\"\t\"GSM5264485\"\t\"GSM5264486\"\t\"GSM5264487\"\t\"GSM5264488\"\t\"GSM5264489\"\t\"GSM5264490\"\t\"GSM5264491\"\t\"GSM5264492\"\t\"GSM5264493\"\t\"GSM5264494\"\t\"GSM5264495\"\t\"GSM5264496\"\t\"GSM5264497\"\t\"GSM5264498\"\t\"GSM5264499\"\t\"GSM5264500\"\t\"GSM5264501\"\t\"GSM5264502\"\n", "\"11715100_at\"\t4.291727\t4.718726\t7.235515\t4.327459\t4.467937\t7.717062\t8.031507\t5.57264\t4.726246\t4.500532\t6.286378\t4.432202\t4.663511\t5.62615\t5.04093\t7.986747\t5.877543\t5.391604\t4.51136\t4.66978\t5.299755\t6.65944\t4.779816\t4.017673\t5.954544\t5.265401\t6.011688\t4.816669\t6.967149\t4.423441\t4.481605\t4.303993\t4.511431\t5.84295\t4.87687\t5.42312\t4.493305\t4.800495\t4.305495\n", "\"11715101_s_at\"\t5.687031\t5.625146\t8.895868\t6.256648\t6.251987\t8.947718\t8.739138\t6.996262\t5.4607\t5.637896\t8.024914\t5.910668\t5.646023\t6.294606\t7.133266\t9.168556\t6.586954\t7.196223\t5.742651\t6.196593\t6.505073\t8.474405\t6.135201\t5.582309\t7.976762\t6.750914\t7.370386\t6.007282\t9.016476\t5.662513\t5.521589\t6.38229\t6.796264\t7.305779\t6.948766\t6.729682\t4.802087\t5.797239\t5.39791\n", "\"11715102_x_at\"\t4.790138\t5.016918\t8.061741\t5.283528\t4.906362\t8.598258\t8.705472\t5.944382\t5.350894\t5.453163\t6.623911\t5.649479\t5.419546\t6.090413\t6.043232\t8.476309\t5.704782\t5.669837\t4.529309\t5.069956\t6.162913\t8.026874\t5.507476\t4.207913\t7.215802\t5.568795\t6.882721\t4.998385\t8.181197\t4.722351\t4.046119\t5.004416\t5.145731\t6.277457\t5.645314\t6.619892\t4.798683\t4.875479\t4.658356\n", "\"11715103_x_at\"\t5.612717\t5.259667\t4.577502\t4.437918\t4.376923\t4.789887\t4.372615\t5.795113\t5.033127\t4.693346\t5.967117\t4.998162\t5.088943\t5.251463\t6.331798\t4.693495\t4.94231\t4.6766\t4.929865\t5.067651\t4.876846\t5.757492\t4.813636\t5.462179\t5.136568\t4.576532\t5.051248\t4.738405\t5.048113\t5.524447\t4.818738\t5.492333\t5.807936\t5.022351\t5.862017\t5.235055\t4.776998\t4.835998\t5.240987\n", "Total lines examined: 60\n", "\n", "Attempting to extract gene data from matrix file...\n", "Successfully extracted gene data with 49193 rows\n", "First 20 gene IDs:\n", "Index(['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at',\n", " '11715104_s_at', '11715105_at', '11715106_x_at', '11715107_s_at',\n", " '11715108_x_at', '11715109_at', '11715110_at', '11715111_s_at',\n", " '11715112_at', '11715113_x_at', '11715114_x_at', '11715115_s_at',\n", " '11715116_s_at', '11715117_x_at', '11715118_s_at', '11715119_s_at'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data available: True\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Add diagnostic code to check file content and structure\n", "print(\"Examining matrix file structure...\")\n", "with gzip.open(matrix_file, 'rt') as file:\n", " table_marker_found = False\n", " lines_read = 0\n", " for i, line in enumerate(file):\n", " lines_read += 1\n", " if '!series_matrix_table_begin' in line:\n", " table_marker_found = True\n", " print(f\"Found table marker at line {i}\")\n", " # Read a few lines after the marker to check data structure\n", " next_lines = [next(file, \"\").strip() for _ in range(5)]\n", " print(\"First few lines after marker:\")\n", " for next_line in next_lines:\n", " print(next_line)\n", " break\n", " if i < 10: # Print first few lines to see file structure\n", " print(f\"Line {i}: {line.strip()}\")\n", " if i > 100: # Don't read the entire file\n", " break\n", " \n", " if not table_marker_found:\n", " print(\"Table marker '!series_matrix_table_begin' not found in first 100 lines\")\n", " print(f\"Total lines examined: {lines_read}\")\n", "\n", "# 2. Try extracting gene expression data from the matrix file again with better diagnostics\n", "try:\n", " print(\"\\nAttempting to extract gene data from matrix file...\")\n", " gene_data = get_genetic_data(matrix_file)\n", " if gene_data.empty:\n", " print(\"Extracted gene expression data is empty\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Successfully extracted gene data with {len(gene_data.index)} rows\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {str(e)}\")\n", " print(\"This dataset appears to have an empty or malformed gene expression matrix\")\n", " is_gene_available = False\n", "\n", "print(f\"\\nGene expression data available: {is_gene_available}\")\n", "\n", "# If data extraction failed, try an alternative approach using pandas directly\n", "if not is_gene_available:\n", " print(\"\\nTrying alternative approach to read gene expression data...\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Skip lines until we find the marker\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Try to read the data directly with pandas\n", " gene_data = pd.read_csv(file, sep='\\t', index_col=0)\n", " \n", " if not gene_data.empty:\n", " print(f\"Successfully extracted gene data with alternative method: {gene_data.shape}\")\n", " print(\"First 20 gene IDs:\")\n", " print(gene_data.index[:20])\n", " is_gene_available = True\n", " else:\n", " print(\"Alternative extraction method also produced empty data\")\n", " except Exception as e:\n", " print(f\"Alternative extraction failed: {str(e)}\")\n" ] }, { "cell_type": "markdown", "id": "409a12cd", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "ee7580a2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:59.489226Z", "iopub.status.busy": "2025-03-25T07:26:59.489112Z", "iopub.status.idle": "2025-03-25T07:26:59.491009Z", "shell.execute_reply": "2025-03-25T07:26:59.490728Z" } }, "outputs": [], "source": [ "# Examine the gene identifiers\n", "# The IDs follow a format like \"11715100_at\", \"11715101_s_at\", etc.\n", "# These appear to be Affymetrix probe IDs, not human gene symbols\n", "# The \"_at\", \"_s_at\", and \"_x_at\" suffixes are typical for Affymetrix arrays\n", "# These will need to be mapped to standard gene symbols for analysis\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "80482fd7", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "ffe92652", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:26:59.492116Z", "iopub.status.busy": "2025-03-25T07:26:59.491996Z", "iopub.status.idle": "2025-03-25T07:27:05.188612Z", "shell.execute_reply": "2025-03-25T07:27:05.188215Z" } }, "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 1967952 rows\n", "\n", "Gene annotation preview (first few rows):\n", "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'GeneChip Array': ['Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array', 'Human Genome HG-U219 Array'], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['20-Aug-10', '20-Aug-10', '20-Aug-10', '20-Aug-10', '20-Aug-10'], 'Sequence Type': ['Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence', 'Consensus sequence'], 'Sequence Source': ['Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database', 'Affymetrix Proprietary Database'], 'Transcript ID(Array Design)': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Target Description': ['g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g21264570 /TID=g21264570 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g21264570 /REP_ORG=Homo sapiens', 'g22748780 /TID=g22748780 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g22748780 /REP_ORG=Homo sapiens', 'g30039713 /TID=g30039713 /CNT=1 /FEA=FLmRNA /TIER=FL /STK=0 /DEF=g30039713 /REP_ORG=Homo sapiens'], 'Representative Public ID': ['g21264570', 'g21264570', 'g21264570', 'g22748780', 'g30039713'], 'Archival UniGene Cluster': ['---', '---', '---', '---', '---'], 'UniGene ID': ['Hs.247813', 'Hs.247813', 'Hs.247813', 'Hs.465643', 'Hs.352515'], 'Genome Version': ['February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)', 'February 2009 (Genome Reference Consortium GRCh37)'], 'Alignments': ['chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr6:26271145-26271612 (-) // 100.0 // p22.2', 'chr19:4639529-5145579 (+) // 48.53 // p13.3', 'chr17:72920369-72929640 (+) // 100.0 // q25.1'], 'Gene Title': ['histone cluster 1, H3g', 'histone cluster 1, H3g', 'histone cluster 1, H3g', 'tumor necrosis factor, alpha-induced protein 8-like 1', 'otopetrin 2'], 'Gene Symbol': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2'], 'Chromosomal Location': ['chr6p21.3', 'chr6p21.3', 'chr6p21.3', 'chr19p13.3', 'chr17q25.1'], 'GB_LIST': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942,NM_152362', 'NM_178160'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Unigene Cluster Type': ['full length', 'full length', 'full length', 'full length', 'full length'], 'Ensembl': ['---', 'ENSG00000178458', '---', 'ENSG00000185361', 'ENSG00000183034'], 'Entrez Gene': ['8355', '8355', '8355', '126282', '92736'], 'SwissProt': ['P68431', 'P68431', 'P68431', 'Q8WVP5', 'Q7RTS6'], 'EC': ['---', '---', '---', '---', '---'], 'OMIM': ['602815', '602815', '602815', '---', '607827'], 'RefSeq Protein ID': ['NP_003525', 'NP_003525', 'NP_003525', 'NP_001161414 /// NP_689575', 'NP_835454'], 'RefSeq Transcript ID': ['NM_003534', 'NM_003534', 'NM_003534', 'NM_001167942 /// NM_152362', 'NM_178160'], 'FlyBase': ['---', '---', '---', '---', '---'], 'AGI': ['---', '---', '---', '---', '---'], 'WormBase': ['---', '---', '---', '---', '---'], 'MGI Name': ['---', '---', '---', '---', '---'], 'RGD Name': ['---', '---', '---', '---', '---'], 'SGD accession number': ['---', '---', '---', '---', '---'], 'Gene Ontology Biological Process': ['0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation', '0006334 // nucleosome assembly // inferred from electronic annotation', '---', '---'], 'Gene Ontology Cellular Component': ['0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '0000786 // nucleosome // inferred from electronic annotation /// 0005634 // nucleus // inferred from electronic annotation /// 0005694 // chromosome // inferred from electronic annotation', '---', '0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation'], 'Gene Ontology Molecular Function': ['0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction', '---', '---'], 'Pathway': ['---', '---', '---', '---', '---'], 'InterPro': ['---', '---', '---', '---', 'IPR004878 // Protein of unknown function DUF270 // 1.0E-6 /// IPR004878 // Protein of unknown function DUF270 // 1.0E-13'], 'Trans Membrane': ['---', '---', '---', '---', 'NP_835454.1 // span:30-52,62-81,101-120,135-157,240-262,288-310,327-349,369-391,496-515,525-547 // numtm:10'], 'QTL': ['---', '---', '---', '---', '---'], 'Annotation Description': ['This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 1 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 2 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 1 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 5 transcripts. // false // Matching Probes // A', 'This probe set was annotated using the Matching Probes based pipeline to a Entrez Gene identifier using 3 transcripts. // false // Matching Probes // A'], 'Annotation Transcript Cluster': ['NM_003534(11)', 'BC079835(11),NM_003534(11)', 'NM_003534(11)', 'BC017672(11),BC044250(9),ENST00000327473(11),NM_001167942(11),NM_152362(11)', 'ENST00000331427(11),ENST00000426069(11),NM_178160(11)'], 'Transcript Assignments': ['NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'BC079835 // Homo sapiens histone cluster 1, H3g, mRNA (cDNA clone IMAGE:5935692). // gb_htc // 11 // --- /// ENST00000321285 // cdna:known chromosome:GRCh37:6:26271202:26271612:-1 gene:ENSG00000178458 // ensembl // 11 // --- /// GENSCAN00000044911 // cdna:Genscan chromosome:GRCh37:6:26271202:26271612:-1 // ensembl // 11 // --- /// NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'NM_003534 // Homo sapiens histone cluster 1, H3g (HIST1H3G), mRNA. // refseq // 11 // ---', 'BC017672 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone MGC:17791 IMAGE:3885999), complete cds. // gb // 11 // --- /// BC044250 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1, mRNA (cDNA clone IMAGE:5784807). // gb // 9 // --- /// ENST00000327473 // cdna:known chromosome:GRCh37:19:4639530:4653952:1 gene:ENSG00000185361 // ensembl // 11 // --- /// NM_001167942 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 1, mRNA. // refseq // 11 // --- /// NM_152362 // Homo sapiens tumor necrosis factor, alpha-induced protein 8-like 1 (TNFAIP8L1), transcript variant 2, mRNA. // refseq // 11 // ---', 'ENST00000331427 // cdna:known chromosome:GRCh37:17:72920370:72929640:1 gene:ENSG00000183034 // ensembl // 11 // --- /// ENST00000426069 // cdna:known chromosome:GRCh37:17:72920370:72929640:1 gene:ENSG00000183034 // ensembl // 11 // --- /// NM_178160 // Homo sapiens otopetrin 2 (OTOP2), mRNA. // refseq // 11 // ---'], 'Annotation Notes': ['BC079835 // gb_htc // 6 // Cross Hyb Matching Probes', '---', 'GENSCAN00000044911 // ensembl // 4 // Cross Hyb Matching Probes /// ENST00000321285 // ensembl // 4 // Cross Hyb Matching Probes /// BC079835 // gb_htc // 7 // Cross Hyb Matching Probes', '---', 'GENSCAN00000031612 // ensembl // 8 // Cross Hyb Matching Probes']}\n", "\n", "Column names in gene annotation data:\n", "['ID', 'GeneChip Array', 'Species Scientific Name', 'Annotation Date', 'Sequence Type', 'Sequence Source', 'Transcript ID(Array Design)', 'Target Description', 'Representative Public ID', 'Archival UniGene Cluster', 'UniGene ID', 'Genome Version', 'Alignments', 'Gene Title', 'Gene Symbol', 'Chromosomal Location', 'GB_LIST', 'SPOT_ID', 'Unigene Cluster Type', 'Ensembl', 'Entrez Gene', 'SwissProt', 'EC', 'OMIM', 'RefSeq Protein ID', 'RefSeq Transcript ID', 'FlyBase', 'AGI', 'WormBase', 'MGI Name', 'RGD Name', 'SGD accession number', 'Gene Ontology Biological Process', 'Gene Ontology Cellular Component', 'Gene Ontology Molecular Function', 'Pathway', 'InterPro', 'Trans Membrane', 'QTL', 'Annotation Description', 'Annotation Transcript Cluster', 'Transcript Assignments', 'Annotation Notes']\n", "\n", "The dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\n", "Example SPOT_ID format: nan\n" ] } ], "source": [ "# 1. Extract gene annotation data from the SOFT file\n", "print(\"Extracting gene annotation data from SOFT file...\")\n", "try:\n", " # Use the library function to extract gene annotation\n", " gene_annotation = get_gene_annotation(soft_file)\n", " print(f\"Successfully extracted gene annotation data with {len(gene_annotation.index)} rows\")\n", " \n", " # Preview the annotation DataFrame\n", " print(\"\\nGene annotation preview (first few rows):\")\n", " print(preview_df(gene_annotation))\n", " \n", " # Show column names to help identify which columns we need for mapping\n", " print(\"\\nColumn names in gene annotation data:\")\n", " print(gene_annotation.columns.tolist())\n", " \n", " # Check for relevant mapping columns\n", " if 'GB_ACC' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains GenBank accessions (GB_ACC) that could be used for gene mapping.\")\n", " # Count non-null values in GB_ACC column\n", " non_null_count = gene_annotation['GB_ACC'].count()\n", " print(f\"Number of rows with GenBank accessions: {non_null_count} out of {len(gene_annotation)}\")\n", " \n", " if 'SPOT_ID' in gene_annotation.columns:\n", " print(\"\\nThe dataset contains genomic regions (SPOT_ID) that could be used for location-based gene mapping.\")\n", " print(\"Example SPOT_ID format:\", gene_annotation['SPOT_ID'].iloc[0])\n", " \n", "except Exception as e:\n", " print(f\"Error processing gene annotation data: {e}\")\n", " is_gene_available = False\n" ] }, { "cell_type": "markdown", "id": "fe011367", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "a6bbcef4", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:05.189874Z", "iopub.status.busy": "2025-03-25T07:27:05.189750Z", "iopub.status.idle": "2025-03-25T07:27:05.862956Z", "shell.execute_reply": "2025-03-25T07:27:05.862598Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapping Affymetrix probe IDs to human gene symbols...\n", "Created mapping between 49384 probes and gene symbols\n", "First few rows of mapping data:\n", "{'ID': ['11715100_at', '11715101_s_at', '11715102_x_at', '11715103_x_at', '11715104_s_at'], 'Gene': ['HIST1H3G', 'HIST1H3G', 'HIST1H3G', 'TNFAIP8L1', 'OTOP2']}\n", "Converting probe-level measurements to gene expression data...\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Successfully converted to gene expression data with 19521 genes and 39 samples\n", "First few rows of gene expression data:\n", "{'GSM5264464': [6.408868, 8.506178, 41.900052, 6.349136, 10.87007], 'GSM5264465': [5.919338, 8.798117000000001, 41.460929, 5.356535, 10.3921], 'GSM5264466': [7.570321, 9.305402, 44.119149, 7.278757, 8.402752], 'GSM5264467': [6.092886, 8.964243, 42.475441, 5.828587, 9.705988], 'GSM5264468': [6.740193, 8.67219, 41.202211, 6.312686, 8.841656], 'GSM5264469': [8.684087, 9.200528, 44.634918, 6.898893, 8.51055], 'GSM5264470': [8.439163, 8.72709, 45.164675, 6.77206, 8.774792], 'GSM5264471': [7.746153, 9.36621, 41.89748, 5.936729, 10.66011], 'GSM5264472': [7.088106, 8.873732, 40.881253, 6.329117, 10.44842], 'GSM5264473': [6.40157, 8.719936, 42.478854, 6.974187, 9.601769], 'GSM5264474': [6.455291, 9.706564, 44.217554, 5.618299, 9.159767], 'GSM5264475': [5.635584, 8.32609, 40.963491, 5.865566, 9.813807], 'GSM5264476': [5.961028, 8.43795, 41.006274, 5.796535, 10.68841], 'GSM5264477': [6.977757, 8.703751, 44.806364, 5.450151, 8.824014], 'GSM5264478': [5.935488, 9.005569000000001, 42.511369, 5.906432, 9.477322], 'GSM5264479': [8.350842, 8.494038, 45.363502000000004, 6.501207, 8.682076], 'GSM5264480': [6.995729, 8.65923, 43.714027, 6.373056, 8.800717], 'GSM5264481': [5.794306, 9.613979, 41.800992, 4.625438, 10.04286], 'GSM5264482': [6.485361, 9.720749999999999, 43.795688, 7.506864, 8.423845], 'GSM5264483': [6.435453, 8.846737000000001, 40.563598999999996, 7.127924, 9.242199], 'GSM5264484': [5.48402, 8.087869, 43.647736, 6.254548, 10.89347], 'GSM5264485': [6.739435, 9.844536000000002, 41.433908, 7.184268, 8.793245], 'GSM5264486': [6.274942, 8.639533, 41.206238, 6.506873, 8.94809], 'GSM5264487': [6.133811, 9.723585, 43.720143, 6.921263, 9.629697], 'GSM5264488': [7.873077, 9.247620000000001, 44.667143, 5.681305, 8.180505], 'GSM5264489': [6.489068, 8.909372999999999, 42.187008, 7.139433, 9.658603], 'GSM5264490': [6.194496, 8.466754, 41.912246, 5.882005, 10.43443], 'GSM5264491': [6.37659, 9.14765, 43.667999, 6.58306, 9.454481], 'GSM5264492': [8.121503, 8.90276, 42.746238000000005, 6.124331, 8.465906], 'GSM5264493': [6.266032, 8.87412, 42.700896, 5.986791, 9.814548], 'GSM5264494': [6.415974, 8.88894, 42.780238, 5.190533, 9.80016], 'GSM5264495': [5.76653, 8.207986, 41.318959, 5.770037, 10.74837], 'GSM5264496': [7.376324, 8.853219, 42.031074000000004, 7.374891, 10.13967], 'GSM5264497': [8.099615, 9.136363, 44.363098, 6.53746, 9.372625], 'GSM5264498': [6.723533, 8.840271999999999, 40.746106, 5.784334, 10.6329], 'GSM5264499': [6.083179, 9.114562, 41.189991, 5.11651, 9.946463], 'GSM5264500': [4.975891, 8.565532, 41.03191, 5.642205, 11.26318], 'GSM5264501': [6.426256, 9.877515, 42.921614, 6.281567, 10.21856], 'GSM5264502': [6.321749, 8.964028, 42.674835, 5.295458, 10.76785]}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE173263.csv\n" ] } ], "source": [ "# Examining the gene annotation and expression data from previous steps\n", "# The gene identifiers in gene_data are in the 'ID' column of gene_annotation\n", "# The gene symbols are in the 'Gene Symbol' column of gene_annotation\n", "\n", "# 1. Identify the mapping columns\n", "print(\"Mapping Affymetrix probe IDs to human gene symbols...\")\n", "prob_col = 'ID' # The column in gene_annotation containing probe IDs\n", "gene_col = 'Gene Symbol' # The column containing gene symbols\n", "\n", "# 2. Create the gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Created mapping between {len(mapping_df)} probes and gene symbols\")\n", "print(\"First few rows of mapping data:\")\n", "print(preview_df(mapping_df))\n", "\n", "# 3. Apply the gene mapping to convert probe-level data to gene-level data\n", "print(\"Converting probe-level measurements to gene expression data...\")\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Successfully converted to gene expression data with {len(gene_data)} genes and {gene_data.shape[1]} samples\")\n", "\n", "# Preview the gene expression data\n", "print(\"First few rows of gene expression data:\")\n", "print(preview_df(gene_data))\n", "\n", "# Save the gene expression data to CSV\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": "984de4cc", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "1d7c2b86", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:27:05.864369Z", "iopub.status.busy": "2025-03-25T07:27:05.864244Z", "iopub.status.idle": "2025-03-25T07:27:06.431491Z", "shell.execute_reply": "2025-03-25T07:27:06.431129Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Normalizing gene symbols...\n", "Loading gene data from previous step...\n", "Gene data shape before normalization: (19521, 39)\n", "Sample of gene symbols before normalization: ['A1BG', 'A1CF', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1']\n", "After normalization: 19298 genes\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Large_B-cell_Lymphoma/gene_data/GSE173263.csv\n", "\n", "Loading clinical data...\n", "Loaded clinical data with shape: (1, 39)\n", "Clinical data columns: ['GSM5264464', 'GSM5264465', 'GSM5264466', 'GSM5264467', 'GSM5264468', 'GSM5264469', 'GSM5264470', 'GSM5264471', 'GSM5264472', 'GSM5264473', 'GSM5264474', 'GSM5264475', 'GSM5264476', 'GSM5264477', 'GSM5264478', 'GSM5264479', 'GSM5264480', 'GSM5264481', 'GSM5264482', 'GSM5264483', 'GSM5264484', 'GSM5264485', 'GSM5264486', 'GSM5264487', 'GSM5264488', 'GSM5264489', 'GSM5264490', 'GSM5264491', 'GSM5264492', 'GSM5264493', 'GSM5264494', 'GSM5264495', 'GSM5264496', 'GSM5264497', 'GSM5264498', 'GSM5264499', 'GSM5264500', 'GSM5264501', 'GSM5264502']\n", "\n", "Linking clinical and genetic data...\n", "Clinical data shape after adjustment: (39, 1)\n", "Linked data shape: (40, 19337)\n", "Linked data columns: ['GSM5264464', 'GSM5264465', 'GSM5264466', 'GSM5264467', 'GSM5264468']\n", "Using trait column: GSM5264464\n", "\n", "Handling missing values...\n", "Data shape after handling missing values: (1, 39)\n", "\n", "Checking for biased features...\n", "Quartiles for 'GSM5264464':\n", " 25%: 0.0\n", " 50% (Median): 0.0\n", " 75%: 0.0\n", "Min: 0.0\n", "Max: 0.0\n", "The distribution of the feature 'GSM5264464' in this dataset is severely biased.\n", "\n", "\n", "Performing final validation...\n", "\n", "Data not saved as it was determined to be unusable\n", "\n", "Dataset usability for Large_B-cell_Lymphoma association studies: False\n", "Note: The distribution of the trait in this dataset is severely biased.\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 if needed\n", "try:\n", " # First, check if we need to reload the gene data\n", " gene_data_path = out_gene_data_file # Use the correct variable from setup\n", " if os.path.exists(gene_data_path):\n", " print(\"Loading gene data from previous step...\")\n", " gene_data = pd.read_csv(gene_data_path, index_col=0)\n", " else:\n", " print(\"Gene data not found, using the gene_data from previous processing...\")\n", " \n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " print(\"Sample of gene symbols before normalization:\", gene_data.index[:10].tolist())\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", " # Handle case where normalization results in 0 genes\n", " if len(normalized_gene_data.index) == 0:\n", " print(\"WARNING: Normalization resulted in 0 genes. Using original gene data.\")\n", " normalized_gene_data = gene_data # Use original data\n", " is_gene_available = False # Mark that normalization failed\n", " else:\n", " is_gene_available = True\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", "except Exception as e:\n", " print(f\"Error in gene normalization: {str(e)}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data\n", "print(\"\\nLoading clinical data...\")\n", "try:\n", " if os.path.exists(out_clinical_data_file):\n", " clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n", " print(f\"Clinical data columns: {clinical_df.columns.tolist()}\")\n", " is_trait_available = True\n", " else:\n", " print(\"Clinical data file not found.\")\n", " is_trait_available = False\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {str(e)}\")\n", " is_trait_available = False\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_gene_available and is_trait_available:\n", " print(\"\\nLinking clinical and genetic data...\")\n", " try:\n", " # Ensure clinical data has a proper DataFrame structure\n", " if clinical_df.shape[0] == 1: # If it's a single row (trait)\n", " clinical_df = clinical_df.T # Transpose if needed\n", " \n", " print(f\"Clinical data shape after adjustment: {clinical_df.shape}\")\n", " \n", " # Link clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)\n", " print(f\"Linked data shape: {linked_data.shape}\")\n", " print(f\"Linked data columns: {linked_data.columns[:5].tolist()}\") # Show first few columns\n", " \n", " # Identify the trait column name (should be the first column in clinical_df)\n", " trait_col = clinical_df.index[0] # Get the trait name from the index\n", " print(f\"Using trait column: {trait_col}\")\n", " \n", " # 4. Handle missing values in the linked data\n", " print(\"\\nHandling missing values...\")\n", " linked_data = handle_missing_values(linked_data, trait_col)\n", " print(f\"Data shape after handling missing values: {linked_data.shape}\")\n", " \n", " # 5. Check for biased features\n", " print(\"\\nChecking for biased features...\")\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait_col)\n", " \n", " except Exception as e:\n", " print(f\"Error in data linking or processing: {str(e)}\")\n", " import traceback\n", " traceback.print_exc()\n", " is_trait_available = False\n", " is_biased = True\n", " linked_data = pd.DataFrame() # Empty DataFrame as placeholder\n", "else:\n", " print(\"\\nCannot link data: either gene data or clinical data is unavailable\")\n", " is_biased = True\n", " linked_data = pd.DataFrame() # Empty DataFrame as placeholder\n", "\n", "# 6. Validate and save cohort information\n", "print(\"\\nPerforming final validation...\")\n", "note = \"\"\n", "if not is_gene_available:\n", " note = \"Gene expression data normalization failed.\"\n", "elif not is_trait_available:\n", " note = \"Clinical trait data is not available or could not be loaded.\"\n", "elif is_biased:\n", " note = \"The distribution of the trait in this dataset is severely biased.\"\n", "else:\n", " note = \"Dataset contains usable gene expression data and treatment response information for DLBCL patients.\"\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 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 to {out_data_file}\")\n", "else:\n", " print(f\"\\nData not saved as it was determined to be unusable\")\n", "\n", "# 8. Report final status\n", "print(f\"\\nDataset usability for {trait} association studies: {is_usable}\")\n", "if note:\n", " print(f\"Note: {note}\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.10.16" } }, "nbformat": 4, "nbformat_minor": 5 }