{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "13777e84", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:28.896800Z", "iopub.status.busy": "2025-03-25T07:00:28.896580Z", "iopub.status.idle": "2025-03-25T07:00:29.064366Z", "shell.execute_reply": "2025-03-25T07:00:29.063996Z" } }, "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 = \"Breast_Cancer\"\n", "cohort = \"GSE207847\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Breast_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Breast_Cancer/GSE207847\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Breast_Cancer/GSE207847.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Breast_Cancer/gene_data/GSE207847.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Breast_Cancer/clinical_data/GSE207847.csv\"\n", "json_path = \"../../output/preprocess/Breast_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "ec5cd27d", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "78f36e16", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:29.065863Z", "iopub.status.busy": "2025-03-25T07:00:29.065712Z", "iopub.status.idle": "2025-03-25T07:00:29.331471Z", "shell.execute_reply": "2025-03-25T07:00:29.330731Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Gene expression profile of luminal breast cancer samples from FFPE sample of primary luminal breast cancer from patient who had a loco-regional recurrence [cohort A]\"\n", "!Series_summary\t\"We aimed at finding a gene signature able to discriminate patients who had a loco-regional recurrence either at early time after surgery or late (< 2 yrs, early; >2 and <5 yrs, intermediate; < 5 yrs, late)\"\n", "!Series_overall_design\t\"We performed gene expression profile using Clariom D platform from FFPE sample of primary luminal breast cancer from patient who had a loco-regional recurrence at different time after surgery (cohort A)\"\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: luminal breast cancer'], 1: ['gender: female'], 2: ['tissue: primary luminal breast cancer'], 3: ['loco-regional recurrence: LATE', 'loco-regional recurrence: EARLY', 'loco-regional recurrence: INTERMEDIATE']}\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": "31cbfe76", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "904dc956", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:29.332818Z", "iopub.status.busy": "2025-03-25T07:00:29.332705Z", "iopub.status.idle": "2025-03-25T07:00:29.344744Z", "shell.execute_reply": "2025-03-25T07:00:29.344439Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical data: {'GSM6321013': [0.0, 0.0], 'GSM6321014': [1.0, 0.0], 'GSM6321015': [2.0, 0.0], 'GSM6321016': [2.0, 0.0], 'GSM6321017': [0.0, 0.0], 'GSM6321018': [0.0, 0.0], 'GSM6321019': [1.0, 0.0], 'GSM6321020': [0.0, 0.0], 'GSM6321021': [1.0, 0.0], 'GSM6321022': [1.0, 0.0], 'GSM6321023': [1.0, 0.0], 'GSM6321024': [0.0, 0.0], 'GSM6321025': [2.0, 0.0], 'GSM6321026': [1.0, 0.0], 'GSM6321027': [0.0, 0.0], 'GSM6321028': [2.0, 0.0], 'GSM6321029': [1.0, 0.0], 'GSM6321030': [0.0, 0.0], 'GSM6321031': [2.0, 0.0], 'GSM6321032': [0.0, 0.0], 'GSM6321033': [2.0, 0.0], 'GSM6321034': [2.0, 0.0], 'GSM6321035': [0.0, 0.0], 'GSM6321036': [1.0, 0.0], 'GSM6321037': [2.0, 0.0], 'GSM6321038': [2.0, 0.0], 'GSM6321039': [0.0, 0.0], 'GSM6321040': [2.0, 0.0], 'GSM6321041': [0.0, 0.0], 'GSM6321042': [0.0, 0.0], 'GSM6321043': [2.0, 0.0], 'GSM6321044': [0.0, 0.0], 'GSM6321045': [0.0, 0.0], 'GSM6321046': [2.0, 0.0], 'GSM6321047': [2.0, 0.0], 'GSM6321048': [1.0, 0.0], 'GSM6321049': [2.0, 0.0], 'GSM6321050': [1.0, 0.0], 'GSM6321051': [0.0, 0.0], 'GSM6321052': [0.0, 0.0], 'GSM6321053': [2.0, 0.0], 'GSM6321054': [2.0, 0.0], 'GSM6321055': [1.0, 0.0], 'GSM6321056': [0.0, 0.0], 'GSM6321057': [0.0, 0.0], 'GSM6321058': [1.0, 0.0], 'GSM6321059': [1.0, 0.0], 'GSM6321060': [2.0, 0.0], 'GSM6321061': [2.0, 0.0], 'GSM6321062': [1.0, 0.0], 'GSM6321063': [0.0, 0.0], 'GSM6321064': [0.0, 0.0], 'GSM6321065': [1.0, 0.0], 'GSM6321066': [2.0, 0.0], 'GSM6321067': [1.0, 0.0], 'GSM6321068': [0.0, 0.0], 'GSM6321069': [0.0, 0.0], 'GSM6321070': [0.0, 0.0], 'GSM6321071': [0.0, 0.0], 'GSM6321072': [1.0, 0.0]}\n", "Clinical data saved to ../../output/preprocess/Breast_Cancer/clinical_data/GSE207847.csv\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this is a gene expression profile study using the Clariom D platform\n", "# So this dataset is likely to contain gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# Trait: The trait here refers to breast cancer, but specifically we are looking at the timing of \n", "# loco-regional recurrence which is in key 3\n", "trait_row = 3 # loco-regional recurrence (EARLY, INTERMEDIATE, LATE)\n", "\n", "# Age: There is no information about age in the sample characteristics\n", "age_row = None\n", "\n", "# Gender: Gender information is available in key 1\n", "gender_row = 1 # gender: female\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert loco-regional recurrence data to binary format.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"EARLY\" in value.upper():\n", " return 1 # Early recurrence (< 2 years)\n", " elif \"LATE\" in value.upper():\n", " return 0 # Late recurrence (> 5 years)\n", " elif \"INTERMEDIATE\" in value.upper():\n", " return 2 # Intermediate recurrence (2-5 years)\n", " else:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender data to binary format.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip().lower()\n", " \n", " if \"female\" in value:\n", " return 0\n", " elif \"male\" in value:\n", " return 1\n", " else:\n", " return None\n", "\n", "# Age function is not needed as age data is not available, but we'll define it for completeness\n", "def convert_age(value):\n", " \"\"\"Convert age data to continuous format.\"\"\"\n", " if not isinstance(value, str):\n", " return None\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Check if trait data is available\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", "# Process clinical data if trait_row is not None\n", "if trait_row is not None:\n", " try:\n", " # Assuming clinical_data is a variable that contains the sample characteristics\n", " # from a previous step rather than a file to be loaded\n", " clinical_data_path = os.path.join(in_cohort_dir, \"clinical_data.txt\")\n", " \n", " # Check if the variable clinical_data exists in the global namespace\n", " if 'clinical_data' in globals():\n", " # Extract clinical features\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 if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " # Preview the data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of clinical data:\", preview)\n", " \n", " # Save to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\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(\"Clinical data variable not found. Skipping clinical feature extraction.\")\n", " except Exception as e:\n", " print(f\"Error processing clinical data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "f8f76ece", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "270ec361", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:29.345866Z", "iopub.status.busy": "2025-03-25T07:00:29.345757Z", "iopub.status.idle": "2025-03-25T07:00:29.777641Z", "shell.execute_reply": "2025-03-25T07:00:29.777247Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Breast_Cancer/GSE207847/GSE207847_family.soft.gz\n", "Matrix file: ../../input/GEO/Breast_Cancer/GSE207847/GSE207847_series_matrix.txt.gz\n", "Found the matrix table marker at line 58\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (135750, 60)\n", "First 20 gene/probe identifiers:\n", "['TC0100006432.hg.1', 'TC0100006433.hg.1', 'TC0100006434.hg.1', 'TC0100006435.hg.1', 'TC0100006436.hg.1', 'TC0100006437.hg.1', 'TC0100006438.hg.1', 'TC0100006439.hg.1', 'TC0100006440.hg.1', 'TC0100006441.hg.1', 'TC0100006442.hg.1', 'TC0100006443.hg.1', 'TC0100006444.hg.1', 'TC0100006445.hg.1', 'TC0100006446.hg.1', 'TC0100006447.hg.1', 'TC0100006448.hg.1', 'TC0100006449.hg.1', 'TC0100006450.hg.1', 'TC0100006451.hg.1']\n" ] } ], "source": [ "# 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", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "marker_row = None\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " marker_row = i\n", " print(f\"Found the matrix table marker at line {i}\")\n", " break\n", " \n", " if not found_marker:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " is_gene_available = False\n", " \n", " # If marker was found, try to extract gene data\n", " if is_gene_available:\n", " try:\n", " # Try using the library function\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " except Exception as e:\n", " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n", " is_gene_available = False\n", " \n", " # If gene data extraction failed, examine file content to diagnose\n", " if not is_gene_available:\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Print lines around the marker if found\n", " if marker_row is not None:\n", " for i, line in enumerate(file):\n", " if i >= marker_row - 2 and i <= marker_row + 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " if i > marker_row + 10:\n", " break\n", " else:\n", " # If marker not found, print first 10 lines\n", " for i, line in enumerate(file):\n", " if i < 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing file: {e}\")\n", " is_gene_available = False\n", "\n", "# Update validation information if gene data extraction failed\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n", " # Update the validation record since gene data isn't available\n", " is_trait_available = False # We already determined trait data isn't available in step 2\n", " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n", " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n" ] }, { "cell_type": "markdown", "id": "71f6833e", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "2559ef36", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:29.778941Z", "iopub.status.busy": "2025-03-25T07:00:29.778812Z", "iopub.status.idle": "2025-03-25T07:00:29.781145Z", "shell.execute_reply": "2025-03-25T07:00:29.780841Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers\n", "gene_ids = ['TC0100006432.hg.1', 'TC0100006433.hg.1', 'TC0100006434.hg.1', 'TC0100006435.hg.1', 'TC0100006436.hg.1', \n", " 'TC0100006437.hg.1', 'TC0100006438.hg.1', 'TC0100006439.hg.1', 'TC0100006440.hg.1', 'TC0100006441.hg.1', \n", " 'TC0100006442.hg.1', 'TC0100006443.hg.1', 'TC0100006444.hg.1', 'TC0100006445.hg.1', 'TC0100006446.hg.1', \n", " 'TC0100006447.hg.1', 'TC0100006448.hg.1', 'TC0100006449.hg.1', 'TC0100006450.hg.1', 'TC0100006451.hg.1']\n", "\n", "# These identifiers appear to be from the Affymetrix/Thermo Fisher Clariom D array (TC prefix)\n", "# They are probeset IDs, not standard gene symbols\n", "# These need to be mapped to standard human gene symbols\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "df102de8", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "7d712f7d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:29.782275Z", "iopub.status.busy": "2025-03-25T07:00:29.782163Z", "iopub.status.idle": "2025-03-25T07:00:54.337502Z", "shell.execute_reply": "2025-03-25T07:00:54.336950Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'probeset_id', 'seqname', 'strand', 'start', 'stop', 'total_probes', 'gene_assignment', 'mrna_assignment', 'swissprot', 'unigene', 'GO_biological_process', 'GO_cellular_component', 'GO_molecular_function', 'pathway', 'protein_domains', 'category', 'locus type', 'SPOT_ID']\n", "{'ID': ['TC0100006432.hg.1', 'TC0100006433.hg.1', 'TC0100006434.hg.1'], 'probeset_id': ['TC0100006432.hg.1', 'TC0100006433.hg.1', 'TC0100006434.hg.1'], 'seqname': ['chr1', 'chr1', 'chr1'], 'strand': ['+', '+', '+'], 'start': ['11869', '28046', '29554'], 'stop': ['14412', '29178', '31109'], 'total_probes': [10.0, 6.0, 10.0], 'gene_assignment': ['NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// OTTHUMT00000002844 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// OTTHUMT00000362751 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102', 'spopoybu.aAug10-unspliced // spopoybu // Transcript Identified by AceView // --- // ---', 'NR_036267 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000607096 // MIR1302-2 // microRNA 1302-2 // --- // 100302278'], 'mrna_assignment': ['NR_046018 // RefSeq // Homo sapiens DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 (DDX11L1), non-coding RNA. // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002844 // Havana transcript // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1[gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:transcribed_unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000362751 // Havana transcript // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1[gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000450305 // ENSEMBL // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 [gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:transcribed_unprocessed_pseudogene] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000456328 // ENSEMBL // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 [gene_biotype:transcribed_unprocessed_pseudogene transcript_biotype:processed_transcript] // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000001 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000001 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000002 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000002 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000003 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000003 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000004 // lncRNAWiki // Non-coding transcript identified by NONCODE // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000004 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0', 'spopoybu.aAug10-unspliced // Ace View // Transcript Identified by AceView // chr1 // 100 // 100 // 0 // --- // 0', 'NR_036267 // RefSeq // Homo sapiens microRNA 1302-10 (MIR1302-10), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000607096 // ENSEMBL // microRNA 1302-2 [gene_biotype:miRNA transcript_biotype:miRNA] // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036051_3 // RefSeq // Homo sapiens microRNA 1302-2 (MIR1302-2), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036266_3 // RefSeq // Homo sapiens microRNA 1302-9 (MIR1302-9), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036268_4 // RefSeq // Homo sapiens microRNA 1302-11 (MIR1302-11), microRNA. // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000469289 // ENSEMBL // havana:known chromosome:GRCh38:1:30267:31109:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000473358 // ENSEMBL // havana:known chromosome:GRCh38:1:29554:31097:1 gene:ENSG00000243485 gene_biotype:lincRNA transcript_biotype:lincRNA // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000469289.1 // lncRNAWiki // microRNA 1302-11 [Source:HGNC Symbol;Acc:HGNC:38246] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000473358.1 // lncRNAWiki // microRNA 1302-11 [Source:HGNC Symbol;Acc:HGNC:38246] // chr1 // 100 // 100 // 0 // --- // 0 /// ENST00000607096.1 // lncRNAWiki // microRNA 1302-11 [Source:HGNC Symbol;Acc:38246] // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002840 // Havana transcript // novel transcript // chr1 // 100 // 100 // 0 // --- // 0 /// OTTHUMT00000002841 // Havana transcript // novel transcript // chr1 // 100 // 100 // 0 // --- // 0 /// uc031tlb.1 // UCSC Genes // microRNA 1302-2 [Source:HGNC Symbol;Acc:HGNC:35294] // chr1 // 100 // 100 // 0 // --- // 0 /// uc057aty.1 // UCSC Genes // N/A // chr1 // 100 // 100 // 0 // --- // 0 /// uc057atz.1 // UCSC Genes // N/A // chr1 // 100 // 100 // 0 // --- // 0 /// HG491497.1:1..712:ncRNA // RNACentral // long non-coding RNA OTTHUMT00000002840.1 (RP11-34P13.3 gene // chr1 // 100 // 100 // 0 // --- // 0 /// HG491498.1:1..535:ncRNA // RNACentral // long non-coding RNA OTTHUMT00000002841.2 (RP11-34P13.3 gene // chr1 // 100 // 100 // 0 // --- // 0 /// LM610125.1:1..138:precursor_RNA // RNACentral // microRNA hsa-mir-1302-9 precursor // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000011 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NONHSAT000012 // NONCODE // Non-coding transcript identified by NONCODE: Linc // chr1 // 100 // 100 // 0 // --- // 0 /// NR_036051.1:1..138:precursor_RNA // RNACentral // microRNA hsa-mir-1302-9 precursor // chr1 // 100 // 100 // 0 // --- // 0'], 'swissprot': ['NR_046018 // B7ZGX0 /// NR_046018 // B7ZGX2 /// NR_046018 // B7ZGX7 /// NR_046018 // B7ZGX8 /// OTTHUMT00000002844 // B7ZGX0 /// OTTHUMT00000002844 // B7ZGX2 /// OTTHUMT00000002844 // B7ZGX7 /// OTTHUMT00000002844 // B7ZGX8 /// OTTHUMT00000362751 // B7ZGX0 /// OTTHUMT00000362751 // B7ZGX2 /// OTTHUMT00000362751 // B7ZGX7 /// OTTHUMT00000362751 // B7ZGX8 /// ENST00000450305 // B7ZGX0 /// ENST00000450305 // B7ZGX2 /// ENST00000450305 // B7ZGX7 /// ENST00000450305 // B7ZGX8 /// ENST00000450305 // B4E2Z4 /// ENST00000450305 // B7ZGW9 /// ENST00000450305 // Q6ZU42 /// ENST00000450305 // B7ZGX3 /// ENST00000450305 // B5WYT6 /// ENST00000456328 // B7ZGX0 /// ENST00000456328 // B7ZGX2 /// ENST00000456328 // B7ZGX7 /// ENST00000456328 // B7ZGX8 /// ENST00000456328 // B4E2Z4 /// ENST00000456328 // B7ZGW9 /// ENST00000456328 // Q6ZU42 /// ENST00000456328 // B7ZGX3 /// ENST00000456328 // B5WYT6', '---', '---'], 'unigene': ['NR_046018 // Hs.714157 // testis| normal| adult /// OTTHUMT00000002844 // Hs.714157 // testis| normal| adult /// OTTHUMT00000362751 // Hs.714157 // testis| normal| adult /// ENST00000450305 // Hs.719844 // brain| testis| normal /// ENST00000450305 // Hs.714157 // testis| normal| adult /// ENST00000450305 // Hs.740212 // --- /// ENST00000450305 // Hs.712940 // bladder| bone marrow| brain| embryonic tissue| intestine| mammary gland| muscle| pharynx| placenta| prostate| skin| spleen| stomach| testis| thymus| breast (mammary gland) tumor| gastrointestinal tumor| glioma| non-neoplasia| normal| prostate cancer| skin tumor| soft tissue/muscle tissue tumor|embryoid body| adult /// ENST00000456328 // Hs.719844 // brain| testis| normal /// ENST00000456328 // Hs.714157 // testis| normal| adult /// ENST00000456328 // Hs.740212 // --- /// ENST00000456328 // Hs.712940 // bladder| bone marrow| brain| embryonic tissue| intestine| mammary gland| muscle| pharynx| placenta| prostate| skin| spleen| stomach| testis| thymus| breast (mammary gland) tumor| gastrointestinal tumor| glioma| non-neoplasia| normal| prostate cancer| skin tumor| soft tissue/muscle tissue tumor|embryoid body| adult', '---', '---'], 'GO_biological_process': ['ENST00000450305 // GO:0006139 // nucleobase-containing compound metabolic process // inferred from electronic annotation /// ENST00000456328 // GO:0006139 // nucleobase-containing compound metabolic process // inferred from electronic annotation', '---', '---'], 'GO_cellular_component': ['---', '---', '---'], 'GO_molecular_function': ['ENST00000450305 // GO:0003676 // nucleic acid binding // inferred from electronic annotation /// ENST00000450305 // GO:0005524 // ATP binding // inferred from electronic annotation /// ENST00000450305 // GO:0008026 // ATP-dependent helicase activity // inferred from electronic annotation /// ENST00000450305 // GO:0016818 // hydrolase activity, acting on acid anhydrides, in phosphorus-containing anhydrides // inferred from electronic annotation /// ENST00000456328 // GO:0003676 // nucleic acid binding // inferred from electronic annotation /// ENST00000456328 // GO:0005524 // ATP binding // inferred from electronic annotation /// ENST00000456328 // GO:0008026 // ATP-dependent helicase activity // inferred from electronic annotation /// ENST00000456328 // GO:0016818 // hydrolase activity, acting on acid anhydrides, in phosphorus-containing anhydrides // inferred from electronic annotation', '---', '---'], 'pathway': ['---', '---', '---'], 'protein_domains': ['---', '---', '---'], 'category': ['main', 'main', 'main'], 'locus type': ['Multiple_Complex', 'Coding', 'Multiple_Complex'], 'SPOT_ID': ['NR_046018 // RefSeq', 'spopoybu.aAug10-unspliced // Ace View', 'NR_036267 // RefSeq']}\n", "\n", "Examining ID and gene_assignment columns format (first 3 rows):\n", "Row 0: ID=TC0100006432.hg.1, gene_assignment=NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// OTTHUMT00000002844 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// OTTHUMT00000362751 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102\n", "Row 1: ID=TC0100006433.hg.1, gene_assignment=spopoybu.aAug10-unspliced // spopoybu // Transcript Identified by AceView // --- // ---\n", "Row 2: ID=TC0100006434.hg.1, gene_assignment=NR_036267 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000607096 // MIR1302-2 // microRNA 1302-2 // --- // 100302278\n", "\n", "gene_assignment column completeness: 138745/8283805 rows (1.67%)\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=3))\n", "\n", "# Looking at the output, the gene_assignment column contains gene symbols\n", "print(\"\\nExamining ID and gene_assignment columns format (first 3 rows):\")\n", "if 'ID' in gene_annotation.columns and 'gene_assignment' in gene_annotation.columns:\n", " for i in range(min(3, len(gene_annotation))):\n", " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}, gene_assignment={gene_annotation['gene_assignment'].iloc[i]}\")\n", "\n", " # Check the quality and completeness of the mapping\n", " non_null_symbols = gene_annotation['gene_assignment'].notna().sum()\n", " total_rows = len(gene_annotation)\n", " print(f\"\\ngene_assignment column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n" ] }, { "cell_type": "markdown", "id": "bd219bfa", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "0939a4c1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:54.339015Z", "iopub.status.busy": "2025-03-25T07:00:54.338894Z", "iopub.status.idle": "2025-03-25T07:00:58.020198Z", "shell.execute_reply": "2025-03-25T07:00:58.019638Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Mapping dataframe shape: (138745, 2)\n", "First 5 rows of mapping dataframe:\n", "{'ID': ['TC0100006432.hg.1', 'TC0100006433.hg.1', 'TC0100006434.hg.1', 'TC0100006435.hg.1', 'TC0100006436.hg.1'], 'Gene': ['NR_046018 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// OTTHUMT00000002844 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102 /// OTTHUMT00000362751 // DDX11L1 // DEAD/H (Asp-Glu-Ala-Asp/His) box helicase 11 like 1 // 1p36.33 // 100287102', 'spopoybu.aAug10-unspliced // spopoybu // Transcript Identified by AceView // --- // ---', 'NR_036267 // MIR1302-10 // microRNA 1302-10 // --- // 100422834 /// ENST00000607096 // MIR1302-2 // microRNA 1302-2 // --- // 100302278', 'OTTHUMT00000471235 // OR4G4P // olfactory receptor, family 4, subfamily G, member 4 pseudogene // 1p36.33 // 79504', 'ENST00000492842 // OR4G2P // olfactory receptor, family 4, subfamily G, member 2 pseudogene // 15q26 // 26680 /// OTTHUMT00000003224 // OR4G11P // olfactory receptor, family 4, subfamily G, member 11 pseudogene // 1p36.33 // 403263']}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data shape after mapping: (73312, 60)\n", "First 5 genes and their expression values:\n", "{'GSM6321013': [23.78333333333333, 13.778, 0.67375, 1.7553571428571428, 1.2], 'GSM6321014': [25.804166666666667, 13.702, 0.5725, 1.86, 1.3533333333333333], 'GSM6321015': [24.316666666666666, 12.75, 0.47125, 1.7839285714285715, 1.2366666666666666], 'GSM6321016': [24.875833333333333, 13.846, 0.70125, 1.8382142857142858, 1.2566666666666666], 'GSM6321017': [24.53, 13.372, 0.73375, 1.8485714285714285, 1.2566666666666666], 'GSM6321018': [23.740833333333335, 13.397, 0.5475, 1.7925, 1.2433333333333334], 'GSM6321019': [25.88, 13.86, 0.68625, 2.0039285714285713, 1.1966666666666665], 'GSM6321020': [24.820833333333333, 13.882, 0.71, 1.936785714285714, 1.0666666666666667], 'GSM6321021': [24.249166666666667, 13.501, 0.6475, 1.7717857142857143, 1.3399999999999999], 'GSM6321022': [25.4325, 14.193999999999999, 0.7875, 2.1514285714285712, 1.32], 'GSM6321023': [24.123333333333335, 13.218, 0.6575, 1.7664285714285715, 1.08], 'GSM6321024': [24.245, 14.112, 0.61875, 1.6657142857142857, 1.22], 'GSM6321025': [25.384166666666665, 13.531, 0.69375, 1.8732142857142857, 1.1066666666666667], 'GSM6321026': [24.07, 13.687000000000001, 0.73875, 1.6814285714285715, 1.0933333333333333], 'GSM6321027': [24.84916666666667, 13.777, 0.68625, 1.86, 1.1933333333333334], 'GSM6321028': [26.574166666666667, 14.75, 0.67125, 2.0810714285714287, 1.1966666666666665], 'GSM6321029': [23.9875, 12.979, 0.5925, 1.9375, 1.2666666666666666], 'GSM6321030': [24.454166666666666, 13.134, 0.60625, 1.7407142857142857, 1.1333333333333333], 'GSM6321031': [25.655833333333334, 13.956999999999999, 0.62625, 1.9171428571428573, 1.1066666666666667], 'GSM6321032': [24.010833333333334, 13.883, 0.52125, 1.7289285714285714, 1.1466666666666667], 'GSM6321033': [26.736666666666665, 14.501, 0.74, 2.0014285714285713, 1.1266666666666667], 'GSM6321034': [24.634166666666665, 13.45, 0.6325, 1.7867857142857144, 1.2933333333333332], 'GSM6321035': [22.57, 13.64, 1.12, 1.6460714285714286, 1.2433333333333334], 'GSM6321036': [23.631666666666668, 13.467, 0.69, 1.8582142857142858, 1.07], 'GSM6321037': [26.0325, 13.623000000000001, 0.875, 2.072857142857143, 1.1033333333333333], 'GSM6321038': [26.270833333333332, 13.207, 0.66375, 1.775357142857143, 1.0933333333333333], 'GSM6321039': [26.08416666666667, 13.462, 0.75, 2.0635714285714286, 1.1199999999999999], 'GSM6321040': [25.624166666666667, 13.879, 0.76375, 1.6896428571428572, 1.19], 'GSM6321041': [24.002499999999998, 12.936, 0.5825, 1.6589285714285713, 1.1233333333333333], 'GSM6321042': [24.223333333333333, 12.818999999999999, 0.54375, 1.731785714285714, 1.07], 'GSM6321043': [26.6125, 14.18, 0.74875, 1.862142857142857, 1.0833333333333333], 'GSM6321044': [23.481666666666666, 13.651, 0.75875, 1.7767857142857144, 1.2833333333333334], 'GSM6321045': [23.833333333333332, 13.571, 0.48125, 1.7296428571428573, 1.1433333333333333], 'GSM6321046': [24.053333333333335, 13.448, 0.54125, 1.7075, 1.2533333333333332], 'GSM6321047': [26.09916666666667, 15.043, 0.6925, 1.8610714285714285, 1.2233333333333334], 'GSM6321048': [25.505, 14.125, 0.74875, 2.0453571428571427, 1.1433333333333333], 'GSM6321049': [24.430833333333332, 13.737, 0.52875, 1.792857142857143, 1.21], 'GSM6321050': [24.553333333333335, 13.478, 0.73875, 1.7646428571428572, 1.23], 'GSM6321051': [23.230833333333333, 13.898, 0.55375, 1.7582142857142857, 1.38], 'GSM6321052': [24.625, 13.211, 0.5325, 2.0325, 1.18], 'GSM6321053': [23.370833333333334, 13.87, 0.58625, 1.6885714285714286, 1.2033333333333334], 'GSM6321054': [25.556666666666665, 14.221, 0.66125, 1.895, 1.1566666666666667], 'GSM6321055': [25.725, 14.253, 0.645, 1.9596428571428572, 1.2233333333333334], 'GSM6321056': [24.6525, 13.586, 0.50625, 1.6478571428571427, 1.16], 'GSM6321057': [23.719166666666666, 13.142999999999999, 0.485, 1.7192857142857143, 1.37], 'GSM6321058': [24.964166666666667, 13.927, 0.69625, 1.9821428571428572, 1.0533333333333335], 'GSM6321059': [25.538333333333334, 14.387, 0.71, 2.052142857142857, 1.19], 'GSM6321060': [25.688333333333333, 13.483, 0.7125, 1.9125, 1.26], 'GSM6321061': [23.655833333333334, 13.738, 0.54125, 1.7982142857142858, 1.1233333333333333], 'GSM6321062': [23.9675, 13.775, 0.5525, 1.7271428571428573, 1.5266666666666666], 'GSM6321063': [23.825, 12.667, 0.55875, 1.695, 1.3], 'GSM6321064': [23.561666666666667, 13.620000000000001, 0.72375, 1.7360714285714285, 1.2766666666666666], 'GSM6321065': [23.295833333333334, 13.771, 0.74375, 1.81, 1.11], 'GSM6321066': [24.096666666666668, 13.527000000000001, 0.57, 1.8489285714285715, 1.1866666666666668], 'GSM6321067': [25.284166666666668, 13.815, 0.6775, 1.8214285714285714, 1.1233333333333333], 'GSM6321068': [25.756666666666668, 13.122, 0.6625, 1.7510714285714286, 1.1933333333333334], 'GSM6321069': [24.190833333333334, 13.783999999999999, 0.6125, 1.7360714285714285, 1.36], 'GSM6321070': [24.461666666666666, 13.361, 0.77625, 1.8410714285714285, 1.2966666666666666], 'GSM6321071': [24.28333333333333, 13.761, 0.63375, 1.7060714285714287, 1.1933333333333334], 'GSM6321072': [25.161666666666665, 14.135, 0.65, 1.8428571428571427, 1.2866666666666666]}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data saved to ../../output/preprocess/Breast_Cancer/gene_data/GSE207847.csv\n" ] } ], "source": [ "# 1. Identify which columns contain the gene identifiers and gene symbols\n", "# From the previous step, we can see:\n", "# - 'ID' column contains the probe identifiers (TC0100006432.hg.1, etc.)\n", "# - 'gene_assignment' column contains gene symbols (e.g., DDX11L1, MIR1302-10)\n", "\n", "# 2. Get a gene mapping dataframe by extracting the ID and gene_assignment columns\n", "# The ID in gene_annotation corresponds to gene identifiers in the gene expression data\n", "prob_col = 'ID'\n", "gene_col = 'gene_assignment'\n", "\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "print(f\"Mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"First 5 rows of mapping dataframe:\")\n", "print(preview_df(mapping_df, n=5))\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene-level data\n", "# First check if we have the gene expression data from the previous step\n", "if 'gene_data' not in locals():\n", " print(\"Extracting gene expression data...\")\n", " gene_data_probes = get_genetic_data(matrix_file)\n", "else:\n", " gene_data_probes = gene_data\n", "\n", "# Apply the mapping to convert probe-level measurements to gene-level data\n", "gene_data = apply_gene_mapping(gene_data_probes, mapping_df)\n", "print(f\"\\nGene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First 5 genes and their expression values:\")\n", "print(preview_df(gene_data, n=5))\n", "\n", "# Save gene data to CSV file for future use\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\"\\nGene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "ce072429", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "72f4b090", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:00:58.021808Z", "iopub.status.busy": "2025-03-25T07:00:58.021686Z", "iopub.status.idle": "2025-03-25T07:01:28.161377Z", "shell.execute_reply": "2025-03-25T07:01:28.160973Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (73312, 60)\n", "Gene data shape after normalization: (34003, 60)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Breast_Cancer/gene_data/GSE207847.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Extracted clinical data shape: (2, 60)\n", "Preview of clinical data (first 5 samples):\n", " GSM6321013 GSM6321014 GSM6321015 GSM6321016 GSM6321017\n", "Breast_Cancer 0.0 1.0 2.0 2.0 0.0\n", "Gender 0.0 0.0 0.0 0.0 0.0\n", "Clinical data saved to ../../output/preprocess/Breast_Cancer/clinical_data/GSE207847.csv\n", "Gene data columns (first 5): ['GSM6321013', 'GSM6321014', 'GSM6321015', 'GSM6321016', 'GSM6321017']\n", "Clinical data columns (first 5): ['GSM6321013', 'GSM6321014', 'GSM6321015', 'GSM6321016', 'GSM6321017']\n", "Found 60 common samples between gene and clinical data\n", "Initial linked data shape: (60, 34005)\n", "Preview of linked data (first 5 rows, first 5 columns):\n", " Breast_Cancer Gender A1BG A1BG-AS1 A1CF\n", "GSM6321013 0.0 0.0 4.351 3.525 0.8300\n", "GSM6321014 1.0 0.0 4.419 3.605 0.8800\n", "GSM6321015 2.0 0.0 5.139 4.165 1.1150\n", "GSM6321016 2.0 0.0 4.494 3.650 0.8725\n", "GSM6321017 0.0 0.0 4.442 3.550 0.8475\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (60, 34005)\n", "Quartiles for 'Breast_Cancer':\n", " 25%: 0.0\n", " 50% (Median): 1.0\n", " 75%: 2.0\n", "Min: 0.0\n", "Max: 2.0\n", "The distribution of the feature 'Breast_Cancer' in this dataset is fine.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 60 occurrences. This represents 100.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is severely biased.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Breast_Cancer/GSE207847.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Make sure the directory exists\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Use the gene_data variable from the previous step (don't try to load it from file)\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Apply normalization to gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " # Use the normalized data for further processing\n", " gene_data = normalized_gene_data\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data - respecting the analysis from Step 2\n", "# From Step 2, we determined:\n", "# trait_row = None # No Breast Cancer subtype data available\n", "# age_row = 2\n", "# gender_row = None\n", "is_trait_available = trait_row is not None\n", "\n", "# Skip clinical feature extraction when trait_row is None\n", "if is_trait_available:\n", " try:\n", " # Load the clinical data from file\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Extract clinical features\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender,\n", " age_row=age_row,\n", " convert_age=convert_age\n", " )\n", " \n", " print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n", " print(\"Preview of clinical data (first 5 samples):\")\n", " print(clinical_features.iloc[:, :5])\n", " \n", " # Save the properly extracted clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", "else:\n", " print(f\"No trait data ({trait}) available in this dataset based on previous analysis.\")\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Debug the column names to ensure they match\n", " print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n", " print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n", " \n", " # Check for common sample IDs\n", " common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n", " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n", " \n", " if len(common_samples) > 0:\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " \n", " # Debug the trait values before handling missing values\n", " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\n", " is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", " \n", " # Save the linked data if it's usable\n", " if is_usable:\n", " 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 to {out_data_file}\")\n", " else:\n", " print(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " print(\"No common samples found between gene expression and clinical data.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No common samples between gene expression and clinical data.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " 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=True, # Assume biased if there's an error\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error in data processing: {str(e)}\"\n", " )\n", "else:\n", " # Create an empty DataFrame for metadata purposes\n", " empty_df = pd.DataFrame()\n", " \n", " # We can't proceed with linking if either trait or gene data is missing\n", " print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n", " 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=True, # Data is unusable if we're missing components\n", " df=empty_df, # Empty dataframe for metadata\n", " note=\"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\n", " )" ] } ], "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 }