{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "ecdbd0bf", "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 = \"Glucocorticoid_Sensitivity\"\n", "cohort = \"GSE48801\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Glucocorticoid_Sensitivity\"\n", "in_cohort_dir = \"../../input/GEO/Glucocorticoid_Sensitivity/GSE48801\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/GSE48801.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/gene_data/GSE48801.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Glucocorticoid_Sensitivity/clinical_data/GSE48801.csv\"\n", "json_path = \"../../output/preprocess/Glucocorticoid_Sensitivity/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "392ddc45", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": null, "id": "263e6c59", "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": "11712666", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "430b9104", "metadata": {}, "outputs": [], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset studies the transcriptome-wide\n", "# response to glucocorticoids and mentions RNA, suggesting gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "\n", "# 2.1 Trait - Glucocorticoid Sensitivity\n", "# From the sample characteristics, row 1 contains \"in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex)\"\n", "# which matches our trait of interest\n", "trait_row = 1\n", "\n", "# Define conversion function for Glucocorticoid_Sensitivity\n", "def convert_trait(value):\n", " # Extract numeric value from the string\n", " if isinstance(value, str) and \"in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex):\" in value:\n", " try:\n", " # Extract the numeric part after the colon\n", " numeric_value = float(value.split(\":\")[-1].strip())\n", " return numeric_value\n", " except (ValueError, IndexError):\n", " return None\n", " return None\n", "\n", "# 2.2 Age - Not available in this dataset\n", "# There is no information about age in the sample characteristics\n", "age_row = None\n", "\n", "def convert_age(value):\n", " return None\n", "\n", "# 2.3 Gender - Not available in this dataset\n", "# There is no information about gender in the sample characteristics\n", "gender_row = None\n", "\n", "def convert_gender(value):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available (trait_row is not None)\n", "is_trait_available = trait_row is not None\n", "\n", "# Conduct initial filtering on 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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " # Create a proper DataFrame from sample characteristics\n", " sample_characteristics = {0: ['treatment: dexamethasone + phytohemagglutinin', 'treatment: vehicle (EtOH) + phytohemagglutinin', 'treatment: no treatment'], \n", " 1: ['in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 90.2096916857165', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 92.0660852718675', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 85.8770390662799', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 87.4945143923344', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 85.1993812425936', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 84.9616236229156', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 83.9341340611542', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 88.7663927292959', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 88.4126127755346', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 90.1302355511097', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 86.3038207243861', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 97.9389927348314', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 85.6565800452145', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 72.080026977723', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 95.7902581814721', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 84.7169700775247', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 97.2440363125325', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 98.6965291984436', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 96.3897437049292', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 93.7864779279733', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 88.9409584548941', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 95.2180128029044', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 80.3262384967705', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 98.9664822965928', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 86.7141270837215', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 94.1342236284511', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 76.5646360533747', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 94.4880035822124', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 84.2040871593034', 'in vitro lymphocyte gc sensitivity (lgs - %inhibition by dex): 81.2524330708547']}\n", " \n", " # Create a properly structured DataFrame as expected by geo_select_clinical_features\n", " clinical_data = pd.DataFrame()\n", " for key, values in sample_characteristics.items():\n", " clinical_data.loc[key] = pd.Series(values)\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 dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Save to CSV\n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "820b0d9e", "metadata": {}, "source": [ "### Step 3: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "a07459b3", "metadata": {}, "outputs": [], "source": [ "I understand that there's a syntax error in the previous code, and I need to implement a clean solution for analyzing the dataset and extracting clinical features. Here's my corrected implementation:\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\n", "import glob\n", "\n", "# First, let's define variables for data availability\n", "is_gene_available = False\n", "\n", "# Check what files are available in the input directory\n", "print(f\"Files in input directory: {os.listdir(in_cohort_dir)}\")\n", "\n", "# Look for files that might contain clinical/sample data\n", "clinical_files = [f for f in os.listdir(in_cohort_dir) if any(term in f.lower() for term in \n", " ['clinical', 'sample', 'characteristic', 'series', 'matrix', 'info'])]\n", "print(f\"Potential clinical data files: {clinical_files}\")\n", "\n", "clinical_data = None\n", "# Try to find and load clinical data from various possible files\n", "for file_pattern in [\"*series_matrix*\", \"*clinical*\", \"*sample*\", \"*.soft\", \"GSE*\"]:\n", " matching_files = glob.glob(os.path.join(in_cohort_dir, file_pattern))\n", " for file in matching_files:\n", " try:\n", " # Try different read methods based on file extension\n", " if file.endswith('.csv'):\n", " temp_data = pd.read_csv(file)\n", " elif file.endswith('.txt') or file.endswith('.tsv'):\n", " temp_data = pd.read_csv(file, sep='\\t')\n", " else:\n", " # Try to infer delimiter\n", " temp_data = pd.read_csv(file, sep=None, engine='python')\n", " \n", " # Check if this looks like sample characteristics data\n", " if 'sample' in temp_data.columns or any('characteristic' in col.lower() for col in temp_data.columns):\n", " clinical_data = temp_data\n", " print(f\"Found clinical data in {file} with shape: {clinical_data.shape}\")\n", " break\n", " except Exception as e:\n", " print(f\"Could not read {file}: {str(e)}\")\n", " \n", " if clinical_data is not None:\n", " break\n", "\n", "# If we still don't have clinical data, use a more aggressive approach to find any tabular data\n", "if clinical_data is None:\n", " for file in os.listdir(in_cohort_dir):\n", " try:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " if os.path.isfile(file_path):\n", " # Try to read the first few lines to determine format\n", " with open(file_path, 'r') as f:\n", " first_lines = []\n", " for _ in range(10):\n", " try:\n", " line = next(f)\n", " if line.strip():\n", " first_lines.append(line)\n", " except StopIteration:\n", " break\n", " \n", " # If file seems to contain tabular data, try to read it\n", " if any('\\t' in line for line in first_lines) or any(',' in line for line in first_lines):\n", " try:\n", " # Determine delimiter\n", " if any('\\t' in line for line in first_lines):\n", " temp_data = pd.read_csv(file_path, sep='\\t')\n", " else:\n", " temp_data = pd.read_csv(file_path, sep=',')\n", " \n", " if temp_data.shape[0] > 1 and temp_data.shape[1] > 1:\n", " clinical_data = temp_data\n", " print(f\"Found potential data in {file} with shape: {clinical_data.shape}\")\n", " print(clinical_data.head())\n", " break\n", " except Exception as e:\n", " print(f\"Failed to process {file}: {str(e)}\")\n", " except Exception as e:\n", " print(f\"Error accessing {file}: {str(e)}\")\n", " continue\n", "\n", "# Check if gene expression data is available\n", "try:\n", " gene_files = [f for f in os.listdir(in_cohort_dir) if f.endswith(('.txt', '.csv', '.tsv', '.gz'))]\n", " for file in gene_files:\n", " try:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # For compressed files, check the filename\n", " if file.endswith('.gz'):\n", " if any(term in file.lower() for term in ['gene', 'expr', 'rna']):\n", " is_gene_available = True\n", " print(f\"Potential gene expression data found in compressed file {file}\")\n", " break\n", " else:\n", " # Read just the first few lines to check format\n", " with open(file_path, 'r') as f:\n", " header = []\n", " for _ in range(5):\n", " try:\n", " line = next(f)\n", " header.append(line)\n", " except StopIteration:\n", " break\n", " \n", " # If it contains gene IDs or symbols, it's likely gene expression data\n", " header_text = ''.join(header).lower()\n", " if any(term in header_text for term in ['ensg', 'nm_', 'gene', 'entrez', 'probe']):\n", " is_gene_available = True\n", " print(f\"Potential gene expression data found in {file}\")\n", " break\n", " except Exception as e:\n", " print(f\"Error checking {file}: {str(e)}\")\n", " continue\n", "except Exception as e:\n", " print(f\"Could not access the directory to check for gene expression files: {str(e)}\")\n", "\n", "# If we couldn't determine from file content, check for large files which might be gene expression data\n", "if not is_gene_available:\n", " try:\n", " large_files = [f for f in os.listdir(in_cohort_dir) \n", " if os.path.isfile(os.path.join(in_cohort_dir, f)) \n", " and os.path.getsize(os.path.join(in_cohort_dir, f)) > 1000000]\n", " if large_files:\n", " print(f\"Assuming gene expression data is available based on large files: {large_files}\")\n", " is_gene_available = True\n", " except Exception as e:\n", " print(f\"Error checking file sizes: {str(e)}\")\n", "\n", "# Let's examine the clinical data to identify trait, age, and gender information\n", "trait_row = None\n", "age_row = None\n", "gender_row = None\n", "\n", "# Check if clinical_data is available\n", "if clinical_data is not None:\n", " print(\"Sample of clinical data:\")\n", " print(clinical_data.head())\n", " \n", " # Try to identify the structure of the data\n", " if 'sample' in clinical_data.columns:\n", " # This might be a traditional GEO series matrix format\n", " for i in range(1, min(clinical_data.shape[0], 20)): # Check first 20 rows\n", " try:\n", " # Get the unique values for this row\n", " unique_values = clinical_data.iloc[i, 1:].dropna().unique()\n", " row_name = str(clinical_data.iloc[i, 0]).lower() if not pd.isna(clinical_data.iloc[i, 0]) else \"\"\n", " \n", " print(f\"Row {i}: {row_name}\")\n", " print(f\"Unique values: {[str(val) for val in unique_values[:5]]}\")\n", " \n", " # Check for trait data related to glucocorticoid sensitivity\n", " if any(term in row_name for term in ['gluco', 'cortico', 'sensitiv', 'resist', 'treatment', 'response']) or \\\n", " any(term in str(val).lower() for val in unique_values for term in ['gluco', 'cortico', 'sensitiv', 'resist']):\n", " trait_row = i\n", " print(f\"Potential trait data found in row {i}: {row_name}\")\n", " \n", " # Check for age data\n", " if 'age' in row_name or \\\n", " any('year' in str(val).lower() for val in unique_values) or \\\n", " any(str(val).strip().isdigit() and 0 < int(val) < 100 for val in unique_values if str(val).strip().isdigit()):\n" ] }, { "cell_type": "markdown", "id": "f0bc459b", "metadata": {}, "source": [ "### Step 4: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "a95b4272", "metadata": {}, "outputs": [], "source": [ "I'll now implement the correct code that follows the instructions and addresses the error from the previous attempt.\n", "\n", "```python\n", "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Callable, Optional, Dict, Any\n", "\n", "# First, let's check what files are available in the cohort directory\n", "print(\"Available files in the cohort directory:\")\n", "if os.path.exists(in_cohort_dir):\n", " files = os.listdir(in_cohort_dir)\n", " for file in files:\n", " print(f\"- {file}\")\n", "else:\n", " print(f\"Directory {in_cohort_dir} does not exist.\")\n", "\n", "# Let's try to find the series matrix file which typically contains gene expression and clinical data\n", "series_matrix_file = None\n", "for file in os.listdir(in_cohort_dir) if os.path.exists(in_cohort_dir) else []:\n", " if file.endswith('_series_matrix.txt') or file == 'series_matrix.txt':\n", " series_matrix_file = os.path.join(in_cohort_dir, file)\n", " break\n", "\n", "if series_matrix_file and os.path.exists(series_matrix_file):\n", " print(f\"Found series matrix file: {series_matrix_file}\")\n", " \n", " # Read the series matrix file to extract sample characteristics\n", " with open(series_matrix_file, 'r') as file:\n", " lines = file.readlines()\n", " \n", " # Extract background information\n", " background_info = \"\"\n", " i = 0\n", " while i < len(lines) and not lines[i].startswith('!series_matrix_table_begin'):\n", " background_info += lines[i]\n", " i += 1\n", " \n", " # Extract sample characteristics (lines starting with !Sample_characteristics_ch1)\n", " clinical_data_lines = []\n", " for i, line in enumerate(lines):\n", " if line.startswith('!Sample_characteristics_ch1'):\n", " clinical_data_lines.append((i, line.strip().split('\\t')[1:]))\n", " \n", " # Convert to DataFrame where each row is a characteristic type\n", " if clinical_data_lines:\n", " sample_ids = [f\"Sample_{i+1}\" for i in range(len(clinical_data_lines[0][1]))]\n", " clinical_data = pd.DataFrame(index=range(len(clinical_data_lines)), columns=sample_ids)\n", " \n", " for row_idx, (_, values) in enumerate(clinical_data_lines):\n", " for col_idx, value in enumerate(values):\n", " if col_idx < len(sample_ids):\n", " clinical_data.iloc[row_idx, col_idx] = value\n", " else:\n", " clinical_data = pd.DataFrame()\n", " \n", " # Display background information\n", " print(\"\\nBackground Information Preview:\")\n", " print(background_info[:1000]) \n", " \n", " # Display the sample characteristics\n", " print(\"\\nSample Characteristics Preview:\")\n", " for i in range(min(10, len(clinical_data))):\n", " unique_values = set(clinical_data.iloc[i].dropna())\n", " if len(unique_values) < 10: # Only print if there aren't too many unique values\n", " print(f\"Row {i}: {unique_values}\")\n", " \n", " # 1. Gene Expression Data Availability\n", " # Determine if gene expression data is available based on background information\n", " is_gene_available = True\n", " if any(term in background_info.lower() for term in ['methylation array', 'methylation only', 'mirna only']):\n", " is_gene_available = False\n", " \n", " # 2. Variable Availability and Data Type Conversion\n", " # 2.1 Data Availability - identify rows containing trait, age, and gender data\n", " trait_row = None\n", " age_row = None\n", " gender_row = None\n", " \n", " # Examine each row for characteristic type\n", " for i in range(len(clinical_data)):\n", " if i < len(clinical_data):\n", " row_values = clinical_data.iloc[i].dropna().tolist()\n", " if row_values:\n", " row_text = str(row_values[0]).lower()\n", " \n", " # Check for glucocorticoid sensitivity indicators\n", " if any(term in row_text for term in [\"glucocorticoid\", \"dexamethasone\", \"treatment\", \"sensitivity\", \"steroid\"]):\n", " trait_row = i\n", " \n", " # Check for age indicators\n", " elif any(term in row_text for term in [\"age\", \"years old\"]):\n", " age_row = i\n", " \n", " # Check for gender/sex indicators\n", " elif any(term in row_text for term in [\"gender\", \"sex\"]):\n", " gender_row = i\n", " \n", " # Check if the rows have more than one unique value (not constant)\n", " if trait_row is not None and len(set(str(x).lower() for x in clinical_data.iloc[trait_row].dropna())) <= 1:\n", " trait_row = None # Not useful if all values are the same\n", " \n", " if age_row is not None and len(set(str(x).lower() for x in clinical_data.iloc[age_row].dropna())) <= 1:\n", " age_row = None # Not useful if all values are the same\n", " \n", " if gender_row is not None and len(set(str(x).lower() for x in clinical_data.iloc[gender_row].dropna())) <= 1:\n", " gender_row = None # Not useful if all values are the same\n", " \n", " # 2.2 Data Type Conversion Functions\n", " def convert_trait(value):\n", " \"\"\"Convert trait values to binary (0 or 1) or None if unknown.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Define conversion rules for glucocorticoid sensitivity\n", " sensitive_terms = [\"sensitive\", \"sensitivity\", \"responder\", \"responsive\", \"response\", \"untreated\", \"control\"]\n", " resistant_terms = [\"resistant\", \"resistance\", \"non-responder\", \"unresponsive\", \"no response\", \"treated\", \"dexamethasone\"]\n", " \n", " if any(term in value for term in sensitive_terms):\n", " return 1 # Sensitive\n", " elif any(term in value for term in resistant_terms):\n", " return 0 # Resistant\n", " else:\n", " return None\n", " \n", " def convert_age(value):\n", " \"\"\"Convert age values to continuous numerical values or None if unknown.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value = str(value)\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " # Try to extract numerical value\n", " import re\n", " numbers = re.findall(r'\\d+', value)\n", " if numbers:\n", " return float(numbers[0])\n", " else:\n", " return None\n", " \n", " def convert_gender(value):\n", " \"\"\"Convert gender values to binary (0=female, 1=male) or None if unknown.\"\"\"\n", " if pd.isna(value) or value is None:\n", " return None\n", " \n", " value = str(value).lower()\n", " \n", " # Extract value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if any(term in value for term in [\"female\", \"f\", \"woman\"]):\n", " return 0 # Female\n", " elif any(term in value for term in [\"male\", \"m\", \"man\"]):\n", " return 1 # Male\n", " else:\n", " return None\n", " \n", " # 3. Save Metadata\n", " # Determine trait availability\n", " is_trait_available = trait_row is not None\n", " \n", " # Conduct initial filtering and save metadata\n", " validation_result = 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", " # Only execute if trait data is available\n", " if trait_row is not None:\n", " # Extract clinical features\n", " clinical\n" ] }, { "cell_type": "markdown", "id": "7f94ecad", "metadata": {}, "source": [ "### Step 5: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": null, "id": "9d17c839", "metadata": {}, "outputs": [], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "073b009a", "metadata": {}, "source": [ "### Step 6: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": null, "id": "6f5835f8", "metadata": {}, "outputs": [], "source": [ "# Reviewing the gene identifiers in the gene expression data\n", "# The identifiers start with \"ILMN_\" which indicates these are Illumina probe IDs\n", "# These are not human gene symbols but rather probe identifiers from Illumina microarray platform\n", "# They need to be mapped to human gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True" ] } ], "metadata": {}, "nbformat": 4, "nbformat_minor": 5 }