File size: 33,401 Bytes
e4183cf |
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 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "8baceca3",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:32.694860Z",
"iopub.status.busy": "2025-03-25T08:31:32.694467Z",
"iopub.status.idle": "2025-03-25T08:31:32.860457Z",
"shell.execute_reply": "2025-03-25T08:31:32.860126Z"
}
},
"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 = \"COVID-19\"\n",
"cohort = \"GSE243348\"\n",
"\n",
"# Input paths\n",
"in_trait_dir = \"../../input/GEO/COVID-19\"\n",
"in_cohort_dir = \"../../input/GEO/COVID-19/GSE243348\"\n",
"\n",
"# Output paths\n",
"out_data_file = \"../../output/preprocess/COVID-19/GSE243348.csv\"\n",
"out_gene_data_file = \"../../output/preprocess/COVID-19/gene_data/GSE243348.csv\"\n",
"out_clinical_data_file = \"../../output/preprocess/COVID-19/clinical_data/GSE243348.csv\"\n",
"json_path = \"../../output/preprocess/COVID-19/cohort_info.json\"\n"
]
},
{
"cell_type": "markdown",
"id": "18459c40",
"metadata": {},
"source": [
"### Step 1: Initial Data Loading"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "5b3217be",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:32.861843Z",
"iopub.status.busy": "2025-03-25T08:31:32.861701Z",
"iopub.status.idle": "2025-03-25T08:31:32.883906Z",
"shell.execute_reply": "2025-03-25T08:31:32.883615Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Background Information:\n",
"!Series_title\t\"Longitudinal gene expression profiling of self-collected blood samples in COVID-19+ and healthy participants\"\n",
"!Series_summary\t\"Longitudinal cohort: 773 host response genes were profiled in previously vaccinated (n=16) and unvaccinated (n=14) COVID-19+ participants along with 5 healthy uninfected controls across a 2-week observational window\"\n",
"!Series_summary\t\"Single timepoint cohort: 773 host response genes were profiled in 6 healthy uninfected participants\"\n",
"!Series_overall_design\t\"Longitudinal cohort: 30 COVID-19+ and 5 uninfected participants were asked perform self-collection and stabilization of capillary blood using a novel technology (homeRNA) every other day for two weeks (7 longtiudinal timepoints per participant). Temporal kinetics of 773 immune genes were profiled using the nCounter direct digital counting of native mRNA.\"\n",
"!Series_overall_design\t\"Single timepoint cohort: 6 healthy uninfected participants were asked perform self-collection and stabilization of capillary blood using a novel technology (homeRNA). Temporal kinetics of 773 immune genes were profiled using the nCounter direct digital counting of native mRNA.\"\n",
"Sample Characteristics Dictionary:\n",
"{0: ['disease status: COVID-19+', 'disease status: Healthy uninfected'], 1: ['participant id: CB0101', 'participant id: CB0102', 'participant id: CB0104', 'participant id: CB0106', 'participant id: CB0107', 'participant id: CB0111', 'participant id: CB0112', 'participant id: CB0113', 'participant id: CB0115', 'participant id: CB0116', 'participant id: CB0117', 'participant id: CB0118', 'participant id: CB0119', 'participant id: CB0120', 'participant id: CB0121', 'participant id: CB0122', 'participant id: CB0123', 'participant id: CB0124', 'participant id: CB0125', 'participant id: CB0128', 'participant id: CB0129', 'participant id: CB0130', 'participant id: CB0131', 'participant id: CB0132', 'participant id: CB0133', 'participant id: CB0134', 'participant id: CB0135', 'participant id: CB0136', 'participant id: CB0138', 'participant id: CB0139'], 2: ['Sex: female', 'Sex: male'], 3: ['age: 44', 'age: 29', 'age: 51', 'age: 32', 'age: 27', 'age: 30', 'age: 41', 'age: 43', 'age: 34', 'age: 60', 'age: 24', 'age: 36', 'age: 33', 'age: 53', 'age: 31', 'age: 59', 'age: 40', 'age: 65', 'age: 37', 'age: 39', 'age: 58', 'age: 42', 'age: 28', 'age: 38'], 4: ['covid-19 vaccination history: unvaccinated', 'covid-19 vaccination history: vaccinated', 'covid-19 vaccination history: partial'], 5: ['day post symptom onset: 10', 'day post symptom onset: 13', 'day post symptom onset: 15', 'day post symptom onset: 17', 'day post symptom onset: 19', 'day post symptom onset: 21', 'day post symptom onset: 23', 'day post symptom onset: 9', 'day post symptom onset: 11', 'day post symptom onset: 8', 'day post symptom onset: 12', 'day post symptom onset: 14', 'day post symptom onset: 16', 'day post symptom onset: 18', 'day post symptom onset: 20', 'day post symptom onset: 27', 'day post symptom onset: 25', 'day post symptom onset: 5', 'day post symptom onset: 7', 'day post symptom onset: 6', 'day post symptom onset: 22', 'day post symptom onset: 24', 'day post symptom onset: 26', 'day post symptom onset: 28', 'study day: 1', 'study day: 3', 'study day: 5', 'study day: 7', 'study day: 9', 'study day: 11'], 6: ['study day: 1', 'study day: 4', 'study day: 6', 'study day: 8', 'study day: 10', 'study day: 12', 'study day: 14', 'study day: 3', 'study day: 5', 'study day: 9', 'study day: 11', 'study day: 13', 'study day: 7', 'study day: 15', 'ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1'], 7: ['ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1', nan]}\n"
]
}
],
"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": "4c297b26",
"metadata": {},
"source": [
"### Step 2: Dataset Analysis and Clinical Feature Extraction"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "f3d4de96",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:32.884964Z",
"iopub.status.busy": "2025-03-25T08:31:32.884858Z",
"iopub.status.idle": "2025-03-25T08:31:32.918521Z",
"shell.execute_reply": "2025-03-25T08:31:32.918240Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Clinical data preview:\n",
"{'sample_0': [1.0, nan, nan], 'sample_1': [0.0, nan, nan], 'sample_2': [nan, nan, nan], 'sample_3': [nan, nan, nan], 'sample_4': [nan, nan, nan], 'sample_5': [nan, nan, nan], 'sample_6': [nan, nan, nan], 'sample_7': [nan, nan, nan], 'sample_8': [nan, nan, nan], 'sample_9': [nan, nan, nan], 'sample_10': [nan, nan, nan], 'sample_11': [nan, nan, nan], 'sample_12': [nan, nan, nan], 'sample_13': [nan, nan, nan], 'sample_14': [nan, nan, nan], 'sample_15': [nan, nan, nan], 'sample_16': [nan, nan, nan], 'sample_17': [nan, nan, nan], 'sample_18': [nan, nan, nan], 'sample_19': [nan, nan, nan], 'sample_20': [nan, nan, nan], 'sample_21': [nan, nan, nan], 'sample_22': [nan, nan, nan], 'sample_23': [nan, nan, nan], 'sample_24': [nan, nan, nan], 'sample_25': [nan, nan, nan], 'sample_26': [nan, nan, nan], 'sample_27': [nan, nan, nan], 'sample_28': [nan, nan, nan], 'sample_29': [nan, nan, nan], 'sample_30': [nan, nan, nan], 'sample_31': [nan, nan, nan], 'sample_32': [nan, nan, 0.0], 'sample_33': [nan, nan, 1.0], 'sample_34': [nan, 44.0, nan], 'sample_35': [nan, 29.0, nan], 'sample_36': [nan, 51.0, nan], 'sample_37': [nan, 32.0, nan], 'sample_38': [nan, 27.0, nan], 'sample_39': [nan, 30.0, nan], 'sample_40': [nan, 41.0, nan], 'sample_41': [nan, 43.0, nan], 'sample_42': [nan, 34.0, nan], 'sample_43': [nan, 60.0, nan], 'sample_44': [nan, 24.0, nan], 'sample_45': [nan, 36.0, nan], 'sample_46': [nan, 33.0, nan], 'sample_47': [nan, 53.0, nan], 'sample_48': [nan, 31.0, nan], 'sample_49': [nan, 59.0, nan], 'sample_50': [nan, 40.0, nan], 'sample_51': [nan, 65.0, nan], 'sample_52': [nan, 37.0, nan], 'sample_53': [nan, 39.0, nan], 'sample_54': [nan, 58.0, nan], 'sample_55': [nan, 42.0, nan], 'sample_56': [nan, 28.0, nan], 'sample_57': [nan, 38.0, nan], 'sample_58': [nan, nan, nan], 'sample_59': [nan, nan, nan], 'sample_60': [nan, nan, nan], 'sample_61': [nan, nan, nan], 'sample_62': [nan, nan, nan], 'sample_63': [nan, nan, nan], 'sample_64': [nan, nan, nan], 'sample_65': [nan, nan, nan], 'sample_66': [nan, nan, nan], 'sample_67': [nan, nan, nan], 'sample_68': [nan, nan, nan], 'sample_69': [nan, nan, nan], 'sample_70': [nan, nan, nan], 'sample_71': [nan, nan, nan], 'sample_72': [nan, nan, nan], 'sample_73': [nan, nan, nan], 'sample_74': [nan, nan, nan], 'sample_75': [nan, nan, nan], 'sample_76': [nan, nan, nan], 'sample_77': [nan, nan, nan], 'sample_78': [nan, nan, nan], 'sample_79': [nan, nan, nan], 'sample_80': [nan, nan, nan], 'sample_81': [nan, nan, nan], 'sample_82': [nan, nan, nan], 'sample_83': [nan, nan, nan], 'sample_84': [nan, nan, nan], 'sample_85': [nan, nan, nan], 'sample_86': [nan, nan, nan], 'sample_87': [nan, nan, nan], 'sample_88': [nan, nan, nan], 'sample_89': [nan, nan, nan], 'sample_90': [nan, nan, nan], 'sample_91': [nan, nan, nan], 'sample_92': [nan, nan, nan], 'sample_93': [nan, nan, nan], 'sample_94': [nan, nan, nan], 'sample_95': [nan, nan, nan], 'sample_96': [nan, nan, nan], 'sample_97': [nan, nan, nan], 'sample_98': [nan, nan, nan], 'sample_99': [nan, nan, nan], 'sample_100': [nan, nan, nan], 'sample_101': [nan, nan, nan], 'sample_102': [nan, nan, nan], 'sample_103': [nan, nan, nan], 'sample_104': [nan, nan, nan], 'sample_105': [nan, nan, nan], 'sample_106': [nan, nan, nan], 'sample_107': [nan, nan, nan], 'sample_108': [nan, nan, nan], 'sample_109': [nan, nan, nan]}\n",
"Clinical data saved to ../../output/preprocess/COVID-19/clinical_data/GSE243348.csv\n"
]
},
{
"name": "stderr",
"output_type": "stream",
"text": [
"/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
" clinical_data[col_name] = None\n",
"/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
" clinical_data[col_name] = None\n",
"/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
" clinical_data[col_name] = None\n",
"/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
" clinical_data[col_name] = None\n",
"/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
" clinical_data[col_name] = None\n",
"/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
" clinical_data[col_name] = None\n",
"/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
" clinical_data[col_name] = None\n",
"/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
" clinical_data[col_name] = None\n",
"/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
" clinical_data[col_name] = None\n",
"/tmp/ipykernel_75088/1254858355.py:96: PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling `frame.insert` many times, which has poor performance. Consider joining all columns at once using pd.concat(axis=1) instead. To get a de-fragmented frame, use `newframe = frame.copy()`\n",
" clinical_data[col_name] = None\n"
]
}
],
"source": [
"# 1. Gene Expression Data Availability\n",
"# Based on the background information, this dataset contains gene expression data\n",
"# \"773 host response genes were profiled using the nCounter direct digital counting of native mRNA\"\n",
"is_gene_available = True\n",
"\n",
"# 2. Variable Availability and Data Type Conversion\n",
"# 2.1 Data Availability\n",
"\n",
"# Trait (COVID-19 status) is in row 0\n",
"trait_row = 0\n",
"\n",
"# Age is in row 3\n",
"age_row = 3\n",
"\n",
"# Gender is in row 2\n",
"gender_row = 2\n",
"\n",
"# 2.2 Data Type Conversion\n",
"\n",
"def convert_trait(value: str) -> int:\n",
" \"\"\"\n",
" Convert COVID-19 status to binary (0 for healthy, 1 for COVID-19+)\n",
" \"\"\"\n",
" if not isinstance(value, str):\n",
" return None\n",
" \n",
" value_lower = value.lower()\n",
" if 'covid-19+' in value_lower:\n",
" return 1\n",
" elif 'healthy' in value_lower:\n",
" return 0\n",
" return None\n",
"\n",
"def convert_age(value: str) -> float:\n",
" \"\"\"\n",
" Convert age values to continuous numeric values\n",
" \"\"\"\n",
" if not isinstance(value, str):\n",
" return None\n",
" \n",
" try:\n",
" # Extract the number after the colon\n",
" parts = value.split(': ')\n",
" if len(parts) > 1:\n",
" return float(parts[1])\n",
" return None\n",
" except:\n",
" return None\n",
"\n",
"def convert_gender(value: str) -> int:\n",
" \"\"\"\n",
" Convert gender to binary (0 for female, 1 for male)\n",
" \"\"\"\n",
" if not isinstance(value, str):\n",
" return None\n",
" \n",
" value_lower = value.lower()\n",
" if 'female' in value_lower:\n",
" return 0\n",
" elif 'male' in value_lower:\n",
" return 1\n",
" return None\n",
"\n",
"# 3. Save Metadata\n",
"# Check if trait data is available\n",
"is_trait_available = trait_row is not None\n",
"validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
" is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n",
"\n",
"# 4. Clinical Feature Extraction\n",
"if trait_row is not None:\n",
" # Sample characteristics were provided in the previous step\n",
" # Create a properly structured DataFrame where each row is a characteristic\n",
" # and columns represent different samples\n",
" \n",
" # First, create an empty DataFrame with the sample characteristics as rows\n",
" clinical_data = pd.DataFrame(index=range(8)) # 8 rows for the characteristics\n",
" \n",
" # Add sample characteristics as rows\n",
" sample_chars = {\n",
" 0: ['disease status: COVID-19+', 'disease status: Healthy uninfected'],\n",
" 1: ['participant id: CB0101', 'participant id: CB0102', 'participant id: CB0104', 'participant id: CB0106', 'participant id: CB0107', 'participant id: CB0111', 'participant id: CB0112', 'participant id: CB0113', 'participant id: CB0115', 'participant id: CB0116', 'participant id: CB0117', 'participant id: CB0118', 'participant id: CB0119', 'participant id: CB0120', 'participant id: CB0121', 'participant id: CB0122', 'participant id: CB0123', 'participant id: CB0124', 'participant id: CB0125', 'participant id: CB0128', 'participant id: CB0129', 'participant id: CB0130', 'participant id: CB0131', 'participant id: CB0132', 'participant id: CB0133', 'participant id: CB0134', 'participant id: CB0135', 'participant id: CB0136', 'participant id: CB0138', 'participant id: CB0139'],\n",
" 2: ['Sex: female', 'Sex: male'],\n",
" 3: ['age: 44', 'age: 29', 'age: 51', 'age: 32', 'age: 27', 'age: 30', 'age: 41', 'age: 43', 'age: 34', 'age: 60', 'age: 24', 'age: 36', 'age: 33', 'age: 53', 'age: 31', 'age: 59', 'age: 40', 'age: 65', 'age: 37', 'age: 39', 'age: 58', 'age: 42', 'age: 28', 'age: 38'],\n",
" 4: ['covid-19 vaccination history: unvaccinated', 'covid-19 vaccination history: vaccinated', 'covid-19 vaccination history: partial'],\n",
" 5: ['day post symptom onset: 10', 'day post symptom onset: 13', 'day post symptom onset: 15', 'day post symptom onset: 17', 'day post symptom onset: 19', 'day post symptom onset: 21', 'day post symptom onset: 23', 'day post symptom onset: 9', 'day post symptom onset: 11', 'day post symptom onset: 8', 'day post symptom onset: 12', 'day post symptom onset: 14', 'day post symptom onset: 16', 'day post symptom onset: 18', 'day post symptom onset: 20', 'day post symptom onset: 27', 'day post symptom onset: 25', 'day post symptom onset: 5', 'day post symptom onset: 7', 'day post symptom onset: 6', 'day post symptom onset: 22', 'day post symptom onset: 24', 'day post symptom onset: 26', 'day post symptom onset: 28', 'study day: 1', 'study day: 3', 'study day: 5', 'study day: 7', 'study day: 9', 'study day: 11'],\n",
" 6: ['study day: 1', 'study day: 4', 'study day: 6', 'study day: 8', 'study day: 10', 'study day: 12', 'study day: 14', 'study day: 3', 'study day: 5', 'study day: 9', 'study day: 11', 'study day: 13', 'study day: 7', 'study day: 15', 'ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1'],\n",
" 7: ['ncounter host response codeset: V1.0', 'ncounter host response codeset: V1.1', None]\n",
" }\n",
" \n",
" # Populate the DataFrame with the sample characteristics\n",
" for idx, values in sample_chars.items():\n",
" for val in values:\n",
" # Create a new column for each unique value\n",
" col_name = f\"sample_{len(clinical_data.columns)}\"\n",
" clinical_data[col_name] = None\n",
" clinical_data.at[idx, col_name] = val\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 and save the data\n",
" preview = preview_df(selected_clinical_df)\n",
" print(\"Clinical data preview:\")\n",
" print(preview)\n",
" \n",
" # Create directory if it doesn't exist\n",
" os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n",
" \n",
" # Save the clinical data\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": "66110b1f",
"metadata": {},
"source": [
"### Step 3: Gene Data Extraction"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "28a1519a",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:32.919524Z",
"iopub.status.busy": "2025-03-25T08:31:32.919425Z",
"iopub.status.idle": "2025-03-25T08:31:32.957929Z",
"shell.execute_reply": "2025-03-25T08:31:32.957640Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"SOFT file: ../../input/GEO/COVID-19/GSE243348/GSE243348_family.soft.gz\n",
"Matrix file: ../../input/GEO/COVID-19/GSE243348/GSE243348_series_matrix.txt.gz\n",
"Found the matrix table marker at line 69\n",
"Gene data shape: (773, 237)\n",
"First 20 gene/probe identifiers:\n",
"['ACE', 'ACKR2', 'ACKR3', 'ACKR4', 'ACOX1', 'ACSL1', 'ACSL3', 'ACSL4', 'ACVR1', 'ADAR', 'ADGRE5', 'ADGRG3', 'ADORA2A', 'AGT', 'AHR', 'AIF1', 'AIM2', 'AKT1', 'AKT2', 'AKT3']\n"
]
}
],
"source": [
"# 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",
"print(f\"SOFT file: {soft_file}\")\n",
"print(f\"Matrix file: {matrix_file}\")\n",
"\n",
"# Set gene availability flag\n",
"is_gene_available = True # Initially assume gene data is available\n",
"\n",
"# First check if the matrix file contains the expected marker\n",
"found_marker = False\n",
"marker_row = None\n",
"try:\n",
" with gzip.open(matrix_file, 'rt') as file:\n",
" for i, line in enumerate(file):\n",
" if \"!series_matrix_table_begin\" in line:\n",
" found_marker = True\n",
" marker_row = i\n",
" print(f\"Found the matrix table marker at line {i}\")\n",
" break\n",
" \n",
" if not found_marker:\n",
" print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n",
" is_gene_available = False\n",
" \n",
" # If marker was found, try to extract gene data\n",
" if is_gene_available:\n",
" try:\n",
" # Try using the library function\n",
" gene_data = get_genetic_data(matrix_file)\n",
" \n",
" if gene_data.shape[0] == 0:\n",
" print(\"Warning: Extracted gene data has 0 rows.\")\n",
" is_gene_available = False\n",
" else:\n",
" print(f\"Gene data shape: {gene_data.shape}\")\n",
" # Print the first 20 gene/probe identifiers\n",
" print(\"First 20 gene/probe identifiers:\")\n",
" print(gene_data.index[:20].tolist())\n",
" except Exception as e:\n",
" print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n",
" is_gene_available = False\n",
" \n",
" # If gene data extraction failed, examine file content to diagnose\n",
" if not is_gene_available:\n",
" print(\"Examining file content to diagnose the issue:\")\n",
" try:\n",
" with gzip.open(matrix_file, 'rt') as file:\n",
" # Print lines around the marker if found\n",
" if marker_row is not None:\n",
" for i, line in enumerate(file):\n",
" if i >= marker_row - 2 and i <= marker_row + 10:\n",
" print(f\"Line {i}: {line.strip()[:100]}...\")\n",
" if i > marker_row + 10:\n",
" break\n",
" else:\n",
" # If marker not found, print first 10 lines\n",
" for i, line in enumerate(file):\n",
" if i < 10:\n",
" print(f\"Line {i}: {line.strip()[:100]}...\")\n",
" else:\n",
" break\n",
" except Exception as e2:\n",
" print(f\"Error examining file: {e2}\")\n",
" \n",
"except Exception as e:\n",
" print(f\"Error processing file: {e}\")\n",
" is_gene_available = False\n",
"\n",
"# Update validation information if gene data extraction failed\n",
"if not is_gene_available:\n",
" print(\"Gene expression data could not be successfully extracted from this dataset.\")\n",
" # Update the validation record since gene data isn't available\n",
" is_trait_available = False # We already determined trait data isn't available in step 2\n",
" validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n",
" is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n"
]
},
{
"cell_type": "markdown",
"id": "0723d070",
"metadata": {},
"source": [
"### Step 4: Gene Identifier Review"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "527c0ff2",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:32.958909Z",
"iopub.status.busy": "2025-03-25T08:31:32.958809Z",
"iopub.status.idle": "2025-03-25T08:31:32.960512Z",
"shell.execute_reply": "2025-03-25T08:31:32.960251Z"
}
},
"outputs": [],
"source": [
"# Review gene identifiers\n",
"# These identifiers appear to be standard human gene symbols (official gene symbols)\n",
"# Examples like ACE, ACKR2, AKT1, etc. are recognized human gene symbols\n",
"# No mapping is required as they are already in the correct format\n",
"\n",
"requires_gene_mapping = False\n"
]
},
{
"cell_type": "markdown",
"id": "d153c38f",
"metadata": {},
"source": [
"### Step 5: Data Normalization and Linking"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "57c0706f",
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-25T08:31:32.961470Z",
"iopub.status.busy": "2025-03-25T08:31:32.961373Z",
"iopub.status.idle": "2025-03-25T08:31:33.135284Z",
"shell.execute_reply": "2025-03-25T08:31:33.134966Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Gene data shape after normalization: (758, 237)\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Normalized gene data saved to ../../output/preprocess/COVID-19/gene_data/GSE243348.csv\n",
"Loaded clinical data with shape: (3, 110)\n",
"Clinical data columns: Index(['sample_0', 'sample_1', 'sample_2', 'sample_3', 'sample_4'], dtype='object') ...\n",
"Clinical data sparsity: 91.52% missing values\n",
"Non-NA values per clinical feature: [2, 24, 2]\n",
"Cannot proceed with linking due to insufficient clinical data (mostly NaN values).\n",
"Abnormality detected in the cohort: GSE243348. Preprocessing failed.\n"
]
}
],
"source": [
"# 1. Normalize gene symbols in gene expression data\n",
"try:\n",
" # Normalize gene symbols\n",
" normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n",
" print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n",
" \n",
" # Create output directory if it doesn't exist\n",
" os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n",
" \n",
" # Save the normalized gene data\n",
" normalized_gene_data.to_csv(out_gene_data_file)\n",
" print(f\"Normalized gene data saved to {out_gene_data_file}\")\n",
" \n",
" # 2. Attempt to load clinical data and link with genetic data\n",
" try:\n",
" # Load clinical data file saved in Step 2\n",
" clinical_df = pd.read_csv(out_clinical_data_file)\n",
" print(f\"Loaded clinical data with shape: {clinical_df.shape}\")\n",
" \n",
" # Inspect the clinical data structure\n",
" print(\"Clinical data columns:\", clinical_df.columns[:5], \"...\" if len(clinical_df.columns) > 5 else \"\")\n",
" \n",
" # Check for sparsity in clinical data\n",
" sparsity = clinical_df.isna().sum().sum() / (clinical_df.shape[0] * clinical_df.shape[1])\n",
" print(f\"Clinical data sparsity: {sparsity:.2%} missing values\")\n",
" \n",
" # Count non-NA values in each row of clinical data\n",
" non_na_counts = clinical_df.notna().sum(axis=1)\n",
" print(f\"Non-NA values per clinical feature: {non_na_counts.tolist()}\")\n",
" \n",
" # Since the clinical data has too many NaN values (as observed in Step 2),\n",
" # and does not contain proper trait information, we cannot link it effectively\n",
" is_trait_available = False\n",
" print(\"Cannot proceed with linking due to insufficient clinical data (mostly NaN values).\")\n",
" \n",
" # 5. Validate and save cohort info - mark as not usable due to lack of trait data\n",
" is_biased = True # Since we can't even analyze trait distribution\n",
" 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=is_trait_available,\n",
" is_biased=is_biased,\n",
" df=pd.DataFrame(), # Empty dataframe since we don't have linked data\n",
" note=\"Gene expression data available but clinical data contains too many missing values for effective linking.\"\n",
" )\n",
" \n",
" except Exception as e:\n",
" print(f\"Error processing clinical data: {e}\")\n",
" is_trait_available = False\n",
" \n",
" # Validate with proper values for unavailable trait data\n",
" 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=is_trait_available,\n",
" is_biased=True,\n",
" df=pd.DataFrame(),\n",
" note=f\"Error processing clinical data: {str(e)}\"\n",
" )\n",
" \n",
"except Exception as e:\n",
" print(f\"Error in gene data processing: {e}\")\n",
" \n",
" # Log the error and mark the dataset as unusable\n",
" validate_and_save_cohort_info(\n",
" is_final=True,\n",
" cohort=cohort,\n",
" info_path=json_path,\n",
" is_gene_available=False,\n",
" is_trait_available=False,\n",
" is_biased=True,\n",
" df=pd.DataFrame(),\n",
" note=f\"Error during gene data normalization: {str(e)}\"\n",
" )"
]
}
],
"metadata": {
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.16"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|