File size: 21,361 Bytes
82732bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6769a68e",
   "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 = \"Stomach_Cancer\"\n",
    "cohort = \"GSE146361\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Stomach_Cancer\"\n",
    "in_cohort_dir = \"../../input/GEO/Stomach_Cancer/GSE146361\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Stomach_Cancer/GSE146361.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Stomach_Cancer/gene_data/GSE146361.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Stomach_Cancer/clinical_data/GSE146361.csv\"\n",
    "json_path = \"../../output/preprocess/Stomach_Cancer/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5fec3494",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "95949586",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Let's first list the directory contents to understand what files are available\n",
    "import os\n",
    "\n",
    "print(\"Files in the cohort directory:\")\n",
    "files = os.listdir(in_cohort_dir)\n",
    "print(files)\n",
    "\n",
    "# Adapt file identification to handle different naming patterns\n",
    "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n",
    "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n",
    "\n",
    "# If no files with these patterns are found, look for alternative file types\n",
    "if not soft_files:\n",
    "    soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n",
    "if not matrix_files:\n",
    "    matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n",
    "\n",
    "print(\"Identified SOFT files:\", soft_files)\n",
    "print(\"Identified matrix files:\", matrix_files)\n",
    "\n",
    "# Use the first files found, if any\n",
    "if len(soft_files) > 0 and len(matrix_files) > 0:\n",
    "    soft_file = os.path.join(in_cohort_dir, soft_files[0])\n",
    "    matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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(\"\\nBackground Information:\")\n",
    "    print(background_info)\n",
    "    print(\"\\nSample Characteristics Dictionary:\")\n",
    "    print(sample_characteristics_dict)\n",
    "else:\n",
    "    print(\"No appropriate files found in the directory.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "61199793",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "15d7037e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Analyze the output to determine the dataset characteristics\n",
    "\n",
    "# 1. Gene Expression Data Availability\n",
    "# From the background information, we can see this dataset contains gene expression data\n",
    "# It mentions \"gene expression profile\" and \"HumanHT-12 v3.0 Expression BeadChip array (Illumina)\"\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For the trait (Stomach Cancer), we can see all samples have \"disease: Gastric Cancer\" (key 0)\n",
    "trait_row = 0\n",
    "\n",
    "# For age, there's no information available\n",
    "age_row = None\n",
    "\n",
    "# For gender, there's no information available\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "def convert_trait(value):\n",
    "    \"\"\"Convert trait value to binary (1 for disease, 0 for control)\"\"\"\n",
    "    if not isinstance(value, str):\n",
    "        return None\n",
    "    # Extract value after colon if present\n",
    "    if \":\" in value:\n",
    "        value = value.split(\":\", 1)[1].strip()\n",
    "    \n",
    "    # All samples have gastric cancer, so all will be 1\n",
    "    if \"gastric cancer\" in value.lower():\n",
    "        return 1\n",
    "    return None\n",
    "\n",
    "def convert_age(value):\n",
    "    \"\"\"Convert age value to continuous\"\"\"\n",
    "    # Not used as age data is unavailable\n",
    "    return None\n",
    "\n",
    "def convert_gender(value):\n",
    "    \"\"\"Convert gender value to binary (0 for female, 1 for male)\"\"\"\n",
    "    # Not used as gender data is unavailable\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\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\n",
    "if trait_row is not None:\n",
    "    # Create a DataFrame from the sample characteristics dictionary\n",
    "    # Based on the sample characteristics, we know the dataset contains 27 cell lines\n",
    "    # Each cell line has the same disease status (Gastric Cancer)\n",
    "    \n",
    "    # Create the clinical data DataFrame\n",
    "    sample_chars = {\n",
    "        0: ['disease: Gastric Cancer'], \n",
    "        1: ['organism part: Stomach'], \n",
    "        2: ['cell line: Gastric Cancer Cell line'], \n",
    "        3: ['cell line: Hs746T', 'cell line: YCC-16', 'cell line: YCC-2', 'cell line: SNU-16', \n",
    "            'cell line: SNU-719', 'cell line: YCC-9', 'cell line: SNU-668', 'cell line: MKN-74', \n",
    "            'cell line: SNU-1', 'cell line: SNU-5', 'cell line: MKN-45', 'cell line: SNU-638', \n",
    "            'cell line: SNU-216', 'cell line: YCC-6', 'cell line: YCC-7', 'cell line: MKN-1', \n",
    "            'cell line: MKN-28', 'cell line: NCI-N87', 'cell line: SNU-484', 'cell line: SNU-601', \n",
    "            'cell line: SNU-620', 'cell line: YCC-3', 'cell line: YCC-11', 'cell line: YCC-1', \n",
    "            'cell line: AGS', 'cell line: KATOIII', 'cell line: SNU-520']\n",
    "    }\n",
    "    \n",
    "    # Extract cell line names from the sample characteristics\n",
    "    cell_lines = [line.split(\": \")[1] for line in sample_chars[3]]\n",
    "    \n",
    "    # Create a DataFrame with all samples having the same trait value\n",
    "    clinical_data = pd.DataFrame(index=cell_lines)\n",
    "    \n",
    "    # Add sample characteristics as columns\n",
    "    for row_idx, values in sample_chars.items():\n",
    "        # Handle the case where row 3 has multiple values (one per cell line)\n",
    "        if row_idx == 3:\n",
    "            continue  # Skip as we've already used these to create the index\n",
    "        \n",
    "        # For other rows, all cell lines share the same value\n",
    "        for value in values:\n",
    "            # Use the part before colon as column name, and after colon as value\n",
    "            if \":\" in value:\n",
    "                col_name, val = value.split(\":\", 1)\n",
    "                clinical_data[col_name.strip()] = val.strip()\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 data\n",
    "    print(\"Preview of selected clinical data:\")\n",
    "    print(preview_df(selected_clinical_df))\n",
    "    \n",
    "    # Save the data\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"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efadfcc7",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc2a6aec",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use the helper function to get the proper file paths\n",
    "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n",
    "\n",
    "# Extract gene expression data\n",
    "try:\n",
    "    gene_data = get_genetic_data(matrix_file_path)\n",
    "    \n",
    "    # Print the first 20 row IDs (gene or probe identifiers)\n",
    "    print(\"First 20 gene/probe identifiers:\")\n",
    "    print(gene_data.index[:20])\n",
    "    \n",
    "    # Print shape to understand the dataset dimensions\n",
    "    print(f\"\\nGene expression data shape: {gene_data.shape}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene data: {e}\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "786f9d52",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed1aacdb",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Based on biomedical knowledge, these are Illumina probe IDs (indicated by the \"ILMN_\" prefix)\n",
    "# and not human gene symbols. These probe IDs need to be mapped to gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "90a7c414",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "083ffd73",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n",
    "try:\n",
    "    # Use the correct variable name from previous steps\n",
    "    gene_annotation = get_gene_annotation(soft_file_path)\n",
    "    \n",
    "    # 2. Preview the gene annotation dataframe\n",
    "    print(\"Gene annotation preview:\")\n",
    "    print(preview_df(gene_annotation))\n",
    "    \n",
    "except UnicodeDecodeError as e:\n",
    "    print(f\"Unicode decoding error: {e}\")\n",
    "    print(\"Trying alternative approach...\")\n",
    "    \n",
    "    # Read the file with Latin-1 encoding which is more permissive\n",
    "    import gzip\n",
    "    import pandas as pd\n",
    "    \n",
    "    # Manually read the file line by line with error handling\n",
    "    data_lines = []\n",
    "    with gzip.open(soft_file_path, 'rb') as f:\n",
    "        for line in f:\n",
    "            # Skip lines starting with prefixes we want to filter out\n",
    "            line_str = line.decode('latin-1')\n",
    "            if not line_str.startswith('^') and not line_str.startswith('!') and not line_str.startswith('#'):\n",
    "                data_lines.append(line_str)\n",
    "    \n",
    "    # Create dataframe from collected lines\n",
    "    if data_lines:\n",
    "        gene_data_str = '\\n'.join(data_lines)\n",
    "        gene_annotation = pd.read_csv(pd.io.common.StringIO(gene_data_str), sep='\\t', low_memory=False)\n",
    "        print(\"Gene annotation preview (alternative method):\")\n",
    "        print(preview_df(gene_annotation))\n",
    "    else:\n",
    "        print(\"No valid gene annotation data found after filtering.\")\n",
    "        gene_annotation = pd.DataFrame()\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error extracting gene annotation data: {e}\")\n",
    "    gene_annotation = pd.DataFrame()\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c60de818",
   "metadata": {},
   "source": [
    "### Step 6: Gene Identifier Mapping"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9f9b46b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Determine the appropriate columns for mapping\n",
    "# Based on the preview of gene_annotation, we can see:\n",
    "# - 'ID' contains the Illumina probe IDs (same as in gene expression data)\n",
    "# - 'Symbol' contains the gene symbols we need\n",
    "\n",
    "# 2. Get the gene mapping dataframe using the specified columns\n",
    "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n",
    "\n",
    "# Print a preview of the mapping\n",
    "print(\"Preview of gene mapping:\")\n",
    "print(gene_mapping.head())\n",
    "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n",
    "\n",
    "# 3. Convert probe-level measurements to gene expression data\n",
    "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n",
    "\n",
    "# Preview the resulting gene expression data\n",
    "print(\"\\nPreview of mapped gene expression data:\")\n",
    "print(gene_data.head())\n",
    "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n",
    "\n",
    "# Normalize gene symbols to handle synonyms\n",
    "gene_data = normalize_gene_symbols_in_index(gene_data)\n",
    "print(\"\\nPreview after normalizing gene symbols:\")\n",
    "print(gene_data.head())\n",
    "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n",
    "\n",
    "# Save the processed gene data\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": "2191b622",
   "metadata": {},
   "source": [
    "### Step 7: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eeffbed2",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. Load the normalized gene data that was saved in the previous step\n",
    "try:\n",
    "    gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "    print(f\"Loaded normalized gene data shape: {gene_data.shape}\")\n",
    "except Exception as e:\n",
    "    print(f\"Error loading gene data: {e}\")\n",
    "    raise ValueError(\"Cannot proceed without gene expression data\")\n",
    "\n",
    "# 2. Load the clinical data created in Step 2\n",
    "try:\n",
    "    clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)\n",
    "    print(f\"Loaded clinical data shape: {clinical_df.shape}\")\n",
    "    print(\"Clinical data preview:\")\n",
    "    print(clinical_df.head())\n",
    "except Exception as e:\n",
    "    print(f\"Error loading clinical data: {e}\")\n",
    "    clinical_df = pd.DataFrame()\n",
    "\n",
    "# The sample IDs in the gene expression data are GSM IDs\n",
    "gene_sample_ids = gene_data.columns\n",
    "print(f\"Gene data has {len(gene_sample_ids)} samples\")\n",
    "print(f\"First few sample IDs: {list(gene_sample_ids[:5])}\")\n",
    "\n",
    "# Create a clinical DataFrame with the same sample IDs as the gene data\n",
    "# We know from previous steps that all samples are cancer cell lines (all have trait=1)\n",
    "clinical_features = pd.DataFrame(index=gene_sample_ids)\n",
    "clinical_features[trait] = 1  # All samples are gastric cancer cell lines\n",
    "\n",
    "print(f\"Prepared clinical features shape: {clinical_features.shape}\")\n",
    "print(clinical_features.head())\n",
    "\n",
    "# Link clinical and genetic data\n",
    "linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 3. Handle 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. Determine whether the trait and demographic features are biased\n",
    "is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n",
    "print(f\"Is trait biased: {is_trait_biased}\")\n",
    "print(f\"Linked data shape after removing biased features: {linked_data.shape}\")\n",
    "\n",
    "# 5. Conduct quality check and save the cohort information\n",
    "note = \"Dataset contains gene expression data from 27 gastric cancer cell lines. All samples have the same trait value (all are cancer), making the dataset unsuitable for associative studies.\"\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=True,\n",
    "    is_biased=is_trait_biased, \n",
    "    df=linked_data,\n",
    "    note=note\n",
    ")\n",
    "\n",
    "# 6. Save the linked data if it's usable\n",
    "print(f\"Data quality check result: {'Usable' if is_usable else 'Not 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(f\"Data not saved due to quality issues.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf02978c",
   "metadata": {},
   "source": [
    "### Step 8: Data Normalization and Linking"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1b6795e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 1. The gene data was already normalized in Step 6\n",
    "gene_data = pd.read_csv(out_gene_data_file, index_col=0)\n",
    "print(f\"Loaded normalized gene data shape: {gene_data.shape}\")\n",
    "\n",
    "# 2. Create clinical features for the same samples that are in the gene data\n",
    "# From previous steps, we know all samples are gastric cancer cell lines\n",
    "clinical_features = pd.DataFrame(index=gene_data.columns)\n",
    "clinical_features[trait] = 1  # All samples are gastric cancer\n",
    "print(f\"Prepared clinical features shape: {clinical_features.shape}\")\n",
    "print(clinical_features.head())\n",
    "\n",
    "# Direct approach to link clinical and genetic data\n",
    "linked_data = clinical_features.copy()\n",
    "# Add gene expression data as additional columns\n",
    "for gene in gene_data.index:\n",
    "    linked_data[gene] = gene_data.loc[gene]\n",
    "print(f\"Linked data shape: {linked_data.shape}\")\n",
    "\n",
    "# 3. Handle missing values in the linked data\n",
    "linked_data_processed = handle_missing_values(linked_data, trait)\n",
    "print(f\"Linked data shape after handling missing values: {linked_data_processed.shape}\")\n",
    "\n",
    "# 4. Determine whether the trait is biased\n",
    "is_trait_biased, linked_data_processed = judge_and_remove_biased_features(linked_data_processed, trait)\n",
    "print(f\"Is trait biased: {is_trait_biased}\")\n",
    "print(f\"Linked data shape after removing biased features: {linked_data_processed.shape}\")\n",
    "\n",
    "# 5. Conduct quality check and save cohort information\n",
    "note = \"Dataset contains gene expression data from 27 gastric cancer cell lines. All samples have the same trait value (all are cancer), making the dataset unsuitable for case-control associative studies.\"\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=True,\n",
    "    is_biased=is_trait_biased, \n",
    "    df=linked_data_processed,\n",
    "    note=note\n",
    ")\n",
    "\n",
    "# 6. Save the linked data if it's usable\n",
    "print(f\"Data quality check result: {'Usable' if is_usable else 'Not usable'}\")\n",
    "if is_usable:\n",
    "    os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n",
    "    linked_data_processed.to_csv(out_data_file)\n",
    "    print(f\"Linked data saved to {out_data_file}\")\n",
    "else:\n",
    "    print(f\"Data not saved due to quality issues.\")"
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}