{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "8acd3956", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:32.088340Z", "iopub.status.busy": "2025-03-25T07:58:32.088115Z", "iopub.status.idle": "2025-03-25T07:58:32.256972Z", "shell.execute_reply": "2025-03-25T07:58:32.256648Z" } }, "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 = \"Mesothelioma\"\n", "cohort = \"GSE163721\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Mesothelioma\"\n", "in_cohort_dir = \"../../input/GEO/Mesothelioma/GSE163721\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Mesothelioma/GSE163721.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Mesothelioma/gene_data/GSE163721.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Mesothelioma/clinical_data/GSE163721.csv\"\n", "json_path = \"../../output/preprocess/Mesothelioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "2635373f", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "4a1cdc66", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:32.258458Z", "iopub.status.busy": "2025-03-25T07:58:32.258320Z", "iopub.status.idle": "2025-03-25T07:58:32.447201Z", "shell.execute_reply": "2025-03-25T07:58:32.446795Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE163721_family.soft.gz', 'GSE163721_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Mesothelioma/GSE163721/GSE163721_family.soft.gz\n", "Matrix file: ../../input/GEO/Mesothelioma/GSE163721/GSE163721_series_matrix.txt.gz\n", "Background Information:\n", "!Series_title\t\"Association of RERG Expression to Female Survival Advantage in Malignant Pleural Mesothelioma II\"\n", "!Series_summary\t\"Sex differences in incidence, prognosis, and treatment response have been described for many cancers. In malignant pleural mesothelioma (MPM), a lethal disease associated with asbestos exposure, men outnumber women 4 to 1, but women consistently live longer than men following surgery-based therapy. This study investigated whether tumor expression of genes associated with estrogen signaling could potentially explain observed survival differences. Two microarray datasets of MPM tumors were analyzed to discover estrogen-related genes associated with survival. A validation cohort of MPM tumors was selected to balance the numbers of men and women and control for competing prognostic influences. The RAS like estrogen regulated growth inhibitor (RERG) gene was identified as the most differentially-expressed estrogen-related gene in these tumors and predicted prognosis in discovery datasets. In the sex-matched validation cohort, low RERG expression was significantly associated with increased risk of death among women. No association between RERG expression and survival was found among men, and no relationship between estrogen receptor protein or gene expression and survival was found for either sex. Additional investigations are needed to elucidate the molecular mechanisms underlying this association and its sex specificity.\"\n", "!Series_overall_design\t\"This study investigated whether tumor expression of genes associated with estrogen signaling could potentially explain observed survival differences between men and women affected by malignant pleural mesothelioma.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue type: Tumor']}\n" ] } ], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "9af59cf5", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "7f2ed36d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:32.448555Z", "iopub.status.busy": "2025-03-25T07:58:32.448443Z", "iopub.status.idle": "2025-03-25T07:58:32.455294Z", "shell.execute_reply": "2025-03-25T07:58:32.455014Z" } }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import pandas as pd\n", "from typing import Optional, Callable, Dict, Any\n", "import os\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset is about gene expression related to estrogen signaling in MPM\n", "# The data is described as \"microarray datasets of MPM tumors\" which indicates gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Data Availability\n", "# From the background information, this is a study about Malignant Pleural Mesothelioma (MPM)\n", "# All samples appear to be tumor samples (MPM) based on the sample characteristics showing \"tissue type: Tumor\"\n", "# Since all samples are mesothelioma tumors (no controls), there's no useful trait variable for association studies\n", "\n", "# The constant feature (all samples are mesothelioma) is not useful for associative studies\n", "trait_row = None # No control vs. disease comparison possible\n", "age_row = None # No age information visible in the sample characteristics\n", "gender_row = None # Not visible in the sample preview\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(val: str) -> Optional[int]:\n", " \"\"\"Convert trait values to binary format (0=control, 1=Mesothelioma)\"\"\"\n", " if val is None:\n", " return None\n", " val = val.split(':', 1)[-1].strip().lower()\n", " if 'mesothelioma' in val or 'mpm' in val or 'tumor' in val:\n", " return 1\n", " elif 'control' in val or 'normal' in val:\n", " return 0\n", " return None\n", "\n", "def convert_age(val: str) -> Optional[float]:\n", " \"\"\"Convert age values to continuous format\"\"\"\n", " if val is None:\n", " return None\n", " val = val.split(':', 1)[-1].strip()\n", " try:\n", " return float(val)\n", " except:\n", " return None\n", "\n", "def convert_gender(val: str) -> Optional[int]:\n", " \"\"\"Convert gender values to binary format (0=female, 1=male)\"\"\"\n", " if val is None:\n", " return None\n", " val = val.split(':', 1)[-1].strip().lower()\n", " if 'female' in val or 'f' == val:\n", " return 0\n", " elif 'male' in val or 'm' == val:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Since we don't have a useful trait variable (all samples are the same), we set trait_available to False\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial validation information\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", "# We skip this step since trait_row is None (as instructed)\n" ] }, { "cell_type": "markdown", "id": "b2d5634e", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "cb68f8b1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:32.456407Z", "iopub.status.busy": "2025-03-25T07:58:32.456301Z", "iopub.status.idle": "2025-03-25T07:58:32.743803Z", "shell.execute_reply": "2025-03-25T07:58:32.743347Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "No subseries references found in the first 1000 lines of the SOFT file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 54359\n", "First 20 gene/probe identifiers:\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" ] } ], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "36a89324", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "95fa2ce3", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:32.745288Z", "iopub.status.busy": "2025-03-25T07:58:32.745165Z", "iopub.status.idle": "2025-03-25T07:58:32.747123Z", "shell.execute_reply": "2025-03-25T07:58:32.746828Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers from previous output\n", "# The identifiers appear to be just sequential numbers (1, 2, 3...) \n", "# These are clearly not gene symbols and would need mapping\n", "# They're likely probe IDs that need to be mapped to actual gene symbols\n", "\n", "# Based on the pattern of identifiers (simple sequential numbers),\n", "# we definitely need gene mapping\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "e575e5d6", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "cdebe247", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:32.748330Z", "iopub.status.busy": "2025-03-25T07:58:32.748223Z", "iopub.status.idle": "2025-03-25T07:58:37.147357Z", "shell.execute_reply": "2025-03-25T07:58:37.146720Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1', '2', '3', '4', '5'], 'Block': ['1', '1', '1', '1', '1'], 'Row': [1.0, 1.0, 1.0, 1.0, 1.0], 'Column': [1.0, 2.0, 3.0, 4.0, 5.0], 'Probe Name': ['GE200017', 'GE766244', 'GE766859', 'GE519376', 'GE519777'], 'Probe Type': ['FIDUCIAL', 'DISCOVERY', 'DISCOVERY', 'DISCOVERY', 'DISCOVERY'], 'GB_ACC': [nan, 'XM_293099', 'BF588963', nan, 'BE550764'], 'Entrez Gene ID': ['-', '-', '5337', '-', '53944'], 'Gene Symbol': ['-', '-', 'PLD1', '-', 'CSNK1G1'], 'Gene Name': ['-', '-', 'phospholipase D1, phosphatidylcholine-specific', '-', 'casein kinase 1, gamma 1'], 'RefSeq ID': ['-', '-', 'NM_001130081, NM_002662', '-', 'NM_022048'], 'Unigene ID': ['-', '-', 'Hs.382865', '-', 'Hs.646508'], 'Ensembl ID': ['-', '-', 'ENSG00000075651', '-', 'ENSG00000169118'], 'UniProt ID': ['-', '-', 'Q13393, Q59EA4', '-', 'Q9HCP0'], 'Chromosome No.': ['-', '-', '3', '-', '15'], 'Chromosome Position': ['-', '-', 'chr3:171318619-171528273', '-', 'chr15:64457717-64648442'], 'GO biological process': ['-', '-', 'GO:0006654(phosphatidic acid biosynthetic process); GO:0006935(chemotaxis); GO:0007154(cell communication); GO:0007264(small GTPase mediated signal transduction); GO:0007265(Ras protein signal transduction); GO:0008654(phospholipid biosynthetic process); GO:0009395(phospholipid catabolic process); GO:0016042(lipid catabolic process); GO:0030335(positive regulation of cell migration); GO:0043434(response to peptide hormone stimulus); GO:0050830(defense response to Gram-positive bacterium)', '-', 'GO:0006468(protein phosphorylation); GO:0016055(Wnt receptor signaling pathway)'], 'GO molecular function': ['-', '-', 'GO:0004630(phospholipase D activity); GO:0016787(hydrolase activity); GO:0035091(phosphatidylinositol binding); GO:0070290(NAPE-specific phospholipase D activity)', '-', 'GO:0000166(nucleotide binding); GO:0004674(protein serine/threonine kinase activity); GO:0005524(ATP binding); GO:0016740(transferase activity)'], 'GO cellular component': ['-', '-', 'GO:0000139(Golgi membrane); GO:0005737(cytoplasm); GO:0005768(endosome); GO:0005783(endoplasmic reticulum); GO:0005789(endoplasmic reticulum membrane); GO:0005792(microsome); GO:0005794(Golgi apparatus); GO:0016020(membrane); GO:0030027(lamellipodium); GO:0031902(late endosome membrane); GO:0031982(vesicle); GO:0031985(Golgi cisterna); GO:0048471(perinuclear region of cytoplasm)', '-', 'GO:0005737(cytoplasm)'], 'SEQUENCE': [nan, 'ATGCTCTGTAGTGTCCTCCCCCTGGTGCAG', 'ATGCAATGCAGTGTTTCTTATCTCTGGTGA', 'CCTCTTCTGACACCTCACGAATGCCTGGAG', 'AATGTGAGGGATAAGGAAAACGGAAGGGTC'], 'SPOT_ID': ['CONTROL_FIDUCIAL probe for gridding', nan, nan, nan, nan]}\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "gene_annotation = get_gene_annotation(soft_file)\n", "\n", "# 2. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "c4092f0e", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "f5bdf05b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:37.149076Z", "iopub.status.busy": "2025-03-25T07:58:37.148947Z", "iopub.status.idle": "2025-03-25T07:58:37.401521Z", "shell.execute_reply": "2025-03-25T07:58:37.400891Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Column names in gene annotation dataframe:\n", "['ID', 'Block', 'Row', 'Column', 'Probe Name', 'Probe Type', 'GB_ACC', 'Entrez Gene ID', 'Gene Symbol', 'Gene Name', 'RefSeq ID', 'Unigene ID', 'Ensembl ID', 'UniProt ID', 'Chromosome No.', 'Chromosome Position', 'GO biological process', 'GO molecular function', 'GO cellular component', 'SEQUENCE', 'SPOT_ID']\n", "\n", "Gene mapping summary:\n", "Total probes in mapping: 54359\n", "Probes with gene symbols: 33916\n", "Sample of gene mapping data:\n", " ID Gene\n", "0 1 -\n", "1 2 -\n", "2 3 PLD1\n", "3 4 -\n", "4 5 CSNK1G1\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data summary:\n", "Shape: (16896, 46)\n", "First few rows and columns:\n", " GSM4984502 GSM4984503 GSM4984504 GSM4984505 GSM4984506\n", "Gene \n", "A1BG 0.453598 0.867600 1.025219 0.847260 0.890790\n", "A1CF 0.813705 1.519490 0.954572 0.542159 1.383813\n", "A2LD1 1.387532 4.196274 1.546933 2.156707 4.564961\n", "A2ML1 1.600246 1.708296 1.472621 1.092117 1.479736\n", "A4GALT 0.700037 0.348783 0.462628 0.229904 0.352832\n" ] } ], "source": [ "# 1. Determine the appropriate columns for mapping\n", "# The gene expression data shows row indices as numeric IDs like 1, 2, 3...\n", "# In the gene annotation dataframe, 'ID' column contains these same identifiers\n", "# The 'Gene Symbol' column in the annotation dataframe contains the gene symbols we need\n", "\n", "# Checking column names to confirm\n", "print(\"Column names in gene annotation dataframe:\")\n", "print(gene_annotation.columns.tolist())\n", "\n", "# 2. Get gene mapping dataframe by extracting the two columns from the gene annotation dataframe\n", "# Extract ID and Gene Symbol columns for mapping\n", "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'Gene Symbol')\n", "\n", "# Display summary of the mapping data\n", "print(\"\\nGene mapping summary:\")\n", "print(f\"Total probes in mapping: {len(gene_mapping)}\")\n", "print(f\"Probes with gene symbols: {len(gene_mapping[gene_mapping['Gene'] != '-'])}\")\n", "print(f\"Sample of gene mapping data:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Convert probe-level measurements to gene expression data\n", "# Apply the mapping to convert probes to genes\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Display summary of the resulting gene expression data\n", "print(\"\\nGene expression data summary:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(\"First few rows and columns:\")\n", "print(gene_data.iloc[:5, :5])\n" ] }, { "cell_type": "markdown", "id": "b3d78cde", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "ab237fd2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:58:37.403232Z", "iopub.status.busy": "2025-03-25T07:58:37.403119Z", "iopub.status.idle": "2025-03-25T07:58:42.429606Z", "shell.execute_reply": "2025-03-25T07:58:42.428995Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of gene data after normalization: (16665, 46)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene data to ../../output/preprocess/Mesothelioma/gene_data/GSE163721.csv\n", "Number of samples: 46\n", "Sample characteristics dictionary:\n", "{0: ['tissue type: Tumor']}\n", "Clinical data preview:\n", " Mesothelioma\n", "GSM4984502 1\n", "GSM4984503 1\n", "GSM4984504 1\n", "GSM4984505 1\n", "GSM4984506 1\n", "Saved clinical data to ../../output/preprocess/Mesothelioma/clinical_data/GSE163721.csv\n", "Shape of linked data: (46, 16666)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (46, 16666)\n", "Quartiles for 'Mesothelioma':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1\n", "Max: 1\n", "The distribution of the feature 'Mesothelioma' in this dataset is severely biased.\n", "\n", "Dataset validation failed due to biased trait variable. Final linked data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of gene data after normalization: {gene_data_normalized.shape}\")\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data_normalized.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Create clinical data from the sample IDs in the gene expression data\n", "# Since all samples are from tumor tissue, they all have mesothelioma (but this is not useful as a trait)\n", "sample_ids = gene_data.columns.tolist()\n", "print(f\"Number of samples: {len(sample_ids)}\")\n", "\n", "# Extract gender information from the original matrix file\n", "gender_data = {}\n", "try:\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Read the matrix file to extract sample characteristics\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Display unique values in each row of clinical data\n", " characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Sample characteristics dictionary:\")\n", " print(characteristics_dict)\n", " \n", " # Try to find gender information in the characteristics\n", " gender_row = None\n", " for idx, values in characteristics_dict.items():\n", " if any('sex:' in str(v).lower() for v in values):\n", " gender_row = idx\n", " break\n", " \n", " if gender_row is not None:\n", " # Extract gender data from the row\n", " for col in clinical_data.columns:\n", " if col != '!Sample_geo_accession':\n", " continue\n", " \n", " for idx, row in clinical_data.iterrows():\n", " if idx == gender_row:\n", " for i, sample_id in enumerate(clinical_data.iloc[0].values):\n", " if i > 0 and sample_id in sample_ids: # Skip the first column (header)\n", " gender_val = clinical_data.iloc[idx, i]\n", " if isinstance(gender_val, str) and 'sex:' in gender_val.lower():\n", " gender = 0 if 'f' in gender_val.lower() else 1 if 'm' in gender_val.lower() else None\n", " gender_data[sample_id] = gender\n", "except Exception as e:\n", " print(f\"Error extracting gender data: {e}\")\n", "\n", "# Create a clinical dataframe\n", "clinical_df = pd.DataFrame(index=sample_ids)\n", "clinical_df['Mesothelioma'] = 1 # All samples have mesothelioma\n", "\n", "# Add gender if available\n", "if gender_data:\n", " clinical_df['Gender'] = clinical_df.index.map(lambda x: gender_data.get(x))\n", " print(f\"Added gender data for {sum(pd.notna(clinical_df['Gender']))} samples\")\n", "\n", "print(\"Clinical data preview:\")\n", "print(clinical_df.head())\n", "\n", "# Save the clinical data\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\"Saved clinical data to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data (transpose gene expression data to have samples as rows)\n", "linked_data = pd.concat([clinical_df, gene_data_normalized.T], axis=1)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data_cleaned = handle_missing_values(linked_data, 'Mesothelioma')\n", "print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", "\n", "# 5. Check if the trait is biased (it will be since all samples are mesothelioma)\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, 'Mesothelioma')\n", "\n", "# 6. Validate the dataset and save cohort information\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=True,\n", " is_trait_available=True, # We do have trait data, it's just that all values are the same\n", " is_biased=is_trait_biased, # This will be True since all samples have the same trait value\n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data from mesothelioma patients only (no controls), making trait biased.\"\n", ")\n", "\n", "# 7. 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", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset validation failed due to biased trait variable. Final linked data not saved.\")" ] } ], "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 }