File size: 16,672 Bytes
736e4a0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "6b0c75c7",
"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 = \"Anxiety_disorder\"\n",
"cohort = \"GSE60190\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Anxiety_disorder\"\n",
"in_cohort_dir = \"../../input/GEO/Anxiety_disorder/GSE60190\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Anxiety_disorder/GSE60190.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Anxiety_disorder/gene_data/GSE60190.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Anxiety_disorder/clinical_data/GSE60190.csv\"\n",
"json_path = \"../../output/preprocess/Anxiety_disorder/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "b00fb8de",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "071404aa",
"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": "67f8ed7f",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d746daa2",
"metadata": {},
"outputs": [],
"source": [
"import pandas as pd\n",
"import os\n",
"import json\n",
"import numpy as np\n",
"from typing import Dict, Any, Callable, Optional, List, Tuple\n",
"\n",
"# 1. Gene Expression Data Availability\n",
"# Based on the background information, this dataset contains gene expression data from DLPFC\n",
"# using Illumina HumanHT-12 v3 microarray, which is suitable for our analysis\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"# Examining the sample characteristics dictionary to identify relevant rows\n",
"\n",
"# For trait, we can use row 3 which has 'dx' (diagnosis) with values including 'Control', 'ED', and 'OCD'\n",
"trait_row = 3\n",
"\n",
"# For age, we can use row 5 which has 'age' values\n",
"age_row = 5\n",
"\n",
"# For gender, we can use row 7 which has 'Sex' values\n",
"gender_row = 7\n",
"\n",
"# 2.2 Data Type Conversion Functions\n",
"def convert_trait(value: str) -> int:\n",
" \"\"\"\n",
" Convert anxiety disorder trait information to binary format.\n",
" For Anxiety_disorder as the trait of interest, we consider OCD as 1 (case) and Control as 0 (control).\n",
" Exclude other conditions like ED, MDD, etc.\n",
" \n",
" Args:\n",
" value: The raw trait value from the dataset\n",
" \n",
" Returns:\n",
" int: 1 for anxiety disorder (OCD), 0 for control, None for other conditions or missing values\n",
" \"\"\"\n",
" if not value or ':' not in value:\n",
" return None\n",
" \n",
" diagnosis = value.split(':', 1)[1].strip()\n",
" \n",
" # For anxiety disorder, we consider OCD patients as cases\n",
" if diagnosis == 'OCD' or diagnosis == 'Tics': # Tics can be related to anxiety disorders\n",
" return 1\n",
" elif diagnosis == 'Control':\n",
" return 0\n",
" else:\n",
" return None # Exclude other diagnoses like ED, Bipolar, MDD\n",
"\n",
"def convert_age(value: str) -> float:\n",
" \"\"\"\n",
" Convert age information to continuous format.\n",
" \n",
" Args:\n",
" value: The raw age value from the dataset\n",
" \n",
" Returns:\n",
" float: Age in years, or None if missing\n",
" \"\"\"\n",
" if not value or ':' not in value:\n",
" return None\n",
" \n",
" try:\n",
" age_str = value.split(':', 1)[1].strip()\n",
" return float(age_str)\n",
" except (ValueError, TypeError):\n",
" return None\n",
"\n",
"def convert_gender(value: str) -> int:\n",
" \"\"\"\n",
" Convert gender information to binary format (0 for female, 1 for male).\n",
" \n",
" Args:\n",
" value: The raw gender value from the dataset\n",
" \n",
" Returns:\n",
" int: 0 for female, 1 for male, or None if missing\n",
" \"\"\"\n",
" if not value or ':' not in value:\n",
" return None\n",
" \n",
" gender = value.split(':', 1)[1].strip()\n",
" \n",
" if gender == 'F':\n",
" return 0\n",
" elif gender == 'M':\n",
" return 1\n",
" else:\n",
" return None\n",
"\n",
"# 3. Save Metadata - Perform initial filtering\n",
"# Trait data is available since trait_row is not None\n",
"is_trait_available = trait_row is not None\n",
"\n",
"# Use the validate_and_save_cohort_info function to save 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",
"# 4. Clinical Feature Extraction\n",
"# Skip this step as clinical_data from previous step is required but not available\n",
"# This will be executed in a subsequent step when clinical_data is available\n"
]
},
{
"cell_type": "markdown",
"id": "207f157d",
"metadata": {},
"source": [
"### Step 3: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "40d230c5",
"metadata": {},
"outputs": [],
"source": [
"I'll provide a properly formatted solution for this step:\n",
"\n",
"```python\n",
"import os\n",
"import json\n",
"import pandas as pd\n",
"import numpy as np\n",
"from typing import Callable, Optional, Dict, Any\n",
"\n",
"# Check what files are available in the directory\n",
"print(f\"Checking files in: {in_cohort_dir}\")\n",
"available_files = os.listdir(in_cohort_dir) if os.path.exists(in_cohort_dir) else []\n",
"print(f\"Available files: {available_files}\")\n",
"\n",
"# For GEO datasets, we typically have matrix files and series_matrix files\n",
"matrix_files = [f for f in available_files if 'matrix' in f.lower()]\n",
"print(f\"Matrix files found: {matrix_files}\")\n",
"\n",
"# Check if the gene expression data is available\n",
"is_gene_available = False\n",
"for file in available_files:\n",
" if file.endswith('.soft') or file.endswith('.txt') or 'matrix' in file.lower():\n",
" try:\n",
" with open(os.path.join(in_cohort_dir, file), 'r') as f:\n",
" content = f.read(10000) # Read first 10000 characters\n",
" # Look for indicators of gene expression data\n",
" if any(term in content.lower() for term in [\"gene_expression\", \"platform_id\", \"platform =\"]):\n",
" is_gene_available = True\n",
" break\n",
" # Filter out pure miRNA or methylation datasets\n",
" if all(term in content.lower() for term in [\"mirna\", \"microrna\"]) and \"gene expression\" not in content.lower():\n",
" is_gene_available = False\n",
" if \"methylation\" in content.lower() and \"gene expression\" not in content.lower():\n",
" is_gene_available = False\n",
" except Exception as e:\n",
" print(f\"Error checking file {file}: {e}\")\n",
"\n",
"# Load sample characteristics if available\n",
"sample_characteristics = {}\n",
"clinical_data = None\n",
"\n",
"# Try different file patterns for clinical data\n",
"possible_clinical_files = [\n",
" os.path.join(in_cohort_dir, \"clinical_data.csv\"),\n",
" os.path.join(in_cohort_dir, \"GSE60190_series_matrix.txt\"),\n",
" os.path.join(in_cohort_dir, \"series_matrix.txt\")\n",
"]\n",
"\n",
"for file_path in possible_clinical_files:\n",
" if os.path.exists(file_path):\n",
" print(f\"Found clinical data file: {file_path}\")\n",
" if file_path.endswith('.csv'):\n",
" clinical_data = pd.read_csv(file_path)\n",
" else:\n",
" # For series_matrix files, we need to parse the !Sample_characteristics lines\n",
" try:\n",
" with open(file_path, 'r') as f:\n",
" lines = f.readlines()\n",
" \n",
" # Extract sample characteristics lines\n",
" char_lines = [line.strip() for line in lines if line.startswith(\"!Sample_characteristics\")]\n",
" \n",
" # Parse sample characteristics\n",
" for i, line in enumerate(char_lines):\n",
" # Extract values after the equals sign\n",
" values = [part.split(\"=\")[1].strip() if \"=\" in part else part.strip() \n",
" for part in line.split(\"\\t\")[1:]]\n",
" if values:\n",
" sample_characteristics[i] = values\n",
" \n",
" # Also create a dataframe from the characteristics\n",
" if sample_characteristics:\n",
" # Convert to a format suitable for a dataframe\n",
" samples = list(set([val for sublist in sample_characteristics.values() for val in sublist]))\n",
" clinical_data = pd.DataFrame(index=range(len(sample_characteristics)), \n",
" columns=['characteristic'] + samples)\n",
" for i, values in sample_characteristics.items():\n",
" clinical_data.iloc[i, 0] = f\"characteristic_{i}\"\n",
" for val in values:\n",
" clinical_data.loc[i, val] = val\n",
" except Exception as e:\n",
" print(f\"Error parsing series matrix file: {e}\")\n",
" break\n",
"\n",
"if clinical_data is None and sample_characteristics:\n",
" # If we have sample characteristics but no dataframe, create one\n",
" clinical_data = pd.DataFrame()\n",
" for i, values in sample_characteristics.items():\n",
" clinical_data.loc[i, 'characteristic'] = f\"characteristic_{i}\"\n",
" for val in values:\n",
" clinical_data.loc[i, val] = val\n",
"\n",
"# Also check for a background info file\n",
"background_info = \"\"\n",
"background_path = os.path.join(in_cohort_dir, \"background_info.txt\")\n",
"if os.path.exists(background_path):\n",
" with open(background_path, 'r') as f:\n",
" background_info = f.read()\n",
" print(\"\\nBackground Info:\")\n",
" print(background_info)\n",
"\n",
"# Print sample characteristics for analysis\n",
"print(\"\\nSample Characteristics:\")\n",
"for key, values in sample_characteristics.items():\n",
" print(f\"Row {key}: {values}\")\n",
"\n",
"# Based on available information, determine trait, age, and gender data\n",
"trait_row = None\n",
"age_row = None\n",
"gender_row = None\n",
"\n",
"# Check each row in sample characteristics to identify relevant data\n",
"for key, values in sample_characteristics.items():\n",
" # Convert values to strings for easier analysis\n",
" str_values = [str(v).lower() if v is not None else \"\" for v in values]\n",
" joined_values = \" \".join(str_values).lower()\n",
" \n",
" # Look for anxiety-related terms\n",
" if any(term in joined_values for term in [\"anxiety\", \"anxious\", \"anx\", \"gad\", \"panic\", \"diagnosis\", \"condition\", \"disorder\"]):\n",
" trait_row = key\n",
" \n",
" # Look for age-related terms\n",
" if any(term in joined_values for term in [\"age\", \"years\", \"yr\", \"yrs\"]):\n",
" age_row = key\n",
" \n",
" # Look for gender-related terms\n",
" if any(term in joined_values for term in [\"gender\", \"sex\", \"male\", \"female\"]):\n",
" gender_row = key\n",
"\n",
"# Define conversion functions\n",
"def convert_trait(value):\n",
" if value is None:\n",
" return None\n",
" \n",
" # Extract value after colon if present\n",
" if isinstance(value, str) and \":\" in value:\n",
" value = value.split(\":\", 1)[1].strip()\n",
" \n",
" value_lower = str(value).lower()\n",
" \n",
" # Look for anxiety indicators\n",
" if any(term in value_lower for term in [\"anxiety\", \"anxious\", \"anxiety disorder\", \"gad\", \"panic\"]):\n",
" return 1\n",
" elif any(term in value_lower for term in [\"control\", \"healthy\", \"normal\", \"none\"]):\n",
" return 0\n",
" else:\n",
" return None\n",
"\n",
"def convert_age(value):\n",
" if value is None:\n",
" return None\n",
" \n",
" # Extract value after 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\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",
" else:\n",
" return None\n",
"\n",
"def convert_gender(value):\n",
" if value is None:\n",
" return None\n",
" \n",
" # Extract value after colon if present\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(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",
" else:\n",
" return None\n",
"\n",
"# 3. Save Metadata - 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. Clinical Feature Extraction (if trait data is available and clinical data exists)\n",
"if trait_row is not None and clinical_data is not None:\n",
" # Extract clinical features\n",
" selected_clinical_df = geo_select_clinical_features("
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
|