{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "d894887e", "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 = \"Lupus_(Systemic_Lupus_Erythematosus)\"\n", "cohort = \"GSE200306\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Lupus_(Systemic_Lupus_Erythematosus)\"\n", "in_cohort_dir = \"../../input/GEO/Lupus_(Systemic_Lupus_Erythematosus)/GSE200306\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/GSE200306.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/gene_data/GSE200306.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/clinical_data/GSE200306.csv\"\n", "json_path = \"../../output/preprocess/Lupus_(Systemic_Lupus_Erythematosus)/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "c2a67e0e", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "55facdd0", "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": "6d439111", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "2f0585de", "metadata": {}, "outputs": [], "source": [ "I'll fix the syntax issues and properly handle the sample characteristics data:\n", "\n", "```python\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset does contain gene expression data\n", "# The Series_summary mentioned: \"RNA was extracted and analyzed by nanostring\" and \"574 immune transcripts were analyzed by nanostring\"\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait (Lupus Nephritis): LN class is in row 0, and there are different classes (IV, III, III/IV+V, healthy control)\n", "trait_row = 0\n", "\n", "# For gender: Sex is in row 1 (M/F)\n", "gender_row = 1\n", "\n", "# For age: Age is in row 2\n", "age_row = 2\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert lupus nephritis class to binary (0: healthy control, 1: lupus nephritis)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " value = value.lower()\n", " if \"healthy control\" in value:\n", " return 0 # Healthy control\n", " elif \"class\" in value: # Any LN class\n", " return 1 # Lupus nephritis patient\n", " return None # Unknown\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0: female, 1: male)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " value = value.lower()\n", " if \"f\" in value:\n", " return 0 # Female\n", " elif \"m\" in value and not \"f\" in value: # Ensure we're not catching \"female\"\n", " return 1 # Male\n", " return None # Unknown\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous value\"\"\"\n", " if pd.isna(value):\n", " return None\n", " # Extract numeric value after colon and whitespace\n", " try:\n", " if \":\" in value:\n", " age_str = value.split(\":\")[1].strip()\n", " return float(age_str)\n", " return float(value)\n", " except (ValueError, IndexError):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait availability\n", "is_trait_available = trait_row is not None\n", "# Initial filtering of dataset usability\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary that was provided\n", " # Each key is a row index and value is a list of characteristics\n", " sample_chars = {0: ['ln class: Class IV', 'ln class: Mixed (III/IV+V)', 'ln class: Class III', 'ln class: Healthy control'], \n", " 1: ['Sex: M', 'Sex: F', None], \n", " 2: ['age (yrs): 37', 'age (yrs): 26', 'age (yrs): 28', 'age (yrs): 32', 'age (yrs): 29', 'age (yrs): 30', 'age (yrs): 22', 'age (yrs): 27', 'age (yrs): 50', 'age (yrs): 25', 'age (yrs): 42', 'age (yrs): 18', 'age (yrs): 24', 'age (yrs): 52', 'age (yrs): 23', 'age (yrs): 35', 'age (yrs): 36', 'age (yrs): 21', 'age (yrs): 38', 'age (yrs): 45', 'age (yrs): 53', 'age (yrs): 33', None, 'age (yrs): 47', 'age (yrs): 39', 'age (yrs): 20', 'age (yrs): 31', 'age (yrs): 19'], \n", " 3: ['proteinuria (g/24hr): 2', 'proteinuria (g/24hr): 4', 'proteinuria (g/24hr): 3.5', 'proteinuria (g/24hr): 5', 'proteinuria (g/24hr): 2.4', 'proteinuria (g/24hr): 1.2', 'proteinuria (g/24hr): 6.12', 'proteinuria (g/24hr): 1.3', 'proteinuria (g/24hr): 1', 'proteinuria (g/24hr): 2.8', 'proteinuria (g/24hr): 2.2', 'proteinuria (g/24hr): 1.0', 'proteinuria (g/24hr): 1.5', 'proteinuria (g/24hr): 2.6', 'proteinuria (g/24hr): 2.0', 'proteinuria (g/24hr): 6.0', 'proteinuria (g/24hr): 1.7', 'proteinuria (g/24hr): 1.8', 'proteinuria (g/24hr): 0.9', 'proteinuria (g/24hr): 1.9', 'proteinuria (g/24hr): 5.9', 'proteinuria (g/24hr): 3.8', 'proteinuria (g/24hr): 2.3', 'proteinuria (g/24hr): 3.4', 'proteinuria (g/24hr): 0.3', 'proteinuria (g/24hr): 0.4', 'proteinuria (g/24hr): 0.1', 'proteinuria (g/24hr): 0.16', 'proteinuria (g/24hr): 0.15', 'proteinuria (g/24hr): 0.05'], \n", " 4: ['serum creatinine (mg/dl): 0.7', 'serum creatinine (mg/dl): 0.5', 'serum creatinine (mg/dl): 1.2', 'serum creatinine (mg/dl): 0.8', 'serum creatinine (mg/dl): 0.9', 'serum creatinine (mg/dl): 0.4', 'serum creatinine (mg/dl): 1.5', 'serum creatinine (mg/dl): 0.6', 'serum creatinine (mg/dl): 1.7', 'serum creatinine (mg/dl): 3.1', 'serum creatinine (mg/dl): 1.1', 'serum creatinine (mg/dl): 1.3', 'serum creatinine (mg/dl): 1.9', None, 'serum creatinine (mg/dl): 1.4', 'serum creatinine (mg/dl): 3.5', 'serum creatinine (mg/dl): 2', 'serum creatinine (mg/dl): 1.0'], \n", " 5: ['clinical response group: complete response', 'clinical response group: No Response', 'clinical response group: Partial Response', None]}\n", " \n", " # Convert the dictionary to a DataFrame suitable for geo_select_clinical_features\n", " clinical_data = pd.DataFrame(sample_chars)\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_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the resulting dataframe\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Ensure the output directory exists\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical data\n", " selected_clinical_df.to\n" ] }, { "cell_type": "markdown", "id": "720dbd52", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "2625d76d", "metadata": {}, "outputs": [], "source": [ "I'll create a corrected version of the code that handles compressed .gz files and properly processes the GEO series matrix data.\n", "\n", "```python\n", "# Analyze the data availability and type conversion for the GSE200306 cohort\n", "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "import gzip\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# First, list files in the directory to understand what's available\n", "print(\"Files in the input directory:\")\n", "for file in os.listdir(in_cohort_dir):\n", " print(f\"- {file}\")\n", "\n", "# Look for and load the series matrix file (compressed format)\n", "series_matrix_file = None\n", "for file in os.listdir(in_cohort_dir):\n", " if file.endswith(\".txt.gz\") and \"series_matrix\" in file.lower():\n", " series_matrix_file = os.path.join(in_cohort_dir, file)\n", " break\n", "\n", "if series_matrix_file:\n", " print(f\"Found series matrix file: {series_matrix_file}\")\n", " \n", " # Parse the series matrix file to extract clinical data\n", " # GEO series matrix files have a specific format with !Sample_characteristics_ch1 rows containing clinical data\n", " clinical_data_rows = []\n", " characteristic_labels = []\n", " sample_ids = []\n", " \n", " with gzip.open(series_matrix_file, 'rt', encoding='utf-8') as file:\n", " for line in file:\n", " if line.startswith('!Sample_geo_accession'):\n", " # Extract sample IDs\n", " sample_ids = line.strip().split('\\t')[1:]\n", " elif line.startswith('!Sample_characteristics_ch1'):\n", " # Extract the label if possible, otherwise use row index as identifier\n", " parts = line.strip().split('\\t')\n", " values = parts[1:]\n", " # Look for a pattern in the first value to extract label\n", " if len(values) > 0:\n", " first_value = values[0]\n", " if ':' in first_value:\n", " label = first_value.split(':', 1)[0].strip()\n", " characteristic_labels.append(label)\n", " else:\n", " characteristic_labels.append(f\"Characteristic_{len(clinical_data_rows)}\")\n", " else:\n", " characteristic_labels.append(f\"Characteristic_{len(clinical_data_rows)}\")\n", " clinical_data_rows.append(values)\n", " \n", " # Create a DataFrame from the extracted data\n", " if clinical_data_rows and sample_ids:\n", " clinical_data = pd.DataFrame(clinical_data_rows, columns=sample_ids)\n", " # Add characteristic labels as the first column\n", " clinical_data.insert(0, 'Characteristic', characteristic_labels)\n", " \n", " print(\"\\nCharacteristic labels:\")\n", " for i, label in enumerate(characteristic_labels):\n", " print(f\"{i}: {label}\")\n", " \n", " # Display unique values in each characteristic row\n", " print(\"\\nSample values for each characteristic:\")\n", " unique_values = {}\n", " for i in range(len(clinical_data)):\n", " label = clinical_data.iloc[i, 0]\n", " values = clinical_data.iloc[i, 1:].dropna().unique().tolist()\n", " if values:\n", " unique_values[i] = values\n", " print(f\"Row {i} - {label}: First 3 values: {values[:3]}\", end=\"\")\n", " if len(values) > 3:\n", " print(f\" ... ({len(values)} total unique values)\")\n", " else:\n", " print()\n", " \n", " # Based on the output, identify the relevant rows for trait, age, and gender\n", " # Example identification - adjust after seeing actual data\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", " \n", " # Look for disease state/SLE/lupus related row\n", " for i, label in enumerate(characteristic_labels):\n", " label_lower = label.lower()\n", " if any(term in label_lower for term in [\"disease\", \"diagnosis\", \"lupus\", \"sle\", \"condition\"]):\n", " if i in unique_values and len(unique_values[i]) > 1: # Ensure it has multiple values\n", " trait_row = i\n", " print(f\"\\nIdentified trait row: {i} - {label}\")\n", " print(f\"Unique values: {unique_values[i]}\")\n", " \n", " # Look for age row\n", " for i, label in enumerate(characteristic_labels):\n", " label_lower = label.lower()\n", " if \"age\" in label_lower:\n", " if i in unique_values: # Check if it has values\n", " age_row = i\n", " print(f\"\\nIdentified age row: {i} - {label}\")\n", " print(f\"Sample values: {unique_values[i][:5]}\")\n", " \n", " # Look for gender/sex row\n", " for i, label in enumerate(characteristic_labels):\n", " label_lower = label.lower()\n", " if any(term in label_lower for term in [\"gender\", \"sex\"]):\n", " if i in unique_values: # Check if it has values\n", " gender_row = i\n", " print(f\"\\nIdentified gender row: {i} - {label}\")\n", " print(f\"Unique values: {unique_values[i]}\")\n", " \n", " # For each row, verify if it's a constant feature (only one unique value)\n", " if trait_row is not None and len(unique_values[trait_row]) <= 1:\n", " print(f\"Warning: Trait row {trait_row} has only one unique value. Setting to None.\")\n", " trait_row = None\n", " \n", " if age_row is not None and len(unique_values[age_row]) <= 1:\n", " print(f\"Warning: Age row {age_row} has only one unique value. Setting to None.\")\n", " age_row = None\n", " \n", " if gender_row is not None and len(unique_values[gender_row]) <= 1:\n", " print(f\"Warning: Gender row {gender_row} has only one unique value. Setting to None.\")\n", " gender_row = None\n", " \n", "else:\n", " print(\"No series matrix file found in the directory.\")\n", " clinical_data = pd.DataFrame()\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", "\n", "# Define conversion functions based on what was observed in the data\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " value = value.lower() if isinstance(value, str) else str(value).lower()\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if any(term in value for term in [\"lupus\", \"sle\", \"patient\", \"case\", \"ln\"]):\n", " return 1\n", " elif any(term in value for term in [\"control\", \"healthy\", \"normal\", \"hc\"]):\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " value = str(value)\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Extract numeric age, handling various formats\n", " try:\n", " # Extract digits from strings like \"age: 45 years\"\n", " import re\n", " numbers = re.findall(r'\\d+\\.?\\d*', value)\n", " if numbers:\n", " return float(numbers[0])\n", " return None\n", " except:\n", " return None\n", "\n", "def convert_gender(value):\n", " if pd.isna(value):\n", " return None\n", " \n", " value = value.lower() if isinstance(value, str) else str(value).lower()\n", " \n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if any(term in value for term in [\"female\", \"f\", \"woman\", \"women\"]):\n", " return 0\n", " elif any(term in value for term in [\"male\", \"m\", \"man\", \"men\"]):\n", " return 1\n", " else:\n", " return None\n", "\n", "# Gene expression data is typically available in GEO series unless specifically indicated as something else\n", "# Set this based on description or file content analysis\n", "is_gene_available = True\n", "is_trait_available = trait_row is not None\n", "\n", "# Save metadata about cohort usability\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort\n" ] }, { "cell_type": "markdown", "id": "8711b450", "metadata": {}, "source": [ "### Step 4: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "dbf02d42", "metadata": {}, "outputs": [], "source": [ "I'll implement the correct code for the current step:\n", "\n", "```python\n", "# Dataset Analysis and Clinical Feature Extraction\n", "\n", "# Load data from the series matrix file\n", "clinical_file = os.path.join(in_cohort_dir, \"GSE200306_samples.txt\")\n", "\n", "# Check if the file exists\n", "if not os.path.exists(clinical_file):\n", " print(f\"File not found: {clinical_file}\")\n", " print(\"Looking for alternative files...\")\n", " \n", " # List files in the directory\n", " files = os.listdir(in_cohort_dir)\n", " print(f\"Files in directory: {files}\")\n", " \n", " # Try to find a file that might contain sample information\n", " potential_files = [f for f in files if 'sample' in f.lower() or 'series' in f.lower() or 'clinical' in f.lower()]\n", " if potential_files:\n", " clinical_file = os.path.join(in_cohort_dir, potential_files[0])\n", " print(f\"Using alternative file: {clinical_file}\")\n", " else:\n", " # If no specific sample file, try to use any text file\n", " txt_files = [f for f in files if f.endswith('.txt')]\n", " if txt_files:\n", " clinical_file = os.path.join(in_cohort_dir, txt_files[0])\n", " print(f\"Using text file: {clinical_file}\")\n", "\n", "# Read the file and parse\n", "clinical_data = {}\n", "try:\n", " with open(clinical_file, 'r') as f:\n", " lines = f.readlines()\n", " \n", " sample_ids = None\n", " \n", " for i, line in enumerate(lines):\n", " if line.startswith('!Sample_'):\n", " parts = line.strip().split('\\t')\n", " key = parts[0]\n", " values = parts[1:]\n", " \n", " if key == '!Sample_geo_accession':\n", " sample_ids = values\n", " \n", " # Store the data with line number as key\n", " clinical_data[i] = (key, values)\n", " \n", " # Convert to DataFrame for easier processing\n", " df_data = {}\n", " for i, (key, values) in clinical_data.items():\n", " label = key.replace('!Sample_', '')\n", " df_data[i] = {sample_ids[j]: values[j] for j in range(len(sample_ids))} if sample_ids else values\n", " \n", " clinical_df = pd.DataFrame.from_dict(df_data, orient='index')\n", " \n", " print(\"Clinical data loaded successfully\")\n", " print(f\"DataFrame shape: {clinical_df.shape}\")\n", " print(\"First few rows:\")\n", " print(clinical_df.head(2))\n", " \n", " # Print unique values for rows that might contain trait, age or gender info\n", " for i in clinical_df.index:\n", " row_name = clinical_data.get(i, ('Unknown', []))[0]\n", " if 'characteristics' in row_name or 'title' in row_name or 'source' in row_name:\n", " unique_vals = set(str(v) for v in clinical_df.iloc[i].values)\n", " if len(unique_vals) < 20: # Only show if not too many unique values\n", " print(f\"Row {i} - {row_name}: {unique_vals}\")\n", " \n", "except Exception as e:\n", " print(f\"Error reading clinical data: {e}\")\n", " clinical_df = pd.DataFrame() # Empty DataFrame as fallback\n", "\n", "# 1. Gene Expression Data Availability\n", "# Check if this dataset contains gene expression data\n", "files_in_dir = os.listdir(in_cohort_dir)\n", "is_gene_available = any('expr' in f.lower() for f in files_in_dir) or any('gene' in f.lower() for f in files_in_dir)\n", "\n", "if not is_gene_available:\n", " # Look for other indicators of gene expression data\n", " for file in files_in_dir:\n", " if file.endswith('.txt') or file.endswith('.csv'):\n", " try:\n", " with open(os.path.join(in_cohort_dir, file), 'r') as f:\n", " first_few_lines = ''.join(f.readline() for _ in range(10))\n", " if 'gene' in first_few_lines.lower() or 'probe' in first_few_lines.lower() or 'transcript' in first_few_lines.lower():\n", " is_gene_available = True\n", " break\n", " except:\n", " pass\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# For trait (SLE status)\n", "trait_row = None\n", "# Look for potential trait rows\n", "for i in clinical_df.index:\n", " row_values = [str(v).lower() for v in clinical_df.iloc[i].values]\n", " if any('lupus' in v or 'sle' in v or 'disease' in v or 'diagnosis' in v or 'status' in v or 'patient' in v for v in row_values):\n", " trait_row = i\n", " break\n", "\n", "def convert_trait(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: 1 for SLE/lupus, 0 for control/healthy\n", " if any(term in value for term in ['sle', 'lupus', 'patient', 'disease', 'case']):\n", " return 1\n", " elif any(term in value for term in ['control', 'healthy', 'normal', 'hc']):\n", " return 0\n", " return None\n", "\n", "# For age\n", "age_row = None\n", "for i in clinical_df.index:\n", " row_values = [str(v).lower() for v in clinical_df.iloc[i].values]\n", " if any('age' in v for v in row_values):\n", " age_row = i\n", " break\n", "\n", "def convert_age(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to extract age as a number\n", " import re\n", " age_match = re.search(r'(\\d+)(?:\\s*years?|\\s*y\\.o\\.|\\s*yo)?', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " return None\n", "\n", "# For gender\n", "gender_row = None\n", "for i in clinical_df.index:\n", " row_values = [str(v).lower() for v in clinical_df.iloc[i].values]\n", " if any(term in ' '.join(row_values) for term in ['gender', 'sex', 'male', 'female']):\n", " gender_row = i\n", " break\n", "\n", "def convert_gender(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " \n", " value = str(value).lower()\n", " # Extract the value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: 0 for female, 1 for male\n", " if any(term in value for term in ['female', 'f']):\n", " return 0\n", " elif any(term in value for term in ['male', 'm']):\n", " return 1\n", " return None\n", "\n", "# Print the identified rows\n", "print(f\"Identified trait row: {trait_row}\")\n", "print(f\"Identified age row: {age_row}\")\n", "print(f\"Identified gender row: {gender_row}\")\n", "\n", "# 3. Save Metadata\n", "is_trait_available = trait_row is not None\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if is_trait_available:\n", " # Use the library function to select and process clinical features\n", " try:\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_\n" ] }, { "cell_type": "markdown", "id": "34d032d5", "metadata": {}, "source": [ "### Step 5: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "4fef3a0d", "metadata": {}, "outputs": [], "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. Use the get_genetic_data function from the library to get the gene_data from the matrix_file\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(\"First 20 gene/probe identifiers:\")\n", "print(gene_data.index[:20])\n" ] }, { "cell_type": "markdown", "id": "e40bb65c", "metadata": {}, "source": [ "### Step 6: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "56546802", "metadata": {}, "outputs": [], "source": [ "# Analyzing the gene identifiers in the gene expression data\n", "# These are known human gene symbols (e.g., ABCB1 = ATP Binding Cassette Subfamily B Member 1,\n", "# ABL1 = ABL Proto-Oncogene 1, ADA = Adenosine Deaminase, etc.)\n", "# They appear to be official gene symbols and not probe IDs or other identifiers\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "bdb90d89", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "ff77fa93", "metadata": {}, "outputs": [], "source": [ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n", "# Save to the gene data file\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\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Link the clinical and genetic data\n", "# Need to load the saved clinical data\n", "clinical_features = pd.read_csv(out_clinical_data_file)\n", "\n", "# Print clinical_features structure to debug\n", "print(f\"Clinical features columns: {clinical_features.columns.tolist()}\")\n", "print(f\"Clinical features shape: {clinical_features.shape}\")\n", "\n", "# Convert clinical features to the correct format for linking\n", "# First, we need to set the appropriate index\n", "if 'Unnamed: 0' in clinical_features.columns:\n", " clinical_features = clinical_features.set_index('Unnamed: 0')\n", "\n", "# Create a new DataFrame with the trait name as Lung_Cancer for clarity\n", "trait_row = clinical_features.iloc[0].rename(trait)\n", "age_row = clinical_features.iloc[1].rename('Age') if len(clinical_features) > 1 else None\n", "gender_row = clinical_features.iloc[2].rename('Gender') if len(clinical_features) > 2 else None\n", "\n", "# Combine rows into a new clinical dataframe with proper naming\n", "clinical_df_rows = [trait_row]\n", "if age_row is not None:\n", " clinical_df_rows.append(age_row)\n", "if gender_row is not None:\n", " clinical_df_rows.append(gender_row)\n", "\n", "named_clinical_df = pd.DataFrame(clinical_df_rows)\n", "print(f\"Named clinical dataframe shape: {named_clinical_df.shape}\")\n", "print(f\"Named clinical dataframe index: {named_clinical_df.index.tolist()}\")\n", "\n", "# Link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(named_clinical_df, normalized_gene_data)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "print(f\"First few columns in linked_data: {linked_data.columns[:10].tolist()}\")\n", "\n", "# Check if the trait column exists in the dataframe\n", "if trait not in linked_data.columns:\n", " print(f\"Warning: '{trait}' column not found in linked data. Available columns: {linked_data.columns[:20].tolist()}\")\n", "\n", "# 3. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after handling missing values: {linked_data.shape}\")\n", "\n", "# 4. Determine whether the trait and demographic features are biased, and remove biased features\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=\"Dataset contains gene expression from olfactory neuroblastoma patients relevant to lung cancer research\"\n", ")\n", "\n", "# 6. If the linked data is usable, save it as a CSV file\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. Data not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }