File size: 13,879 Bytes
6bc7e45 |
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 |
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"id": "ed3d3307",
"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 = \"Allergies\"\n",
"cohort = \"GSE230164\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/Allergies\"\n",
"in_cohort_dir = \"../../input/GEO/Allergies/GSE230164\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/Allergies/GSE230164.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/Allergies/gene_data/GSE230164.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/Allergies/clinical_data/GSE230164.csv\"\n",
"json_path = \"../../output/preprocess/Allergies/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "83f25c6e",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "5dbe3593",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "f61931c3",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "48e922d6",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "e07dac68",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f6cd71d8",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"id": "d8656551",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c57135c9",
"metadata": {},
"outputs": [],
"source": [
"# First, let's load the gene expression data to examine the gene identifiers\n",
"try:\n",
" # Load gene expression data from a previous step\n",
" gene_file = os.path.join(in_cohort_dir, 'gene_expression.txt')\n",
" gene_data = pd.read_csv(gene_file, sep='\\t', index_col=0)\n",
" \n",
" # Look at the first few gene identifiers\n",
" gene_identifiers = gene_data.index.tolist()[:10] # Sample of gene identifiers\n",
" print(\"Sample gene identifiers:\", gene_identifiers)\n",
" \n",
" # Check if identifiers are likely human gene symbols\n",
" # Human gene symbols typically have format like \"BRCA1\", \"TP53\", etc.\n",
" # Other formats might be Ensembl IDs (ENSG...), Affymetrix IDs, or probe IDs\n",
" \n",
" # Simple heuristic: If most identifiers match pattern of human gene symbols\n",
" # (typically uppercase letters with some numbers, not starting with numbers)\n",
" import re\n",
" \n",
" gene_symbol_pattern = re.compile(r'^[A-Z][A-Z0-9]*$')\n",
" ensembl_pattern = re.compile(r'^ENS[A-Z]*[0-9]+')\n",
" probe_pattern = re.compile(r'^[0-9]+_')\n",
" \n",
" gene_symbol_count = sum(1 for gene_id in gene_identifiers if gene_symbol_pattern.match(gene_id))\n",
" ensembl_count = sum(1 for gene_id in gene_identifiers if ensembl_pattern.match(gene_id))\n",
" probe_count = sum(1 for gene_id in gene_identifiers if probe_pattern.match(gene_id))\n",
" \n",
" print(f\"Gene symbol pattern matches: {gene_symbol_count}/{len(gene_identifiers)}\")\n",
" print(f\"Ensembl pattern matches: {ensembl_count}/{len(gene_identifiers)}\")\n",
" print(f\"Probe pattern matches: {probe_count}/{len(gene_identifiers)}\")\n",
" \n",
" # Determine if mapping is needed\n",
" requires_gene_mapping = not (gene_symbol_count / len(gene_identifiers) > 0.8)\n",
" print(f\"requires_gene_mapping = {requires_gene_mapping}\")\n",
" \n",
"except Exception as e:\n",
" print(f\"Error examining gene identifiers: {e}\")\n",
" # If we can't determine, default to requiring mapping\n",
" requires_gene_mapping = True\n",
" print(f\"requires_gene_mapping = {requires_gene_mapping}\")\n"
]
},
{
"cell_type": "markdown",
"id": "be820d6a",
"metadata": {},
"source": [
"### Step 5: Gene Annotation"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "4b40bbd7",
"metadata": {},
"outputs": [],
"source": [
"# 1. First get the file paths using geo_get_relevant_filepaths function\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"\n",
"# 2. 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",
"# 3. 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": "4eb875c7",
"metadata": {},
"source": [
"### Step 6: Gene Identifier Mapping"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "adb23b68",
"metadata": {},
"outputs": [],
"source": [
"# 1. Let's identify the relevant columns for mapping\n",
"# Based on the preview, 'ID' seems to be the probe identifier, and 'Symbol' contains gene symbols\n",
"# These appear to match what we need for mapping\n",
"\n",
"# 2. Get gene expression data\n",
"gene_data = get_genetic_data(matrix_file)\n",
"print(f\"Gene expression data shape: {gene_data.shape}\")\n",
"print(\"First few probe IDs from gene expression data:\")\n",
"print(gene_data.index[:5])\n",
"\n",
"# 3. Get gene mapping dataframe\n",
"gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
"print(f\"Gene mapping dataframe shape: {gene_mapping.shape}\")\n",
"print(\"First few rows of gene mapping:\")\n",
"print(gene_mapping.head())\n",
"\n",
"# 4. Apply gene mapping to convert probe-level measurements to gene-level expression\n",
"gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
"print(f\"After mapping: Gene expression data shape: {gene_data.shape}\")\n",
"print(\"First few gene symbols:\")\n",
"print(gene_data.index[:10])\n",
"\n",
"# 5. Normalize gene symbols using synonym information\n",
"gene_data = normalize_gene_symbols_in_index(gene_data)\n",
"print(f\"After normalization: Gene expression data shape: {gene_data.shape}\")\n",
"print(\"First few normalized gene symbols:\")\n",
"print(gene_data.index[:10])\n",
"\n",
"# 6. Save gene data to file\n",
"os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
"gene_data.to_csv(out_gene_data_file)\n",
"print(f\"Gene expression data saved to {out_gene_data_file}\")\n"
]
},
{
"cell_type": "markdown",
"id": "a810ba3d",
"metadata": {},
"source": [
"### Step 7: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c9d33a62",
"metadata": {},
"outputs": [],
"source": [
"# 1. The gene data is already normalized in the previous step\n",
"\n",
"# 2. Link the clinical and genetic data\n",
"print(\"Extracting clinical data directly from the source...\")\n",
"# Get the matrix file again to ensure we have the proper data\n",
"soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n",
"background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n",
"\n",
"# Get unique values dictionary to identify feature rows\n",
"unique_values_dict = get_unique_values_by_row(clinical_data)\n",
"print(\"Sample characteristics (first few entries):\")\n",
"for i, (key, values) in enumerate(unique_values_dict.items()):\n",
" print(f\"{key}: {values}\")\n",
" if i > 5: # Limit output to first few entries\n",
" print(\"...\")\n",
" break\n",
"\n",
"# Define conversion functions based on the data inspection\n",
"# These would normally be defined in Step 2\n",
"def convert_trait(cell):\n",
" \"\"\"Convert allergies information to binary (1: has allergies, 0: healthy control)\"\"\"\n",
" if isinstance(cell, str):\n",
" if 'allergy' in cell.lower() or 'allergic' in cell.lower():\n",
" return 1\n",
" elif 'healthy' in cell.lower() or 'control' in cell.lower():\n",
" return 0\n",
" return None\n",
"\n",
"def convert_age(cell):\n",
" \"\"\"Extract age value from cell\"\"\"\n",
" if isinstance(cell, str) and 'age:' in cell.lower():\n",
" # Extract numbers after \"age:\"\n",
" import re\n",
" match = re.search(r'age:\\s*(\\d+)', cell.lower())\n",
" if match:\n",
" return float(match.group(1))\n",
" return None\n",
"\n",
"def convert_gender(cell):\n",
" \"\"\"Convert gender to binary (0: female, 1: male)\"\"\"\n",
" if isinstance(cell, str):\n",
" cell = cell.lower()\n",
" if 'female' in cell or 'f' in cell:\n",
" return 0\n",
" elif 'male' in cell or 'm' in cell:\n",
" return 1\n",
" return None\n",
"\n",
"# Find appropriate rows for trait, age, and gender\n",
"trait_row = None\n",
"age_row = None\n",
"gender_row = None\n",
"\n",
"# Scan through the unique values to identify feature rows\n",
"for idx, values in unique_values_dict.items():\n",
" values_str = str(values).lower()\n",
" if 'allergy' in values_str or 'allergic' in values_str or 'healthy' in values_str:\n",
" trait_row = idx\n",
" elif 'age' in values_str:\n",
" age_row = idx\n",
" elif 'gender' in values_str or 'sex' in values_str or ('male' in values_str and 'female' in values_str):\n",
" gender_row = idx\n",
"\n",
"print(f\"Identified trait_row: {trait_row}, age_row: {age_row}, gender_row: {gender_row}\")\n",
"\n",
"# Extract clinical features\n",
"if trait_row is not None:\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",
" print(\"Clinical data preview:\")\n",
" print(preview_df(selected_clinical_df))\n",
" \n",
" # Save the clinical data to a CSV file\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\"Clinical data saved to {out_clinical_data_file}\")\n",
" \n",
" # Link clinical and genetic data\n",
" print(\"Linking clinical and genetic data...\")\n",
" linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n",
" print(f\"Linked data shape: {linked_data.shape}\")\n",
" \n",
" # 3. Handle missing values in the linked data\n",
" print(\"Handling missing values...\")\n",
" linked_data = handle_missing_values(linked_data, trait)\n",
" print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n",
" \n",
" # 4. Check if trait is biased\n",
" print(\"Checking for bias in trait distribution...\")\n",
" is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
" \n",
" # 5. Final validation\n",
" note = \"Dataset contains gene expression data from peripheral blood related to food allergies.\"\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, # We have gene data\n",
" is_trait_available=True, # We've identified the trait row\n",
" is_biased=is_biased,\n",
" df=linked_data,\n",
" note=note\n",
" )\n",
" \n",
" print(f\"Dataset usability: {is_usable}\")\n",
" \n",
" # 6. Save linked data if usable\n",
" if is_usable:\n",
" os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
" linked_data.to_csv(out_data_file)\n",
" print(f\"Linked data saved to {out_data_file}\")\n",
" else:\n",
" print(\"Dataset is not usable for trait-gene association studies due to bias or other issues.\")\n",
"else:\n",
" print(\"No trait information found in the clinical data. Cannot proceed with linking.\")\n",
" # Save validation 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=False,\n",
" is_biased=None,\n",
" df=None,\n",
" note=\"No trait information found in the clinical data.\"\n",
" )\n",
" print(f\"Dataset usability: {is_usable}\")"
]
}
],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
|