{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "df457879", "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 = \"Obesity\"\n", "cohort = \"GSE158237\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Obesity\"\n", "in_cohort_dir = \"../../input/GEO/Obesity/GSE158237\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Obesity/GSE158237.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Obesity/gene_data/GSE158237.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Obesity/clinical_data/GSE158237.csv\"\n", "json_path = \"../../output/preprocess/Obesity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "c44d1ffe", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "9660c5cc", "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": "945aa107", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "126abbdf", "metadata": {}, "outputs": [], "source": [ "I'll provide a corrected version of the code that properly handles the sample characteristics dictionary.\n", "\n", "```python\n", "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Callable, Optional, Dict, Any, Union\n", "\n", "# 1. Determine if gene expression data is available\n", "# Based on the background information, this appears to be gene expression data from colon biopsies\n", "is_gene_available = True # Gene expression data appears to be available based on study description\n", "\n", "# 2. Determine data availability and conversion functions\n", "\n", "# 2.1 For the trait (Obesity)\n", "# BMI is a continuous measure that directly relates to obesity\n", "trait_row = 10 # BMI is in row 10\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert BMI value to obesity classification (binary)\"\"\"\n", " if value is None or value == '/' or pd.isna(value):\n", " return None\n", " \n", " # Extract numeric value after the colon\n", " if isinstance(value, str) and ':' in value:\n", " try:\n", " bmi_str = value.split(':', 1)[1].strip()\n", " bmi = float(bmi_str)\n", " # Use standard BMI threshold for obesity (≥30 kg/m² = obese)\n", " return 1 if bmi >= 30.0 else 0\n", " except:\n", " return None\n", " return None\n", "\n", "# 2.2 For age\n", "age_row = 1 # Age is in row 1\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to a numeric value\"\"\"\n", " if value is None or value == '/' or pd.isna(value):\n", " return None\n", " \n", " # Extract numeric value after the colon\n", " if isinstance(value, str) and ':' in value:\n", " try:\n", " age_str = value.split(':', 1)[1].strip()\n", " return float(age_str)\n", " except:\n", " return None\n", " return None\n", "\n", "# 2.3 For gender\n", "gender_row = 2 # Sex is in row 2\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert sex value to binary (0 for female, 1 for male)\"\"\"\n", " if value is None or value == '/' or pd.isna(value):\n", " return None\n", " \n", " # Extract value after the colon\n", " if isinstance(value, str) and ':' in value:\n", " try:\n", " sex_str = value.split(':', 1)[1].strip()\n", " # Assuming 1 = male, 2 = female (common coding in medical datasets)\n", " if sex_str == '1':\n", " return 1 # Male\n", " elif sex_str == '2':\n", " return 0 # Female\n", " else:\n", " return None\n", " except:\n", " return None\n", " return None\n", "\n", "# 3. Save metadata with initial filtering\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. Extract clinical features if trait_row is not None\n", "if trait_row is not None:\n", " try:\n", " # Define the sample characteristics dictionary from the output\n", " sample_char_dict = {\n", " 0: ['tissue: colon'], \n", " 1: ['age (years): 52', 'age (years): 71', 'age (years): 66', 'age (years): 53', 'age (years): 57', 'age (years): 70', 'age (years): 62', 'age (years): 58', 'age (years): 60', 'age (years): 68', 'age (years): 69', 'age (years): 44', 'age (years): 73', 'age (years): 55', 'age (years): 48', 'age (years): 56', 'age (years): 65', 'age (years): 64', 'age (years): 67', 'age (years): 59', 'age (years): 50', 'age (years): 39', 'age (years): 51', 'age (years): 46'], \n", " 2: ['Sex: 1', 'Sex: 2'], \n", " 3: ['ast (u/l): 9', 'ast (u/l): 22', 'ast (u/l): 16', 'ast (u/l): 15', 'ast (u/l): 18', 'ast (u/l): 20', 'ast (u/l): 33', 'ast (u/l): 12', 'ast (u/l): 23', 'ast (u/l): 17', 'ast (u/l): 32', 'ast (u/l): 7', 'ast (u/l): 14', 'ast (u/l): /', 'ast (u/l): 21', 'ast (u/l): 19', 'ast (u/l): 31', 'ast (u/l): 13', 'ast (u/l): 30', 'ast (u/l): 29', 'ast (u/l): 35'], \n", " 4: ['alt (u/l): /', 'alt (u/l): 34', 'alt (u/l): 29', 'alt (u/l): 42', 'alt (u/l): 22', 'alt (u/l): 32', 'alt (u/l): 74', 'alt (u/l): 31', 'alt (u/l): 19', 'alt (u/l): 44', 'alt (u/l): 25', 'alt (u/l): 30', 'alt (u/l): 28', 'alt (u/l): 17', 'alt (u/l): 21', 'alt (u/l): 27', 'alt (u/l): 26', 'alt (u/l): 24', 'alt (u/l): 59', 'alt (u/l): 20', 'alt (u/l): 18', 'alt (u/l): 38', 'alt (u/l): 15', 'alt (u/l): 33'], \n", " 5: ['triglycerides (mg/dl): 61', 'triglycerides (mg/dl): 115', 'triglycerides (mg/dl): 77', 'triglycerides (mg/dl): 108', 'triglycerides (mg/dl): 87', 'triglycerides (mg/dl): 93', 'triglycerides (mg/dl): 304', 'triglycerides (mg/dl): 118', 'triglycerides (mg/dl): 73', 'triglycerides (mg/dl): 69', 'triglycerides (mg/dl): 127', 'triglycerides (mg/dl): 190', 'triglycerides (mg/dl): 76', 'triglycerides (mg/dl): 70', 'triglycerides (mg/dl): 62', 'triglycerides (mg/dl): 50', 'triglycerides (mg/dl): 42', 'triglycerides (mg/dl): 66', 'triglycerides (mg/dl): 52', 'triglycerides (mg/dl): 99', 'triglycerides (mg/dl): 166', 'triglycerides (mg/dl): 124', 'triglycerides (mg/dl): 129', 'triglycerides (mg/dl): 102', 'triglycerides (mg/dl): 325', 'triglycerides (mg/dl): 90', 'triglycerides (mg/dl): 278', 'triglycerides (mg/dl): 180', 'triglycerides (mg/dl): 130', 'triglycerides (mg/dl): 97'], \n", " 6: ['total cholesterol (mg/dl): 184', 'total cholesterol (mg/dl): 162', 'total cholesterol (mg/dl): 202', 'total cholesterol (mg/dl): 170', 'total cholesterol (mg/dl): /', 'total cholesterol (mg/dl\n" ] }, { "cell_type": "markdown", "id": "2701cd21", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "3396a06d", "metadata": {}, "outputs": [], "source": [ "I'll provide properly formatted code to analyze the GEO dataset and extract clinical features.\n", "\n", "```python\n", "# First, let's examine what files are actually available in the cohort directory\n", "import pandas as pd\n", "import numpy as np\n", "import os\n", "import re\n", "import json\n", "\n", "# List files in the directory to understand what's available\n", "files_in_dir = os.listdir(in_cohort_dir)\n", "print(f\"Files in directory: {files_in_dir}\")\n", "\n", "# Check for matrix file which would contain gene expression data\n", "# GEO series matrix file typically contains gene expression data\n", "matrix_files = [f for f in files_in_dir if 'matrix' in f.lower() or 'series' in f.lower()]\n", "is_gene_available = len(matrix_files) > 0 and not any(['mirna' in f.lower() or 'methylation' in f.lower() for f in matrix_files])\n", "print(f\"Matrix files: {matrix_files}\")\n", "print(f\"Gene expression data available: {is_gene_available}\")\n", "\n", "# Load the series matrix file to extract clinical data\n", "clinical_data = None\n", "unique_values = {}\n", "\n", "if matrix_files:\n", " matrix_file_path = os.path.join(in_cohort_dir, matrix_files[0])\n", " try:\n", " # In GEO series matrix files, sample characteristics are typically in rows starting with \"!Sample_characteristics_ch1\"\n", " with open(matrix_file_path, 'r') as file:\n", " lines = file.readlines()\n", " \n", " # Extract sample characteristic lines\n", " characteristic_lines = [line.strip() for line in lines if line.startswith('!Sample_characteristics_ch1')]\n", " \n", " if characteristic_lines:\n", " # Parse these lines into a dataframe\n", " samples = []\n", " for line in characteristic_lines:\n", " parts = line.split('\\t')\n", " samples.append(parts[1:]) # Skip the first part which is the header\n", " \n", " # Transpose to get characteristics as rows\n", " clinical_data = pd.DataFrame(samples).T\n", " print(\"\\nClinical data sample (first 5 rows):\")\n", " print(clinical_data.head())\n", " \n", " # Get unique values for each row to identify trait, age, and gender data\n", " for i, row in clinical_data.iterrows():\n", " row_values = row.values # All values in this row\n", " unique_vals = set(val for val in row_values if pd.notna(val) and val != '')\n", " if len(unique_vals) > 0:\n", " unique_values[i] = list(unique_vals)\n", " print(f\"Row {i}: {list(unique_vals)[:3]}{'...' if len(unique_vals) > 3 else ''}\")\n", " except Exception as e:\n", " print(f\"Error loading series matrix file: {e}\")\n", " clinical_data = pd.DataFrame()\n", "\n", "# Based on the unique values analysis, identify the row indices for trait, age, and gender\n", "# For now, setting to None; we'll update these after analyzing the data\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# After examining the unique values, update these variables with actual row indices\n", "# Analyze each row to identify trait, age, and gender\n", "for row_idx, vals in unique_values.items():\n", " # Convert to string for easier text analysis\n", " vals_str = ' '.join([str(val).lower() for val in vals])\n", " \n", " # Look for trait-related terms (like obesity, BMI, weight)\n", " if any(term in vals_str for term in ['obese', 'obesity', 'bmi', 'body mass index', 'weight']):\n", " trait_row = row_idx\n", " print(f\"Identified trait row: {row_idx} with values: {vals[:3]}{'...' if len(vals) > 3 else ''}\")\n", " \n", " # Look for age-related terms\n", " elif any(term in vals_str for term in ['age', 'years old', 'year old']):\n", " age_row = row_idx\n", " print(f\"Identified age row: {row_idx} with values: {vals[:3]}{'...' if len(vals) > 3 else ''}\")\n", " \n", " # Look for gender-related terms\n", " elif any(term in vals_str for term in ['gender', 'sex', 'male', 'female']):\n", " gender_row = row_idx\n", " print(f\"Identified gender row: {row_idx} with values: {vals[:3]}{'...' if len(vals) > 3 else ''}\")\n", "\n", "# Define conversion functions for each variable based on inspection of unique values\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert obesity-related trait values to binary (0=non-obese, 1=obese)\"\"\"\n", " if pd.isna(value) or value == '':\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to lowercase for case-insensitive comparison\n", " if isinstance(value, str):\n", " value_lower = value.lower()\n", " \n", " # Obesity-related terms\n", " if any(term in value_lower for term in ['obese', 'obesity']):\n", " return 1\n", " # Non-obese terms\n", " elif any(term in value_lower for term in ['normal', 'lean', 'control', 'non-obese']):\n", " return 0\n", " # BMI-based classification (if BMI values are provided)\n", " elif 'bmi' in value_lower:\n", " try:\n", " bmi_match = re.search(r'(\\d+\\.?\\d*)', value)\n", " if bmi_match:\n", " bmi = float(bmi_match.group(1))\n", " return 1 if bmi >= 30 else 0\n", " except:\n", " pass\n", " \n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous numeric values\"\"\"\n", " if pd.isna(value) or value == '':\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to extract numeric age value\n", " if isinstance(value, str):\n", " try:\n", " # Look for patterns like \"X years\" or just numbers\n", " age_match = re.search(r'(\\d+\\.?\\d*)', value)\n", " if age_match:\n", " return float(age_match.group(1))\n", " except:\n", " pass\n", " \n", " # If value is already numeric\n", " elif isinstance(value, (int, float)):\n", " return float(value)\n", " \n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0=female, 1=male)\"\"\"\n", " if pd.isna(value) or value == '':\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to lowercase for case-insensitive comparison\n", " if isinstance(value, str):\n", " value_lower = value.lower()\n", " \n", " if any(term in value_lower for term in ['female', 'f', 'woman', 'women']):\n", " return 0\n", " elif any(term in value_lower for term in ['male', 'm', 'man', 'men']):\n", " return 1\n", " \n", " return None\n", "\n", "# Based on the actual inspection results, determine if the trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Save metadata to record 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", "# Extract clinical features if trait data is available and clinical data exists\n", "if is_trait_available and clinical_data is not None and not clinical_data.empty:\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=\n" ] }, { "cell_type": "markdown", "id": "88704adb", "metadata": {}, "source": [ "### Step 4: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "5fcdf9da", "metadata": {}, "outputs": [], "source": [ "I'll provide a clean implementation for this step:\n", "\n", "```python\n", "import os\n", "import json\n", "import pandas as pd\n", "from typing import Callable, Dict, Any, Optional\n", "\n", "# 1. First, let's check for and load the sample characteristics data\n", "if os.path.exists(os.path.join(in_cohort_dir, 'sample_characteristics.json')):\n", " with open(os.path.join(in_cohort_dir, 'sample_characteristics.json'), 'r') as f:\n", " sample_chars = json.load(f)\n", "else:\n", " # If file doesn't exist, create empty dictionary\n", " sample_chars = {}\n", "\n", "# Also check for background information\n", "if os.path.exists(os.path.join(in_cohort_dir, 'background.txt')):\n", " with open(os.path.join(in_cohort_dir, 'background.txt'), 'r') as f:\n", " background = f.read()\n", "else:\n", " background = \"\"\n", "\n", "# Print to review the data\n", "print(\"Sample Characteristics:\")\n", "if sample_chars:\n", " for key, values in sample_chars.items():\n", " unique_values = set(values)\n", " print(f\"Key {key}: {len(unique_values)} unique values\")\n", " if len(unique_values) <= 10: # Print all unique values if there are few\n", " print(f\" Unique values: {unique_values}\")\n", " else:\n", " # Print a few examples\n", " print(f\" Sample values: {list(unique_values)[:5]}\")\n", "\n", "print(\"\\nBackground Information:\")\n", "print(background[:1000] + \"...\" if len(background) > 1000 else background)\n", "\n", "# 2. Load the clinical data if available\n", "clinical_data_path = os.path.join(in_cohort_dir, 'clinical_data.csv')\n", "if os.path.exists(clinical_data_path):\n", " clinical_data = pd.read_csv(clinical_data_path)\n", " print(f\"\\nClinical Data Shape: {clinical_data.shape}\")\n", " print(clinical_data.head())\n", "else:\n", " clinical_data = pd.DataFrame()\n", " print(\"\\nNo clinical data found.\")\n", "\n", "# 3. Check for gene expression data (matrix file)\n", "is_gene_available = False\n", "matrix_files = [f for f in os.listdir(in_cohort_dir) if f.endswith('_matrix.csv') or f == 'matrix.csv']\n", "if matrix_files:\n", " # Check if it's gene expression data by looking at the file\n", " matrix_path = os.path.join(in_cohort_dir, matrix_files[0])\n", " try:\n", " # Read just a few rows to check content\n", " gene_sample = pd.read_csv(matrix_path, nrows=5)\n", " print(f\"\\nMatrix File Preview ({matrix_files[0]}):\")\n", " print(gene_sample.head())\n", " \n", " # If many rows (genes) and first column has gene identifiers, likely gene expression data\n", " if gene_sample.shape[0] > 0 and len(gene_sample.columns) > 1:\n", " is_gene_available = True\n", " except Exception as e:\n", " print(f\"Error reading matrix file: {e}\")\n", "\n", "print(f\"\\nGene Expression Data Available: {is_gene_available}\")\n", "\n", "# Now, based on sample characteristics, determine trait, age, and gender availability\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Examine sample characteristics to identify relevant rows\n", "if sample_chars:\n", " for key, values in sample_chars.items():\n", " unique_values = set(values)\n", " \n", " # Look for obesity-related characteristics (weight, BMI, obesity status)\n", " if len(unique_values) > 1 and any(obesity_term in ' '.join(str(v) for v in unique_values).lower() \n", " for obesity_term in ['obesity', 'obese', 'bmi', 'body mass', 'weight']):\n", " trait_row = int(key)\n", " \n", " # Look for age information\n", " if len(unique_values) > 1 and any(age_term in ' '.join(str(v) for v in unique_values).lower() \n", " for age_term in ['age:', 'year', 'yr', 'age at']):\n", " age_row = int(key)\n", " \n", " # Look for gender/sex information\n", " if len(unique_values) > 1 and any(gender_term in ' '.join(str(v) for v in unique_values).lower() \n", " for gender_term in ['gender:', 'sex:', 'male', 'female']):\n", " gender_row = int(key)\n", "\n", "# Define conversion functions\n", "def convert_trait(value):\n", " \"\"\"Convert obesity trait value to binary: 1 for obese, 0 for non-obese/control.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value part if it contains a colon\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " value_lower = str(value).lower()\n", " \n", " # Check for obese/obesity indicators\n", " if any(term in value_lower for term in ['obese', 'obesity']):\n", " return 1\n", " # Check for non-obese indicators\n", " elif any(term in value_lower for term in ['non-obese', 'lean', 'control', 'normal weight']):\n", " return 0\n", " # Try to interpret BMI values if present\n", " elif 'bmi' in value_lower:\n", " try:\n", " # Extract numeric part of BMI\n", " import re\n", " bmi_value = float(re.search(r'\\d+\\.?\\d*', value_lower).group())\n", " return 1 if bmi_value >= 30 else 0 # WHO definition: BMI ≥ 30 is obese\n", " except:\n", " return None\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age value to continuous numeric type.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value part if it contains a colon\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Try to extract numeric age\n", " try:\n", " import re\n", " age_match = re.search(r'(\\d+\\.?\\d*)', str(value))\n", " if age_match:\n", " return float(age_match.group(1))\n", " except:\n", " pass\n", " \n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary: 0 for female, 1 for male.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value part if it contains a colon\n", " if isinstance(value, str) and ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " value_lower = str(value).lower()\n", " \n", " if any(female_term in value_lower for female_term in ['female', 'f', 'woman', 'girl']):\n", " return 0\n", " elif any(male_term in value_lower for male_term in ['male', 'm', 'man', 'boy']):\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", "# Save initial metadata\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 and save clinical features if trait data is available\n", "if is_trait_available and not clinical_data.empty:\n", " selected_clinical = 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 processed clinical data\n", " print(\"\\nProcessed Clinical Data Preview:\")\n", " print(preview\n" ] }, { "cell_type": "markdown", "id": "51374fb8", "metadata": {}, "source": [ "### Step 5: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "fa1d310d", "metadata": {}, "outputs": [], "source": [ "# 1. First get the file paths again to access the matrix file\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": "bc779090", "metadata": {}, "source": [ "### Step 6: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "642aa690", "metadata": {}, "outputs": [], "source": [ "# The gene identifiers appear to be numeric/alphanumeric values that are likely probe IDs \n", "# from a microarray platform, not standard human gene symbols.\n", "# Human gene symbols typically follow a specific naming convention (e.g., BRCA1, TP53)\n", "# and are not purely numeric. These identifiers (like '16657436') are most likely\n", "# probe identifiers from an Affymetrix or similar microarray platform.\n", "\n", "# Therefore, these identifiers will need to be mapped to human gene symbols\n", "# for biological interpretation and cross-study comparability.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "bffa3161", "metadata": {}, "source": [ "### Step 7: Gene Annotation" ] }, { "cell_type": "code", "execution_count": null, "id": "459b5320", "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": "a7568636", "metadata": {}, "source": [ "### Step 8: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": null, "id": "bf108ae6", "metadata": {}, "outputs": [], "source": [ "# 1. First, let's determine which columns in gene_annotation correspond to gene IDs and symbols\n", "\n", "# Examine the gene annotation DataFrame to find the probe ID column and gene symbol column\n", "# From the preview, we can see:\n", "# - 'ID' column contains identifiers that match those in the gene expression data (e.g., '16657436')\n", "# - For gene symbols, we need to look for a column that contains standard human gene symbols\n", "\n", "# Check for a column containing gene symbols\n", "gene_symbol_columns = []\n", "for col in gene_annotation.columns:\n", " # Look at the first 100 values in each column to check for likely gene symbol patterns\n", " sample_values = gene_annotation[col].dropna().head(100).astype(str).tolist()\n", " # Gene symbols typically have patterns like uppercase letters with numbers (e.g., BRCA1)\n", " if any(re.search(r'^[A-Z][A-Z0-9]{1,9}$', str(val)) for val in sample_values):\n", " gene_symbol_columns.append(col)\n", "\n", "print(f\"Potential gene symbol columns: {gene_symbol_columns}\")\n", "\n", "# If we can't find a direct gene symbol column, look for a column with gene accession numbers\n", "gene_accession_columns = []\n", "for col in gene_annotation.columns:\n", " sample_values = gene_annotation[col].dropna().head(100).astype(str).tolist()\n", " # Gene accession numbers often have patterns like NM_, NR_, XM_, etc.\n", " if any(re.search(r'^(NM_|NR_|XM_|XR_)', str(val)) for val in sample_values):\n", " gene_accession_columns.append(col)\n", "\n", "print(f\"Potential gene accession columns: {gene_accession_columns}\")\n", "\n", "# Based on the column analysis, we need to choose the right columns for mapping\n", "# The 'ID' column in gene_annotation matches the indices in gene_data\n", "probe_id_column = 'ID'\n", "\n", "# For gene symbols, use 'GB_ACC' as it appears to contain gene accessions\n", "# which can be used to extract potential gene symbols\n", "gene_symbol_column = 'GB_ACC'\n", "\n", "# 2. Create a gene mapping DataFrame using these columns\n", "mapping_df = get_gene_mapping(gene_annotation, probe_id_column, gene_symbol_column)\n", "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"Sample of mapping data:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene-level data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First few gene symbols after mapping:\")\n", "print(gene_data.index[:10])" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }