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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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "8927c3e9",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:43:53.864295Z",
     "iopub.status.busy": "2025-03-25T04:43:53.864193Z",
     "iopub.status.idle": "2025-03-25T04:43:54.023869Z",
     "shell.execute_reply": "2025-03-25T04:43:54.023528Z"
    }
   },
   "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 = \"Vitamin_D_Levels\"\n",
    "cohort = \"GSE33544\"\n",
    "\n",
    "# Input paths\n",
    "in_trait_dir = \"../../input/GEO/Vitamin_D_Levels\"\n",
    "in_cohort_dir = \"../../input/GEO/Vitamin_D_Levels/GSE33544\"\n",
    "\n",
    "# Output paths\n",
    "out_data_file = \"../../output/preprocess/Vitamin_D_Levels/GSE33544.csv\"\n",
    "out_gene_data_file = \"../../output/preprocess/Vitamin_D_Levels/gene_data/GSE33544.csv\"\n",
    "out_clinical_data_file = \"../../output/preprocess/Vitamin_D_Levels/clinical_data/GSE33544.csv\"\n",
    "json_path = \"../../output/preprocess/Vitamin_D_Levels/cohort_info.json\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "92ae2f55",
   "metadata": {},
   "source": [
    "### Step 1: Initial Data Loading"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f2cd48bc",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:43:54.025270Z",
     "iopub.status.busy": "2025-03-25T04:43:54.025123Z",
     "iopub.status.idle": "2025-03-25T04:43:54.053925Z",
     "shell.execute_reply": "2025-03-25T04:43:54.053633Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Files in the cohort directory:\n",
      "['GSE33544_family.soft.gz', 'GSE33544_series_matrix.txt.gz']\n",
      "Identified SOFT files: ['GSE33544_family.soft.gz']\n",
      "Identified matrix files: ['GSE33544_series_matrix.txt.gz']\n",
      "\n",
      "Background Information:\n",
      "!Series_title\t\"Human B cell receptor light chain repertoire analysis in healthy individuals and SLE patients\"\n",
      "!Series_summary\t\"Determination of expression levels of light chain V genes in peripheral blood B cells after FACS sorting for two populations of B cells (CD20+CD138-IgKappa+IgLambda- and CD20+CD138-IgKappa-IgLambda+).  Analysis was performed on healthy individuals and SLE patients with analysis performed using several models.\"\n",
      "!Series_overall_design\t\"Dual channel hybridization with experimental samples detected on red channel and reference sample detected on green channel.  Two replicate hybridizations.\"\n",
      "\n",
      "Sample Characteristics Dictionary:\n",
      "{0: ['disease state: Healthy', 'disease state: SLE', 'disease state: N/A'], 1: ['individual: Healthy01', 'individual: Healthy02', 'individual: Healthy03', 'individual: Healthy04', 'individual: Healthy05', 'individual: Healthy06', 'individual: Healthy07', 'individual: Healthy08', 'individual: Healthy09', 'individual: Healthy10', 'individual: SLE01', 'individual: SLE02', 'individual: SLE03', 'individual: SLE04', 'individual: SLE05', 'individual: SLE06', 'individual: SLE07', 'individual: SLE08', 'individual: SLE09', 'individual: SLE10', 'sample type: Standard 1, Reference sample with reverse complement of B3 spiked in a 5.3% and 2-13 spiked in at 26%', 'sample type: Standard 2, Reference sample withreverse complement of B3 spiked in at 10.8% and 2-13 spiked in at 10.8%', 'sample type: Standard 3, Reference sample with reverse complement of B3 spiked in at 26.0% and 2-13 spiked in at 5.2%', 'sample type: Standard 4, Reference sample with reverse complement of O2/O12 spiked in at 2.2% and 1-19 spiked in at 11.1%', 'sample type: Standard 5, Reference sample with reverse complement of O2/O12 spiked in at 4.7% and 1-19 at 4.7%'], 2: ['cell type: FACS sorted peripheral blood B cells with the CD20+CD138-IgKappa+IgLambda- phenotype', 'cell type: FACS sorted peripheral blood B cells with the CD20+CD138-IgKappa-IgLambda+ phenotype', nan]}\n"
     ]
    }
   ],
   "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": "b7c4ee79",
   "metadata": {},
   "source": [
    "### Step 2: Dataset Analysis and Clinical Feature Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "4c5a0f28",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:43:54.054953Z",
     "iopub.status.busy": "2025-03-25T04:43:54.054849Z",
     "iopub.status.idle": "2025-03-25T04:43:54.059455Z",
     "shell.execute_reply": "2025-03-25T04:43:54.059182Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 1. Gene Expression Data Availability\n",
    "# Based on the series title and summary, this dataset appears to contain gene expression data for\n",
    "# B cell receptor light chain V genes, which makes it suitable for our analysis\n",
    "is_gene_available = True\n",
    "\n",
    "# 2. Variable Availability and Data Type Conversion\n",
    "\n",
    "# 2.1 Data Availability\n",
    "# For trait (Vitamin D Levels), there is no explicit measurement in the data\n",
    "# The dataset focuses on B cell receptor light chain in healthy individuals and SLE patients\n",
    "# It does not contain data on Vitamin D levels\n",
    "trait_row = None\n",
    "\n",
    "# For age, there is no information available in the sample characteristics\n",
    "age_row = None\n",
    "\n",
    "# For gender, there is no information available in the sample characteristics\n",
    "gender_row = None\n",
    "\n",
    "# 2.2 Data Type Conversion\n",
    "# Since the trait is not available, we'll define a placeholder conversion function\n",
    "def convert_trait(val):\n",
    "    # Not used because trait data is not available, but defined for completeness\n",
    "    return None\n",
    "\n",
    "def convert_age(val):\n",
    "    # Not used because age data is not available, but defined for completeness\n",
    "    return None\n",
    "\n",
    "def convert_gender(val):\n",
    "    # Not used because gender data is not available, but defined for completeness\n",
    "    return None\n",
    "\n",
    "# 3. Save Metadata\n",
    "# Conduct initial filtering on the usability of the dataset\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",
    "# We skip this step since trait_row is None, indicating that clinical data relevant to our trait is not available\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e6fa0e8b",
   "metadata": {},
   "source": [
    "### Step 3: Gene Data Extraction"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "eefda092",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:43:54.060437Z",
     "iopub.status.busy": "2025-03-25T04:43:54.060336Z",
     "iopub.status.idle": "2025-03-25T04:43:54.075041Z",
     "shell.execute_reply": "2025-03-25T04:43:54.074716Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "First 20 gene/probe identifiers:\n",
      "Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',\n",
      "       '14', '15', '16', '17', '18', '19', '20'],\n",
      "      dtype='object', name='ID')\n",
      "\n",
      "Gene expression data shape: (702, 90)\n"
     ]
    }
   ],
   "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": "fd0ea077",
   "metadata": {},
   "source": [
    "### Step 4: Gene Identifier Review"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "4f510ebb",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:43:54.076089Z",
     "iopub.status.busy": "2025-03-25T04:43:54.075973Z",
     "iopub.status.idle": "2025-03-25T04:43:54.077741Z",
     "shell.execute_reply": "2025-03-25T04:43:54.077442Z"
    }
   },
   "outputs": [],
   "source": [
    "# The identifiers in this dataset appear to be simple numeric values (1, 2, 3, etc.)\n",
    "# rather than standard human gene symbols or common probe identifiers.\n",
    "# These are likely to be row indices or some proprietary/custom identifiers\n",
    "# that would need to be mapped to standard gene symbols.\n",
    "\n",
    "requires_gene_mapping = True\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "67cda6e5",
   "metadata": {},
   "source": [
    "### Step 5: Gene Annotation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f291f512",
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-03-25T04:43:54.078738Z",
     "iopub.status.busy": "2025-03-25T04:43:54.078632Z",
     "iopub.status.idle": "2025-03-25T04:43:54.178761Z",
     "shell.execute_reply": "2025-03-25T04:43:54.178445Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sample of gene expression data (first 5 rows, first 5 columns):\n",
      "    GSM829558  GSM829559  GSM829560  GSM829561  GSM829562\n",
      "ID                                                       \n",
      "1      8.6110     7.5734     7.8586     7.0651     7.0482\n",
      "2      8.8956     7.9014     7.7024     7.6270     7.2680\n",
      "3      8.1202     8.5356     8.1926     7.6255     6.6475\n",
      "4      7.7357     9.0515     6.9298     7.7770     6.8019\n",
      "5      8.0023     9.1398     6.9036     7.9086     7.1469\n",
      "\n",
      "Platform information:\n",
      "!Series_title = Human B cell receptor light chain repertoire analysis in healthy individuals and SLE patients\n",
      "!Platform_title = University of Chicago Weigert Light Chain\n",
      "\n",
      "Gene annotation columns:\n",
      "['ID', 'ORF', 'Light Chain', 'SPOT_ID', 'SEQUENCE']\n",
      "\n",
      "Gene annotation preview:\n",
      "{'ID': ['1', '2', '3', '4', '5'], 'ORF': ['A1', 'A1', 'A1', 'A1', 'A1'], 'Light Chain': [\"'A1'\", \"'A1'\", \"'A1'\", \"'A1'\", \"'A1'\"], 'SPOT_ID': [nan, nan, nan, nan, nan], 'SEQUENCE': ['AGGCCAATCTCCAAGGCGCCTAATTTATAAGGTTTCTAACTGGGACTCTGGGGTCCCAGACAGATTCAGC', 'AGGCCAATCTCCAAGGCGCCTAATTTATAAGGTTTCTAACTGGGACTCTGGGGTCCCAGACAGATTCAGC', 'AGGCCAATCTCCAAGGCGCCTAATTTATAAGGTTTCTAACTGGGACTCTGGGGTCCCAGACAGATTCAGC', 'AGGCCAATCTCCAAGGCGCCTAATTTATAAGGTTTCTAACTGGGACTCTGGGGTCCCAGACAGATTCAGC', 'AGGCCAATCTCCAAGGCGCCTAATTTATAAGGTTTCTAACTGGGACTCTGGGGTCCCAGACAGATTCAGC']}\n",
      "\n",
      "Matching rows in annotation for sample IDs: 910\n",
      "\n",
      "Potential gene symbol columns: []\n",
      "\n",
      "Is this dataset likely to contain gene expression data? False\n",
      "\n",
      "NOTE: Based on our analysis, this dataset doesn't appear to contain gene expression data.\n",
      "It appears to be a different type of data (possibly SNP array or other genomic data).\n"
     ]
    }
   ],
   "source": [
    "# 1. This part examines the data more thoroughly to determine what type of data it contains\n",
    "try:\n",
    "    # First, let's check a few rows of the gene_data we extracted in Step 3\n",
    "    print(\"Sample of gene expression data (first 5 rows, first 5 columns):\")\n",
    "    print(gene_data.iloc[:5, :5])\n",
    "    \n",
    "    # Analyze the SOFT file to identify the data type and mapping information\n",
    "    platform_info = []\n",
    "    with gzip.open(soft_file_path, 'rt', encoding='latin-1') as f:\n",
    "        for line in f:\n",
    "            if line.startswith(\"!Platform_title\") or line.startswith(\"!Series_title\") or \"description\" in line.lower():\n",
    "                platform_info.append(line.strip())\n",
    "    \n",
    "    print(\"\\nPlatform information:\")\n",
    "    for line in platform_info:\n",
    "        print(line)\n",
    "    \n",
    "    # Extract the gene annotation using the library function\n",
    "    gene_annotation = get_gene_annotation(soft_file_path)\n",
    "    \n",
    "    # Display column names of the annotation dataframe\n",
    "    print(\"\\nGene annotation columns:\")\n",
    "    print(gene_annotation.columns.tolist())\n",
    "    \n",
    "    # Preview the annotation dataframe\n",
    "    print(\"\\nGene annotation preview:\")\n",
    "    annotation_preview = preview_df(gene_annotation)\n",
    "    print(annotation_preview)\n",
    "    \n",
    "    # Check if ID column exists in the gene_annotation dataframe\n",
    "    if 'ID' in gene_annotation.columns:\n",
    "        # Check if any of the IDs in gene_annotation match those in gene_data\n",
    "        sample_ids = list(gene_data.index[:10])\n",
    "        matching_rows = gene_annotation[gene_annotation['ID'].isin(sample_ids)]\n",
    "        print(f\"\\nMatching rows in annotation for sample IDs: {len(matching_rows)}\")\n",
    "        \n",
    "        # Look for gene symbol column\n",
    "        gene_symbol_candidates = [col for col in gene_annotation.columns if 'gene' in col.lower() or 'symbol' in col.lower() or 'name' in col.lower()]\n",
    "        print(f\"\\nPotential gene symbol columns: {gene_symbol_candidates}\")\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"Error analyzing gene annotation data: {e}\")\n",
    "    gene_annotation = pd.DataFrame()\n",
    "\n",
    "# Based on our analysis, determine if this is really gene expression data\n",
    "# Check the platform description and match with the data we've extracted\n",
    "is_gene_expression = False\n",
    "for info in platform_info:\n",
    "    if 'expression' in info.lower() or 'transcript' in info.lower() or 'mrna' in info.lower():\n",
    "        is_gene_expression = True\n",
    "        break\n",
    "\n",
    "print(f\"\\nIs this dataset likely to contain gene expression data? {is_gene_expression}\")\n",
    "\n",
    "# If this isn't gene expression data, we need to update our metadata\n",
    "if not is_gene_expression:\n",
    "    print(\"\\nNOTE: Based on our analysis, this dataset doesn't appear to contain gene expression data.\")\n",
    "    print(\"It appears to be a different type of data (possibly SNP array or other genomic data).\")\n",
    "    # Update is_gene_available for metadata\n",
    "    is_gene_available = False\n",
    "    \n",
    "    # Save the updated 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",
    "    )"
   ]
  }
 ],
 "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
}