{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "f4a7253c", "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 = \"Melanoma\"\n", "cohort = \"GSE215868\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Melanoma\"\n", "in_cohort_dir = \"../../input/GEO/Melanoma/GSE215868\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Melanoma/GSE215868.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Melanoma/gene_data/GSE215868.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Melanoma/clinical_data/GSE215868.csv\"\n", "json_path = \"../../output/preprocess/Melanoma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "13a82d94", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "b22e0d21", "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": "0129cabe", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "394ea7b3", "metadata": {}, "outputs": [], "source": [ "I've analyzed the issue and will provide a corrected version that properly structures the sample characteristics for the `geo_select_clinical_features` function.\n", "\n", "```python\n", "import pandas as pd\n", "import numpy as np\n", "import os\n", "import re\n", "from typing import Optional, Dict, Any, Callable\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on series title and summary, this appears to be gene expression data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# For trait: We're looking for melanoma indicator. \"long-term benefit\" in row 4\n", "trait_row = 4 # \"long-term benefit\" represents melanoma therapy outcome\n", "# For age: Available in row 0\n", "age_row = 0\n", "# For gender: Not available in the sample characteristics dictionary\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " # Extract the value after the colon\n", " match = re.search(r'long-term benefit:\\s*(.*)', value)\n", " if match:\n", " # Convert to binary: YES=1, NO=0\n", " trait_value = match.group(1).strip()\n", " if trait_value == \"YES\":\n", " return 1\n", " elif trait_value == \"NO\":\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value):\n", " return None\n", " # Extract age value after the colon\n", " match = re.search(r'age:\\s*(\\d+)', value)\n", " if match:\n", " return int(match.group(1))\n", " return None\n", "\n", "def convert_gender(value):\n", " # Function defined but not used as gender data is not available\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Initial filtering on 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=trait_row is not None\n", ")\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Since we don't have direct access to clinical_data.csv, we need to create a DataFrame\n", " # that matches the expected structure for geo_select_clinical_features\n", " \n", " # Create a DataFrame where each row is a feature type and each column will be a sample\n", " # This matches the expected structure for geo_select_clinical_features\n", " \n", " # Sample characteristics dictionary from the previous step\n", " sample_chars = {\n", " 0: ['age: 71', 'age: 59', 'age: 63', 'age: 44', 'age: 56', 'age: 58', 'age: 74', 'age: 51', 'age: 76', 'age: 16', 'age: 72', 'age: 73', 'age: 34', 'age: 64', 'age: 68', 'age: 36', 'age: 52', 'age: 54', 'age: 85', 'age: 82', 'age: 46', 'age: 69', 'age: 40', 'age: 75', 'age: 86', 'age: 50', 'age: 77', 'age: 88', 'age: 38', 'age: 61'],\n", " 1: ['bor: CR', 'bor: SD', 'bor: PR', 'bor: PD', 'bor: UK'],\n", " 2: ['pfs_days: 270', 'pfs_days: 588', 'pfs_days: 308', 'pfs_days: 942', 'pfs_days: 85', 'pfs_days: 351', 'pfs_days: 81', 'pfs_days: 932', 'pfs_days: 979', 'pfs_days: 685', 'pfs_days: 204', 'pfs_days: 16', 'pfs_days: 80', 'pfs_days: 652', 'pfs_days: 407', 'pfs_days: 1887', 'pfs_days: 36', 'pfs_days: 141', 'pfs_days: 153', 'pfs_days: 341', 'pfs_days: 1102', 'pfs_days: 96', 'pfs_days: 916', 'pfs_days: 62', 'pfs_days: 761', 'pfs_days: 136', 'pfs_days: 217', 'pfs_days: 102', 'pfs_days: 1552', 'pfs_days: 61'],\n", " 3: ['pfs_index: 0', 'pfs_index: 1'],\n", " 4: ['os_days: 350', 'long-term benefit: NO', 'long-term benefit: YES', 'os_days: 688', 'os_days: 377', 'os_days: 1833', 'os_days: 574', 'os_days: 446', 'os_days: 474', 'os_days: 415', 'os_days: 528', 'os_days: 605', 'os_days: 449', 'os_days: 259', 'os_days: 291', 'os_days: 376', 'os_days: 266', 'os_days: 123', 'os_days: 28', 'os_days: 301', 'os_days: 669'],\n", " 5: ['os_index: 0', 'os_days: 1048', 'os_days: 911', 'os_days: 1354', 'os_days: 377', 'os_days: 514', 'os_days: 446', 'os_days: 959', 'os_days: 980', 'os_days: 418', 'os_days: 309', 'os_days: 678', 'os_days: 1010', 'os_days: 636', 'os_days: 1890', 'os_days: 238', 'os_days: 240', 'os_days: 681', 'os_days: 1169', 'os_days: 1037', 'os_days: 917', 'os_days: 200', 'os_days: 772', 'os_days: 160', 'os_days: 510', 'os_days: 1555', 'os_days: 128', 'os_days: 353', 'os_days: 229', 'os_days: 105'],\n", " 6: ['itx: PEMBRO', 'os_index: 0', 'os_index: 1', 'itx: IPI+NIVO', 'itx: NIVO'],\n", " 7: ['prior checkpoint blockade: NO', 'itx: PEMBRO', 'itx: NIVO', 'itx: IPI+NIVO', 'prior checkpoint blockade: YES', 'itx: NIVO+EXPERIMENTAL', 'itx: Pembro'],\n", " 8: [np.nan, 'prior checkpoint blockade: YES', 'prior checkpoint blockade: NO']\n", " }\n", " \n", " # This appears to be a dictionary where keys are row indices and values are lists of characteristics\n", " # geo_select_clinical_features is expecting a DataFrame where rows are these characteristics\n", " clinical_data = pd.DataFrame(index=sample_chars.keys())\n", " \n", " # Extract clinical features using geo_select_clinical_features\n", " clinical_features = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " 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(clinical_features)\n", " print(\"Clinical Features Preview:\")\n", " print(preview)\n", " \n", " # Save clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file),\n" ] }, { "cell_type": "markdown", "id": "ca458376", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "6c2728b9", "metadata": {}, "outputs": [], "source": [ "I understand the issue now - we need to handle the gzipped series matrix file properly. I'll implement the correct approach to extract the clinical features:\n", "\n", "```python\n", "import os\n", "import pandas as pd\n", "import json\n", "import numpy as np\n", "import gzip\n", "import re\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# First, let's check what files are available in the cohort directory\n", "print(f\"Checking files in {in_cohort_dir}\")\n", "available_files = os.listdir(in_cohort_dir)\n", "print(f\"Available files: {available_files}\")\n", "\n", "# Load the series matrix file which contains sample characteristics\n", "matrix_files = [f for f in available_files if \"series_matrix\" in f.lower()]\n", "if matrix_files:\n", " matrix_file_path = os.path.join(in_cohort_dir, matrix_files[0])\n", " print(f\"Loading series matrix file: {matrix_file_path}\")\n", " \n", " # Read the gzipped matrix file\n", " with gzip.open(matrix_file_path, 'rt') as file:\n", " lines = file.readlines()\n", " \n", " # Extract sample characteristics and organize by type\n", " char_types = {}\n", " current_samples = []\n", " \n", " for line in lines:\n", " if line.startswith(\"!Sample_characteristics_ch1\"):\n", " parts = line.strip().split('\\t')\n", " if len(parts) > 1:\n", " # Extract the characteristic value for each sample\n", " char_value = parts[1]\n", " if \":\" in char_value:\n", " char_type, value = char_value.split(\":\", 1)\n", " char_type = char_type.strip()\n", " if char_type not in char_types:\n", " char_types[char_type] = []\n", " char_types[char_type].append(value.strip())\n", " else:\n", " # Handle case where there's no colon separator\n", " if \"uncategorized\" not in char_types:\n", " char_types[\"uncategorized\"] = []\n", " char_types[\"uncategorized\"].append(char_value)\n", " \n", " # Get sample identifiers\n", " elif line.startswith(\"!Sample_geo_accession\"):\n", " parts = line.strip().split('\\t')\n", " if len(parts) > 1:\n", " current_samples = parts[1:]\n", " \n", " # Print discovered characteristic types\n", " print(\"Discovered characteristic types:\")\n", " for char_type, values in char_types.items():\n", " unique_values = set(values)\n", " print(f\"Type: {char_type}\")\n", " print(f\"Unique values: {unique_values}\")\n", " print(f\"Count: {len(values)}\")\n", " print()\n", " \n", " # Create a DataFrame for characteristics\n", " clinical_data = pd.DataFrame(index=current_samples)\n", " for char_type, values in char_types.items():\n", " if len(values) == len(current_samples):\n", " clinical_data[char_type] = values\n", " \n", " # Transpose for the format expected by geo_select_clinical_features\n", " clinical_data = clinical_data.T.reset_index()\n", " clinical_data.columns = ['characteristic'] + list(clinical_data.columns[1:])\n", " \n", " print(\"Clinical data preview:\")\n", " print(clinical_data.head())\n", " \n", " # Determine feature availability based on the data\n", " # Let's examine characteristics to find trait, age and gender information\n", " is_gene_available = True # Assuming this dataset contains gene expression data\n", " \n", " # These will be set based on examining the actual data\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", " \n", " # Look for trait-related information (melanoma)\n", " for i, char_type in enumerate(clinical_data['characteristic']):\n", " char_type_lower = str(char_type).lower()\n", " # Search for trait information\n", " if 'disease' in char_type_lower or 'diagnosis' in char_type_lower or 'melanoma' in char_type_lower or 'tumor' in char_type_lower or 'cancer' in char_type_lower or 'status' in char_type_lower:\n", " # Check if there are at least two unique values (not constant)\n", " unique_vals = clinical_data.iloc[i, 1:].nunique()\n", " if unique_vals > 1:\n", " trait_row = i\n", " print(f\"Found trait information in row {i}: {char_type}\")\n", " print(f\"Unique values: {clinical_data.iloc[i, 1:].unique()}\")\n", " \n", " # Search for age information\n", " elif 'age' in char_type_lower:\n", " # Check if there are multiple unique values\n", " unique_vals = clinical_data.iloc[i, 1:].nunique()\n", " if unique_vals > 1:\n", " age_row = i\n", " print(f\"Found age information in row {i}: {char_type}\")\n", " print(f\"Unique values: {clinical_data.iloc[i, 1:].unique()[:5]}\") # Show first 5 unique values\n", " \n", " # Search for gender information\n", " elif 'gender' in char_type_lower or 'sex' in char_type_lower:\n", " # Check if there are at least two unique values\n", " unique_vals = clinical_data.iloc[i, 1:].nunique()\n", " if unique_vals > 1:\n", " gender_row = i\n", " print(f\"Found gender information in row {i}: {char_type}\")\n", " print(f\"Unique values: {clinical_data.iloc[i, 1:].unique()}\")\n", " \n", " # Define conversion functions\n", " def convert_trait(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " value = str(value).strip().lower()\n", " \n", " # Convert to binary based on melanoma context\n", " if any(term in value for term in ['melanoma', 'tumor', 'cancer', 'malignant']):\n", " return 1\n", " elif any(term in value for term in ['normal', 'control', 'healthy', 'benign']):\n", " return 0\n", " else:\n", " return None\n", " \n", " def convert_age(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " value = str(value).strip()\n", " \n", " # Extract numeric age\n", " try:\n", " # Find numbers in the string\n", " age_match = re.search(r'(\\d+)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " else:\n", " return None\n", " except:\n", " return None\n", " \n", " def convert_gender(value):\n", " if pd.isna(value) or value is None:\n", " return None\n", " value = str(value).strip().lower()\n", " \n", " # Convert gender to binary (female=0, male=1)\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", " else:\n", " return None\n", " \n", " # Determine if trait data is available\n", " is_trait_available = trait_row is not None\n", " \n", " # 3. Save Metadata - 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 (if trait data is available)\n", " if trait_row is not None:\n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " # Preview the results\n", " print(\"Selected clinical features preview:\")\n", " preview = preview_df(selected_clinical_df)\n", " print(preview)\n", " \n", " # Save to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_\n" ] }, { "cell_type": "markdown", "id": "45a7e8aa", "metadata": {}, "source": [ "### Step 4: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "78dfd3bc", "metadata": {}, "outputs": [], "source": [ "```python\n", "import pandas as pd\n", "import os\n", "import json\n", "import numpy as np\n", "\n", "# List all files in the cohort directory to understand the available data\n", "print(\"Files in the cohort directory:\")\n", "for file in os.listdir(in_cohort_dir):\n", " print(f\"- {file}\")\n", "\n", "# Try to find the gene expression matrix file\n", "expression_file = None\n", "for file in os.listdir(in_cohort_dir):\n", " if any(term in file.lower() for term in [\"expression\", \"matrix\", \"counts\", \"fpkm\", \"tpm\", \"series_matrix\"]):\n", " if not any(excluded in file.lower() for excluded in [\"mirna\", \"methyl\"]):\n", " expression_file = os.path.join(in_cohort_dir, file)\n", " print(f\"Found potential gene expression file: {file}\")\n", " break\n", "\n", "# Check for gene expression data availability\n", "is_gene_available = expression_file is not None\n", "print(f\"Gene expression data available: {is_gene_available}\")\n", "\n", "# Try to load the series matrix file which should contain sample characteristics\n", "clinical_data = None\n", "if expression_file and os.path.exists(expression_file):\n", " try:\n", " # Series matrix files often contain both sample characteristics and expression data\n", " with open(expression_file, 'r') as f:\n", " lines = []\n", " i = 0\n", " # Read the first few lines to identify the structure\n", " for line in f:\n", " lines.append(line)\n", " i += 1\n", " if i > 100: # Read first 100 lines to get header info\n", " break\n", " \n", " # Check for sample characteristics section in these lines\n", " characteristic_lines = [line for line in lines if \"!Sample_characteristics\" in line]\n", " print(f\"Found {len(characteristic_lines)} sample characteristic lines\")\n", " \n", " if characteristic_lines:\n", " # Extract sample characteristics\n", " sample_chars = []\n", " for line in characteristic_lines:\n", " parts = line.strip().split('\\t')\n", " sample_chars.append(parts[1:]) # Skip the !Sample_characteristics tag\n", " \n", " # Transpose the data to have samples as columns\n", " if sample_chars:\n", " sample_chars_transposed = list(map(list, zip(*sample_chars)))\n", " clinical_data = pd.DataFrame(sample_chars_transposed)\n", " \n", " # Find the row containing sample IDs if available\n", " id_row = None\n", " for i, row in clinical_data.iterrows():\n", " if any(id_term in str(val).lower() for val in row for id_term in [\"geo_accession\", \"sample\", \"id\"]):\n", " id_row = i\n", " break\n", " \n", " if id_row is not None:\n", " clinical_data.columns = clinical_data.iloc[id_row]\n", " \n", " print(\"Clinical data shape:\", clinical_data.shape)\n", " print(\"Sample of clinical data:\")\n", " print(clinical_data.head())\n", " \n", " # Examine unique values in each row to identify potential trait, age, and gender rows\n", " print(\"\\nUnique values in each row:\")\n", " for i, row in clinical_data.iterrows():\n", " unique_vals = set(str(val) for val in row if not pd.isna(val))\n", " if 1 < len(unique_vals) < 10: # Show rows with 2-9 unique values\n", " print(f\"Row {i}: {unique_vals}\")\n", " except Exception as e:\n", " print(f\"Error processing series matrix file: {e}\")\n", "\n", "# If we couldn't extract clinical data from the series matrix, try to find a separate clinical file\n", "if clinical_data is None:\n", " print(\"Looking for separate clinical data file...\")\n", " for file in os.listdir(in_cohort_dir):\n", " if any(term in file.lower() for term in [\"clinical\", \"pheno\", \"metadata\", \"phenotype\", \"sample\"]):\n", " clinical_file = os.path.join(in_cohort_dir, file)\n", " try:\n", " clinical_data = pd.read_csv(clinical_file, sep='\\t')\n", " print(f\"Loaded clinical data from {file}\")\n", " print(\"Clinical data shape:\", clinical_data.shape)\n", " print(\"Sample of clinical data:\")\n", " print(clinical_data.head())\n", " break\n", " except Exception as e:\n", " print(f\"Error loading clinical file {file}: {e}\")\n", "\n", "# Based on our examination of the data, we'll set these variables\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# If we have clinical data, analyze it to find trait, age, and gender information\n", "if clinical_data is not None:\n", " # Check each row for trait, age, and gender information\n", " for i, row in clinical_data.iterrows():\n", " row_values = [str(val).lower() for val in row if not pd.isna(val)]\n", " row_text = ' '.join(row_values)\n", " \n", " # Check for melanoma/disease information\n", " if any(term in row_text for term in [\"melanoma\", \"tumor\", \"cancer\", \"diagnosis\", \"disease\", \"status\", \"patient\", \"primary\"]):\n", " unique_vals = set(row_values)\n", " if len(unique_vals) > 1: # Ensure there's variation in the values\n", " print(f\"Potential trait row {i}: {unique_vals}\")\n", " trait_row = i\n", " \n", " # Check for age information\n", " if any(term in row_text for term in [\"age\", \"years\", \"yr\", \"old\"]):\n", " # Verify variety in ages\n", " if len(set(row_values)) > 1:\n", " print(f\"Potential age row {i}: {set(row_values)}\")\n", " age_row = i\n", " \n", " # Check for gender information\n", " if any(term in row_text for term in [\"gender\", \"sex\", \"male\", \"female\"]):\n", " # Verify variety in genders\n", " if len(set(row_values)) > 1:\n", " print(f\"Potential gender row {i}: {set(row_values)}\")\n", " gender_row = i\n", "\n", "# Define conversion functions\n", "def convert_trait(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: 1 for melanoma, 0 for control\n", " value_lower = str(value).lower()\n", " if any(term in value_lower for term in [\"melanoma\", \"tumor\", \"cancer\", \"case\", \"patient\", \"primary\", \"yes\", \"positive\"]):\n", " return 1\n", " elif any(term in value_lower for term in [\"control\", \"normal\", \"healthy\", \"non-melanoma\", \"nevus\", \"benign\", \"no\", \"negative\"]):\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Extract numeric age\n", " if isinstance(value, (int, float)):\n", " return float(value)\n", " \n", " import re\n", " # Try to extract numbers from the string\n", " numbers = re.findall(r'\\d+', str(value))\n", " if numbers:\n", " return float(numbers[0])\n", " return None\n", "\n", "def convert_gender(value):\n", " if value is None or pd.isna(value):\n", " return None\n", " # Extract value after colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary: 0 for female, 1 for male\n", " value_lower = str(value).lower()\n", " if any(term in value_lower for term in [\"female\", \"f\", \"woman\", \"girl\"]):\n", " return 0\n", " elif any(term in value_lower for term in [\"male\", \"m\", \"man\", \"boy\"]):\n", " return 1\n", " return None\n", "\n", "# Determine trait availability\n", "is_trait_available = trait_row is not None\n", "print(f\"Trait data available: {is_trait_available}\")\n", "print(f\"Age data available: {age_row is not None}\")\n", "print(f\"Gender data available: {gender_row is\n" ] }, { "cell_type": "markdown", "id": "8a25cd3e", "metadata": {}, "source": [ "### Step 5: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "856a7463", "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. 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": "ef919e84", "metadata": {}, "source": [ "### Step 6: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "2355fb91", "metadata": {}, "outputs": [], "source": [ "# Looking at the gene identifiers in the gene expression data\n", "# These appear to be human gene symbols (like A2M, ABCF1, ACVR1C, etc.)\n", "# rather than probe IDs or other identifiers that would require mapping\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "77c57976", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": null, "id": "6b324492", "metadata": {}, "outputs": [], "source": [ "# 1. Get the paths to the SOFT and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene expression data\n", "gene_data = get_genetic_data(matrix_file)\n", "print(f\"Extracted gene data with shape: {gene_data.shape}\")\n", "\n", "# Normalize gene symbols in the gene expression data\n", "print(f\"Top 10 gene indices before normalization: {gene_data.index[:10].tolist()}\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Top 10 gene indices after normalization: {normalized_gene_data.index[:10].tolist()}\")\n", "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n", "\n", "# Create directory for gene data file if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "# Save the normalized gene data\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# Define conversion functions for clinical data extraction\n", "def convert_trait(value):\n", " if pd.isna(value):\n", " return None\n", " # Extract the value after 'long-term benefit:' if present\n", " match = re.search(r'long-term benefit:\\s*(.*)', str(value))\n", " if match:\n", " value = match.group(1).strip()\n", " if value.upper() == \"YES\":\n", " return 1\n", " elif value.upper() == \"NO\":\n", " return 0\n", " return None\n", "\n", "def convert_age(value):\n", " if pd.isna(value):\n", " return None\n", " # Extract age value after the colon\n", " match = re.search(r'age:\\s*(\\d+)', str(value))\n", " if match:\n", " return int(match.group(1))\n", " return None\n", "\n", "def convert_gender(value):\n", " # Not used as gender data isn't available\n", " return None\n", "\n", "# 2. Extract clinical features using the clinical data from step 1\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", "# Based on the sample characteristics dictionary from Step 1, \n", "# long-term benefit (trait) is in row 4\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=4, # \"long-term benefit\" information is in row 4\n", " convert_trait=convert_trait,\n", " age_row=0, # Age information is in row 0\n", " convert_age=convert_age,\n", " gender_row=None, # No gender information available\n", " convert_gender=None\n", ")\n", "\n", "# Save clinical data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_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\n", "try:\n", " linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", " print(f\"Shape of linked data: {linked_data.shape}\")\n", " \n", " # 4. 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", " # 5. Determine if the trait and demographic features are biased\n", " is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\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,\n", " is_biased=is_trait_biased,\n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data from melanoma patients with information on long-term benefit from PD-1 based immunotherapy.\"\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. Final linked data not saved.\")\n", " \n", "except Exception as e:\n", " print(f\"Error in data linking process: {e}\")\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=False,\n", " is_biased=None,\n", " df=None,\n", " note=f\"Failed to link clinical and gene data. Error: {e}\"\n", " )\n", " print(\"Dataset validation failed. Final linked data not saved.\")" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }