{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "91ddd6cc", "metadata": {}, "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 = \"Rectal_Cancer\"\n", "cohort = \"GSE40492\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Rectal_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Rectal_Cancer/GSE40492\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Rectal_Cancer/GSE40492.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Rectal_Cancer/gene_data/GSE40492.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Rectal_Cancer/clinical_data/GSE40492.csv\"\n", "json_path = \"../../output/preprocess/Rectal_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f4ceeee5", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "8260aad4", "metadata": {}, "outputs": [], "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": "72982944", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "5c0e4ade", "metadata": {}, "outputs": [], "source": [ "I analyzed the patient data for this rectal cancer dataset. The corrections focus on properly handling the clinical data without relying on a pre-existing CSV file.\n", "\n", "```python\n", "# 1. Gene Expression Data Availability\n", "# Based on the background info, this dataset contains gene expression data for rectal cancer patients.\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Rectal Cancer)\n", "# Looking at the clinical features, we can use pathological lymph node status after treatment\n", "# From row 9: 'pathological lymphnode status after neoadjuvant treatment and surgery (0,1,2 - according to uicc tnm classification)'\n", "trait_row = 9\n", "\n", "# For age\n", "# Age is available in row 1\n", "age_row = 1\n", "\n", "# For gender\n", "# Gender is available in row 2 as 'Sex'\n", "gender_row = 2\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value_str):\n", " \"\"\"Convert lymph node status to binary value.\n", " 0 = No positive lymph nodes, 1 = Positive lymph nodes\"\"\"\n", " if value_str is None or 'NA' in value_str:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value_str:\n", " value = value_str.split(':', 1)[1].strip()\n", " else:\n", " value = value_str.strip()\n", " \n", " # Status 0 means no positive lymph nodes\n", " if value == '0':\n", " return 0\n", " # Status 1 or 2 means positive lymph nodes\n", " elif value in ['1', '2']:\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value_str):\n", " \"\"\"Convert age to continuous value.\"\"\"\n", " if value_str is None or 'NA' in value_str:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value_str:\n", " value = value_str.split(':', 1)[1].strip()\n", " else:\n", " value = value_str.strip()\n", " \n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value_str):\n", " \"\"\"Convert gender to binary value. 0 = female, 1 = male\"\"\"\n", " if value_str is None or 'NA' in value_str:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value_str:\n", " value = value_str.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value_str.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", "# 3. Save Metadata\n", "is_trait_available = trait_row is not None\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "# We'll proceed only if trait_row is not None\n", "if trait_row is not None:\n", " # Create the clinical data DataFrame from the sample characteristics dictionary\n", " sample_chars_dict = {0: ['dataset: Training', 'dataset: Validation'], 1: ['age: 55.5', 'age: 65.6', 'age: 62.6', 'age: 61.8', 'age: 52.1', 'age: 59.1', 'age: 70.6', 'age: 60.6', 'age: 55', 'age: 53.1', 'age: 58.5', 'age: 68.4', 'age: 58.8', 'age: 70', 'age: 77.5', 'age: 75.2', 'age: 76.3', 'age: 38.2', 'age: 61.1', 'age: 69.4', 'age: 54.2', 'age: 77.7', 'age: 57.4', 'age: 61.2', 'age: 56.5', 'age: 47', 'age: 62.7', 'age: 51.2', 'age: 73.2', 'age: 47.2'], 2: ['Sex: female', 'Sex: male'], 3: ['therapy: 5-FU + Oxaliplatin + RT', 'therapy: 5-FU + RT'], 4: ['surgery type: deep anterior resection (TAbdominoperineal resection (APR))', 'surgery type: Other', 'surgery type: Abdominoperineal excision (APE)', 'surgery type: NA', 'surgery type: Abdominoperineal resection (APR)'], 5: ['clinical tumor category (0,i,ii,iii,iv - according to uicc tnm classification): 3', 'clinical tumor category (0,i,ii,iii,iv - according to uicc tnm classification): 2', 'clinical tumor category (0,i,ii,iii,iv - according to uicc tnm classification): NA', 'clinical tumor category (0,i,ii,iii,iv - according to uicc tnm classification): 4'], 6: ['clinical lymphnode status (0,1 - according to uicc tnm classification): 1', 'clinical lymphnode status (0,1 - according to uicc tnm classification): 0', 'clinical lymphnode status (0,1 - according to uicc tnm classification): NA'], 7: ['clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): IV', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): III', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): II', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): III A', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): III B', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): II A', 'clinical tumor stage (0,i,ii,iii,iv - according to uicc tnm classification): III C'], 8: ['pathological tumor category after neoadjuvant treatment and surgery (0,i,ii,iii,iv - according to uicc tnm classification): 3', 'pathological tumor category after neoadjuvant treatment and surgery (0,i,ii,iii,iv - according to uicc tnm classification): 0', 'pathological tumor category after neoadjuvant treatment and surgery (0,i,ii,iii,iv - according to uicc tnm classification): 2', 'pathological tumor category after neoadjuvant treatment and surgery (0,i,ii,iii,iv - according to uicc tnm classification): 4', 'pathological tumor category after neoadjuvant treatment and surgery (0,i,ii,iii,iv - according to uicc tnm classification): 1'], 9: ['pathological lymphnode status after neoadjuvant treatment and surgery (0,1,2 - according to uicc tnm classification): 1', 'pathological lymphnode status after neoadjuvant treatment and surgery (0,1,2 - according to uicc tnm classification): 0', 'pathological lymphnode status after neoadjuvant treatment and surgery (0,1,2 - according to uicc tnm classification): 2']}\n", "\n", " # Convert the sample characteristics dictionary to a DataFrame\n", " clinical_data = pd.DataFrame.from_dict(sample_chars_dict, orient='index')\n", " \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\n" ] }, { "cell_type": "markdown", "id": "e4c22109", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "199b6cfa", "metadata": {}, "outputs": [], "source": [ "I'll analyze the dataset and extract the clinical features as requested:\n", "\n", "```python\n", "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "import gzip\n", "import re\n", "\n", "# Let's first look at what files we have in the cohort directory to understand the dataset\n", "print(f\"Files in {in_cohort_dir}:\")\n", "for file in os.listdir(in_cohort_dir):\n", " print(f\"- {file}\")\n", "\n", "# Function to extract sample characteristics from series matrix file\n", "def extract_sample_characteristics(file_path):\n", " sample_char_dict = {}\n", " current_row = None\n", " \n", " with gzip.open(file_path, 'rt') as f:\n", " lines = []\n", " in_char_section = False\n", " samples = []\n", " \n", " for line in f:\n", " if line.startswith('!Sample_geo_accession'):\n", " samples = line.strip().split('\\t')[1:]\n", " \n", " elif line.startswith('!Sample_characteristics_ch1'):\n", " if not in_char_section:\n", " in_char_section = True\n", " \n", " parts = line.strip().split('\\t')\n", " char_value = parts[0].split('!Sample_characteristics_ch1')[1].strip()\n", " if char_value: # If there's a label in the line\n", " current_row = len(sample_char_dict)\n", " sample_char_dict[current_row] = {'label': char_value, 'values': parts[1:]}\n", " else: # If it's a continuation line\n", " if current_row is not None:\n", " sample_char_dict[current_row]['values'].extend(parts[1:])\n", " \n", " elif in_char_section and not line.startswith('!Sample_'):\n", " in_char_section = False\n", " \n", " # Check for data type description\n", " if line.startswith('!Series_summary'):\n", " lines.append(line)\n", " if line.startswith('!Series_title'):\n", " lines.append(line)\n", " if line.startswith('!Series_overall_design'):\n", " lines.append(line)\n", " \n", " # Create DataFrame from the dictionary\n", " df_columns = samples\n", " df_index = list(range(len(sample_char_dict)))\n", " df = pd.DataFrame(index=df_index, columns=df_columns)\n", " \n", " for row_idx, row_data in sample_char_dict.items():\n", " for col_idx, value in enumerate(row_data['values']):\n", " if col_idx < len(df_columns):\n", " df.iloc[row_idx, col_idx] = value\n", " \n", " return df, lines\n", "\n", "# Load the matrix file to check if gene expression data is available\n", "matrix_file = os.path.join(in_cohort_dir, \"GSE40492_series_matrix.txt.gz\")\n", "is_gene_available = False\n", "clinical_data = None\n", "background_info = []\n", "\n", "if os.path.exists(matrix_file):\n", " # Extract sample characteristics from the matrix file\n", " clinical_data, background_info = extract_sample_characteristics(matrix_file)\n", " \n", " # Check for gene expression data by reading the first few lines of the file\n", " with gzip.open(matrix_file, 'rt') as f:\n", " # Skip header lines\n", " for line in f:\n", " if line.startswith('!series_matrix_table_begin'):\n", " break\n", " \n", " # Read column headers (should be sample IDs)\n", " header = next(f)\n", " \n", " # Check a few data rows to see if they contain gene expression data\n", " for _ in range(5):\n", " line = next(f)\n", " # If the line contains gene IDs and numeric values, it's likely gene expression data\n", " if re.match(r'^[A-Za-z0-9_-]+\\t[-+]?[0-9]*\\.?[0-9]+', line):\n", " is_gene_available = True\n", " break\n", "\n", "# Print background information\n", "print(\"\\nBackground information:\")\n", "for line in background_info:\n", " print(line.strip())\n", "\n", "# Print sample characteristics if available\n", "if clinical_data is not None:\n", " print(\"\\nSample characteristics shape:\", clinical_data.shape)\n", " print(\"\\nSample characteristics preview:\")\n", " print(clinical_data.head(3))\n", " \n", " # Print unique values for each row to identify clinical features\n", " for i in range(len(clinical_data)):\n", " unique_values = clinical_data.iloc[i].unique()\n", " print(f\"\\nRow {i}: {len(unique_values)} unique values:\")\n", " print(unique_values[:10])\n", "\n", "# Based on the data exploration, determine clinical features\n", "# For trait (Rectal Cancer - looking for response status)\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Scan through the rows to find relevant clinical features\n", "if clinical_data is not None:\n", " for i in range(len(clinical_data)):\n", " row_values = [str(val).lower() for val in clinical_data.iloc[i] if not pd.isna(val)]\n", " row_text = ' '.join(row_values)\n", " \n", " # Check for response information (trait)\n", " if any('responder' in val for val in row_values):\n", " trait_row = i\n", " \n", " # Check for age information\n", " if any('age' in val for val in row_values):\n", " age_row = i\n", " \n", " # Check for gender/sex information\n", " if any(gender_term in row_text for gender_term in ['gender', 'sex', 'male', 'female']):\n", " gender_row = i\n", "\n", "print(f\"\\nIdentified rows - trait: {trait_row}, age: {age_row}, gender: {gender_row}\")\n", "\n", "# Define conversion functions for clinical features\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " value = str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if 'responder' in value:\n", " return 1 # Responder\n", " elif 'non-responder' in value:\n", " return 0 # Non-responder\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value):\n", " return None\n", " value = str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " # Try to extract numeric age\n", " match = re.search(r'(\\d+)', value)\n", " if match:\n", " return float(match.group(1))\n", " return None\n", "\n", "def convert_gender(value):\n", " if pd.isna(value):\n", " return None\n", " value = str(value).lower()\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if any(female_term in value for female_term in ['female', 'f', 'woman']):\n", " return 0\n", " elif any(male_term in value for male_term in ['male', 'm', 'man']):\n", " return 1\n", " else:\n", " return None\n", "\n", "# Validate and save cohort info\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", "# Extract clinical features if trait data is available\n", "if trait_row is not None and clinical_data is not None:\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", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted clinical features\n", " print(\"\\nExtracted clinical features preview:\")\n", " preview = preview_df(clinical_features)\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save clinical features to CSV\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"\\nClinical\n" ] }, { "cell_type": "markdown", "id": "394abeb6", "metadata": {}, "source": [ "### Step 4: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "59183ede", "metadata": {}, "outputs": [], "source": [ "# 1. First get the file paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# 3. Print the first 20 row IDs (gene or probe identifiers) for future observation\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "faaf9393", "metadata": {}, "source": [ "### Step 5: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "390e74e8", "metadata": {}, "outputs": [], "source": [ "# Examining the gene identifiers revealed numeric values ('12', '13', '14', etc.)\n", "# These are clearly not standard human gene symbols (which would be alphanumeric like BRCA1, TP53, etc.)\n", "# These appear to be probe or array identifiers that will need to be mapped to proper gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "cf97a7be", "metadata": {}, "source": [ "### Step 6: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "efc22ded", "metadata": {}, "outputs": [], "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": "762d35e2", "metadata": {}, "source": [ "### Step 7: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "9ef11ef6", "metadata": {}, "outputs": [], "source": [ "# 1. Determine which columns in gene_annotation contain probe IDs and gene symbols\n", "# Looking at the gene_annotation preview, the 'ID' column contains numeric identifiers similar to \n", "# the gene_data index. For gene symbols, the 'GENE_SYMBOL' column appears to be the appropriate one.\n", "prob_col = 'ID'\n", "gene_col = 'GENE_SYMBOL'\n", "\n", "# 2. Get gene mapping dataframe with the two columns\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# 3. Convert probe-level measurements to gene-level expression data\n", "# The apply_gene_mapping function splits probe signals equally among mapped genes\n", "# and then sums up contributions to each gene\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Let's check the first few rows of the mapped gene data to verify the transformation\n", "print(\"Gene expression data after mapping to gene symbols:\")\n", "print(gene_data.head())\n", "print(f\"Shape of gene expression data: {gene_data.shape}\")\n" ] }, { "cell_type": "markdown", "id": "a91e5ce9", "metadata": {}, "source": [ "### Step 8: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "b5324b32", "metadata": {}, "outputs": [], "source": [ "# First, we need to re-establish all the required variables and data from previous steps\n", "\n", "# 1. Get file paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Get background info and clinical data\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "\n", "# 3. Define the necessary row indices based on analysis of clinical data\n", "# From the sample characteristics dictionary, we can determine:\n", "# Trait: pathological lymph node status is at row 9\n", "# Age: age information is at row 1\n", "# Gender: sex information is at row 2\n", "trait_row = 9\n", "age_row = 1\n", "gender_row = 2\n", "\n", "# 4. Define conversion functions for clinical features\n", "def convert_trait(value_str):\n", " \"\"\"Convert lymph node status to binary value.\n", " 0 = No positive lymph nodes, 1 = Positive lymph nodes\"\"\"\n", " if value_str is None or 'NA' in value_str:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value_str:\n", " value = value_str.split(':', 1)[1].strip()\n", " else:\n", " value = value_str.strip()\n", " \n", " # Status 0 means no positive lymph nodes\n", " if value == '0':\n", " return 0\n", " # Status 1 or 2 means positive lymph nodes\n", " elif value in ['1', '2']:\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value_str):\n", " \"\"\"Convert age to continuous value.\"\"\"\n", " if value_str is None or 'NA' in value_str:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value_str:\n", " value = value_str.split(':', 1)[1].strip()\n", " else:\n", " value = value_str.strip()\n", " \n", " try:\n", " return float(value)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value_str):\n", " \"\"\"Convert gender to binary value. 0 = female, 1 = male\"\"\"\n", " if value_str is None or 'NA' in value_str:\n", " return None\n", " \n", " # Extract the value after the colon\n", " if ':' in value_str:\n", " value = value_str.split(':', 1)[1].strip().lower()\n", " else:\n", " value = value_str.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", "# Reload the gene expression data from the matrix file\n", "gene_data = get_genetic_data(matrix_file)\n", "\n", "# Get gene annotation data\n", "gene_annotation = get_gene_annotation(soft_file)\n", "prob_col = 'ID'\n", "gene_col = 'GENE_SYMBOL'\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# Apply gene mapping to convert probe-level data to gene-level\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "\n", "# Now proceed with the data normalization and linking steps\n", "\n", "# 1. Extract clinical features\n", "clinical_features = geo_select_clinical_features(\n", " 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", "# Save the clinical features 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", "\n", "# Normalize gene symbols in the gene expression data\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Normalized gene data shape: {normalized_gene_data.shape}\")\n", "print(f\"First few normalized gene symbols: {list(normalized_gene_data.index[:10])}\")\n", "\n", "# Save the normalized gene data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# 2. Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(linked_data.head())\n", "\n", "# 3. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Determine whether the trait and demographic features are severely biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. Conduct quality check and save the 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,\n", " is_biased=is_trait_biased, \n", " df=unbiased_linked_data,\n", " note=f\"Dataset contains rectal cancer patients with clinical annotations including pathological lymph node status.\"\n", ")\n", "\n", "# 6. Save the data if it's usable\n", "if is_usable:\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " # Save the data\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(f\"Data quality check failed. The dataset is not suitable for association studies.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }