{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "9fed05d7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:53:13.320599Z", "iopub.status.busy": "2025-03-25T03:53:13.320498Z", "iopub.status.idle": "2025-03-25T03:53:13.490101Z", "shell.execute_reply": "2025-03-25T03:53:13.489745Z" } }, "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 = \"Sarcoma\"\n", "cohort = \"GSE133228\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Sarcoma\"\n", "in_cohort_dir = \"../../input/GEO/Sarcoma/GSE133228\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Sarcoma/GSE133228.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Sarcoma/gene_data/GSE133228.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Sarcoma/clinical_data/GSE133228.csv\"\n", "json_path = \"../../output/preprocess/Sarcoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "315e4635", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "85dd80e0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:53:13.491531Z", "iopub.status.busy": "2025-03-25T03:53:13.491368Z", "iopub.status.idle": "2025-03-25T03:53:13.642779Z", "shell.execute_reply": "2025-03-25T03:53:13.642408Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE133228-GPL16311_series_matrix.txt.gz', 'GSE133228_family.soft.gz']\n", "SOFT file: ../../input/GEO/Sarcoma/GSE133228/GSE133228_family.soft.gz\n", "Matrix file: ../../input/GEO/Sarcoma/GSE133228/GSE133228-GPL16311_series_matrix.txt.gz\n", "Background Information:\n", "!Series_title\t\"STAG2 promotes CTCF-anchored loop extrusion and cis-promoter and -enhancer interactions\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['gender: Male', 'gender: Female'], 1: ['age: 3', 'age: 11', 'age: 4', 'age: 25', 'age: 13', 'age: 15', 'age: 19', 'age: 8', 'age: 20', 'age: 24', 'age: 16', 'age: 14', 'age: 5', 'age: 37', 'age: 26', 'age: 10', 'age: 35', 'age: 23', 'age: 17', 'age: 12', 'age: 9', 'age: 0', 'age: 36', 'age: 27', 'age: 1', 'age: 18', 'age: 29', 'age: 6', 'age: 28', 'age: 31'], 2: ['tumor type: primary 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": "e944276f", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "c1a26138", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:53:13.644254Z", "iopub.status.busy": "2025-03-25T03:53:13.644140Z", "iopub.status.idle": "2025-03-25T03:53:13.809076Z", "shell.execute_reply": "2025-03-25T03:53:13.808692Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Trait data is not available. Skipping clinical feature extraction.\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import re\n", "import numpy as np\n", "\n", "# Load clinical data\n", "clinical_data = pd.read_csv(os.path.join(in_cohort_dir, \"GSE133228-GPL16311_series_matrix.txt.gz\"), \n", " sep='\\t', comment='!', skiprows=0)\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the matrix filename \"GSE133228-GPL16311_series_matrix.txt.gz\", this likely contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Sarcoma)\n", "# From sample characteristics dict, key 2 has 'tumor type: primary tumor', but it's a constant value\n", "# As per instructions, constant features are useless in associative studies\n", "trait_row = None\n", "\n", "# For age\n", "# Age is available under key 1 in the sample characteristics dictionary\n", "age_row = 1\n", "\n", "# For gender\n", "# Gender is available under key 0 in the sample characteristics dictionary\n", "gender_row = 0\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "# For trait (keeping this function in case it's needed later)\n", "def convert_trait(value):\n", " if value is None:\n", " return None\n", " \n", " # Handle if value is already numeric\n", " if isinstance(value, (int, float)):\n", " return 1 if value == 1 else 0\n", " \n", " # For string values, extract after colon if present\n", " if ':' in str(value):\n", " value = str(value).split(':', 1)[1].strip()\n", " \n", " if 'primary tumor' in str(value).lower():\n", " return 1\n", " else:\n", " return 0\n", "\n", "# For age\n", "def convert_age(value):\n", " if value is None:\n", " return None\n", " \n", " # Handle if value is already numeric\n", " if isinstance(value, (int, float)):\n", " return float(value)\n", " \n", " # Extract value after colon if present\n", " if ':' in str(value):\n", " value = str(value).split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "# For gender\n", "def convert_gender(value):\n", " if value is None:\n", " return None\n", " \n", " # Handle if value is already numeric\n", " if isinstance(value, (int, float)):\n", " return 1 if value == 1 else 0 if value == 0 else None\n", " \n", " # Extract value after colon if present\n", " if ':' in str(value):\n", " value = str(value).split(':', 1)[1].strip().lower()\n", " else:\n", " value = str(value).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", "# 3. Save Metadata\n", "# Determine if trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering\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", "# Since trait_row is None, we skip this step\n", "if trait_row is not None:\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # 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", "else:\n", " print(\"Trait data is not available. Skipping clinical feature extraction.\")\n" ] }, { "cell_type": "markdown", "id": "694ba24a", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "b0ff1dfd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:53:13.810332Z", "iopub.status.busy": "2025-03-25T03:53:13.810218Z", "iopub.status.idle": "2025-03-25T03:53:13.988108Z", "shell.execute_reply": "2025-03-25T03:53:13.987734Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "Found potential subseries references:\n", "!Series_relation = SuperSeries of: GSE132966\n", "!Series_relation = SuperSeries of: GSE133154\n", "!Series_relation = SuperSeries of: GSE133227\n", "!Series_relation = SuperSeries of: GSE142162\n", "!Series_relation = SuperSeries of: GSE156649\n", "!Series_relation = SuperSeries of: GSE156650\n", "!Series_relation = SuperSeries of: GSE156653\n", "!Series_relation = SuperSeries of: GSE171948\n", "\n", "Gene data extraction result:\n", "Number of rows: 19070\n", "First 20 gene/probe identifiers:\n", "Index(['100009676_at', '10000_at', '10001_at', '10002_at', '10003_at',\n", " '100048912_at', '100049716_at', '10004_at', '10005_at', '10006_at',\n", " '10007_at', '10008_at', '100093630_at', '10009_at', '1000_at',\n", " '100101467_at', '100101938_at', '10010_at', '100113407_at', '10011_at'],\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": "9700f5dc", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "46424275", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:53:13.989373Z", "iopub.status.busy": "2025-03-25T03:53:13.989267Z", "iopub.status.idle": "2025-03-25T03:53:13.991151Z", "shell.execute_reply": "2025-03-25T03:53:13.990841Z" } }, "outputs": [], "source": [ "# Analyze the gene identifiers\n", "# The format \"XXX_at\" where XXX is a numerical ID suggests these are probe identifiers\n", "# from a microarray platform (likely Affymetrix), not standard human gene symbols.\n", "# These need to be mapped to official gene symbols for biological interpretation.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "52093038", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "e40cb645", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:53:13.992259Z", "iopub.status.busy": "2025-03-25T03:53:13.992159Z", "iopub.status.idle": "2025-03-25T03:53:15.548757Z", "shell.execute_reply": "2025-03-25T03:53:15.548384Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1_at', '10_at', '100_at', '1000_at', '10000_at'], 'SPOT_ID': ['1', '10', '100', '1000', '10000'], 'Description': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'v-akt murine thymoma viral oncogene homolog 3 (protein kinase B, gamma)']}\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": "ddf97a15", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "676792eb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:53:15.550095Z", "iopub.status.busy": "2025-03-25T03:53:15.549973Z", "iopub.status.idle": "2025-03-25T03:53:15.675314Z", "shell.execute_reply": "2025-03-25T03:53:15.674940Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping info:\n", "Total number of probe-gene mappings: 19037\n", "Sample mappings (first 5 rows):\n", " ID Gene\n", "0 1_at alpha-1-B glycoprotein\n", "1 10_at N-acetyltransferase 2 (arylamine N-acetyltrans...\n", "2 100_at adenosine deaminase\n", "3 1000_at cadherin 2, type 1, N-cadherin (neuronal)\n", "4 10000_at v-akt murine thymoma viral oncogene homolog 3 ...\n", "\n", "After mapping:\n", "Number of unique genes: 2034\n", "First 5 gene symbols:\n", "Index(['A-', 'A-2', 'A-52', 'A-I', 'A-II'], dtype='object', name='Gene')\n" ] } ], "source": [ "# 1. Identify which columns in the gene annotation dataframe contain the identifiers and symbols\n", "# From the preview, we can see:\n", "# - 'ID' column contains identifiers like '1_at', matching the gene expression data format\n", "# - 'Description' column contains gene names/descriptions\n", "\n", "# 2. Extract the gene mapping dataframe with probe IDs and gene symbols\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Description')\n", "\n", "# Print info about the mapping\n", "print(\"Gene mapping info:\")\n", "print(\"Total number of probe-gene mappings:\", len(gene_mapping))\n", "print(\"Sample mappings (first 5 rows):\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping)\n", "\n", "# Print some statistics about the gene data after mapping\n", "print(\"\\nAfter mapping:\")\n", "print(\"Number of unique genes:\", len(gene_data))\n", "print(\"First 5 gene symbols:\")\n", "print(gene_data.index[:5])\n" ] }, { "cell_type": "markdown", "id": "f43cf360", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "1f5b831d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T03:53:15.676708Z", "iopub.status.busy": "2025-03-25T03:53:15.676587Z", "iopub.status.idle": "2025-03-25T03:53:18.131484Z", "shell.execute_reply": "2025-03-25T03:53:18.131171Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original gene expression data shape: (19070, 79)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Created mapping with 19037 entries\n", "Processing batch 1/20\n", "Processing batch 2/20\n", "Processing batch 3/20\n", "Processing batch 4/20\n", "Processing batch 5/20\n", "Processing batch 6/20\n", "Processing batch 7/20\n", "Processing batch 8/20\n", "Processing batch 9/20\n", "Processing batch 10/20\n", "Processing batch 11/20\n", "Processing batch 12/20\n", "Processing batch 13/20\n", "Processing batch 14/20\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Processing batch 15/20\n", "Processing batch 16/20\n", "Processing batch 17/20\n", "Processing batch 18/20\n", "Processing batch 19/20\n", "Processing batch 20/20\n", "After mapping: (4280, 79)\n", "After normalization: (1171, 79)\n", "Gene expression data saved to ../../output/preprocess/Sarcoma/gene_data/GSE133228.csv\n", "Sample IDs from gene data: 79 samples\n", "Clinical data shape: (1, 79)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Clinical data saved to ../../output/preprocess/Sarcoma/clinical_data/GSE133228.csv\n", "Selecting top 5000 genes with highest variance...\n", "Subset gene data shape: (1171, 79)\n", "Shape of linked data: (79, 1172)\n", "Handling missing values...\n", "Shape of linked data after handling missing values: (79, 1172)\n", "Checking for bias in features...\n", "Quartiles for 'Sarcoma':\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 'Sarcoma' in this dataset is severely biased.\n", "\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/media/techt/DATA/GenoAgent/tools/preprocess.py:455: FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`\n", " df[gene_cols] = df[gene_cols].fillna(df[gene_cols].mean())\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Dataset validation failed due to trait bias. Final linked data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols - let's take a more memory-efficient approach\n", "# Instead of doing all at once, process in smaller chunks\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Get fresh gene expression data\n", "gene_data = get_genetic_data(matrix_file)\n", "print(f\"Original gene expression data shape: {gene_data.shape}\")\n", "\n", "# Get the gene annotation again\n", "gene_annotation = get_gene_annotation(soft_file)\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Description')\n", "print(f\"Created mapping with {len(gene_mapping)} entries\")\n", "\n", "# Process and map in chunks to reduce memory usage\n", "batch_size = 1000\n", "num_batches = (len(gene_data) + batch_size - 1) // batch_size\n", "result_dfs = []\n", "\n", "for i in range(num_batches):\n", " print(f\"Processing batch {i+1}/{num_batches}\")\n", " start_idx = i * batch_size\n", " end_idx = min((i + 1) * batch_size, len(gene_data))\n", " \n", " # Get a subset of the expression data\n", " batch_expr = gene_data.iloc[start_idx:end_idx]\n", " \n", " # Process this batch\n", " batch_mapping = gene_mapping[gene_mapping['ID'].isin(batch_expr.index)]\n", " if len(batch_mapping) > 0:\n", " mapped_batch = apply_gene_mapping(batch_expr, batch_mapping)\n", " result_dfs.append(mapped_batch)\n", " \n", " # Clear memory\n", " del batch_expr\n", " del batch_mapping\n", "\n", "# Combine results\n", "if result_dfs:\n", " mapped_gene_data = pd.concat(result_dfs)\n", " print(f\"After mapping: {mapped_gene_data.shape}\")\n", " \n", " # Normalize gene symbols using NCBI database\n", " try:\n", " gene_data_normalized = normalize_gene_symbols_in_index(mapped_gene_data)\n", " print(f\"After normalization: {gene_data_normalized.shape}\")\n", " except Exception as e:\n", " print(f\"Error during normalization: {e}\")\n", " # Fallback to unmapped data\n", " gene_data_normalized = mapped_gene_data\n", "else:\n", " print(\"Mapping failed for all batches, using original data\")\n", " gene_data_normalized = gene_data\n", "\n", "# Save the gene data\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\"Gene expression data saved to {out_gene_data_file}\")\n", "\n", "# 2. Create clinical data with the trait information\n", "sample_ids = gene_data.columns.tolist()\n", "print(f\"Sample IDs from gene data: {len(sample_ids)} samples\")\n", "\n", "# Create a clinical dataframe with the trait (Sarcoma)\n", "clinical_df = pd.DataFrame(index=[trait], columns=sample_ids)\n", "clinical_df.loc[trait] = 1 # All samples are sarcoma tumors\n", "\n", "print(f\"Clinical data shape: {clinical_df.shape}\")\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\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data - using smaller version for efficiency\n", "# Select a subset of genes to reduce memory issues\n", "print(\"Selecting top 5000 genes with highest variance...\")\n", "if len(gene_data_normalized) > 5000:\n", " gene_variance = gene_data_normalized.var(axis=1)\n", " top_genes = gene_variance.nlargest(5000).index\n", " gene_data_subset = gene_data_normalized.loc[top_genes]\n", "else:\n", " gene_data_subset = gene_data_normalized\n", "\n", "print(f\"Subset gene data shape: {gene_data_subset.shape}\")\n", "linked_data = geo_link_clinical_genetic_data(clinical_df, gene_data_subset)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "print(\"Handling missing values...\")\n", "linked_data_cleaned = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", "\n", "# 5. Check if the trait and demographic features are biased\n", "print(\"Checking for bias in features...\")\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, trait)\n", "\n", "# 6. Validate the dataset and save cohort information\n", "note = \"Dataset contains expression data for pediatric tumors including rhabdomyosarcoma (sarcoma). All samples are tumor samples, so trait bias is expected and the dataset is not suitable for case-control analysis.\"\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,\n", " is_biased=is_trait_biased,\n", " df=unbiased_linked_data,\n", " note=note\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 trait bias. 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 }