{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "aa8971ee", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:28.910514Z", "iopub.status.busy": "2025-03-25T07:59:28.910101Z", "iopub.status.idle": "2025-03-25T07:59:29.078713Z", "shell.execute_reply": "2025-03-25T07:59:29.078328Z" } }, "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 = \"Mesothelioma\"\n", "cohort = \"GSE68950\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Mesothelioma\"\n", "in_cohort_dir = \"../../input/GEO/Mesothelioma/GSE68950\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Mesothelioma/GSE68950.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Mesothelioma/gene_data/GSE68950.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Mesothelioma/clinical_data/GSE68950.csv\"\n", "json_path = \"../../output/preprocess/Mesothelioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "d35d0191", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "87fd489a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:29.080251Z", "iopub.status.busy": "2025-03-25T07:59:29.080102Z", "iopub.status.idle": "2025-03-25T07:59:29.477020Z", "shell.execute_reply": "2025-03-25T07:59:29.476657Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE68950_family.soft.gz', 'GSE68950_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Mesothelioma/GSE68950/GSE68950_family.soft.gz\n", "Matrix file: ../../input/GEO/Mesothelioma/GSE68950/GSE68950_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"caArray_golub-00327: Sanger cell line Affymetrix gene expression project\"\n", "!Series_summary\t\"The microarray gene expression pattern was studied using 798 different cancer cell lines. The cancer cell lines are obtained from different centers. Annotation information were provided in the supplementary file.\"\n", "!Series_overall_design\t\"golub-00327\"\n", "!Series_overall_design\t\"Assay Type: Gene Expression\"\n", "!Series_overall_design\t\"Provider: Affymetrix\"\n", "!Series_overall_design\t\"Array Designs: HT_HG-U133A\"\n", "!Series_overall_design\t\"Organism: Homo sapiens (ncbitax)\"\n", "!Series_overall_design\t\"Tissue Sites: leukemia, Urinary tract, Lung, BiliaryTract, Autonomic Ganglion, Thyroid gland, Stomach, Breast, Pancreas, Head and Neck, Lymphoma, Colorectal, Placenta, Liver, Brain, Bone, pleura, Skin, endometrium, Ovary, cervix, Oesophagus, Connective and Soft Tissue, Muscle, Kidney, Prostate, Adrenal Gland, Eye, Testis, Smooth Muscle Tissue, Vulva, Unknow\"\n", "!Series_overall_design\t\"Material Types: cell, synthetic_RNA, whole_organism, total_RNA, BVG\"\n", "!Series_overall_design\t\"Disease States: M3 acute myeloid leukemia, hairy cell leukemia, transitional cell carcinoma, Adenocarcinoma, B cell lymphoma unspecified, Acute Lymphoblastic Leukemia, blast phase chronic myeloid leukemia, Carcinoma, M6 acute myeloid leukemia, Neuroblastoma, follicular carcinoma, ductal carcinoma, Burkitt Lymphoma, Squamous Cell Carcinoma, M5 acute myeloid leukemia, Mycosis Fungoides and Sezary Syndrome, Acute T-Cell Lymphoblastic Leukemia, Adult T-Cell Leukemia/Lymphoma, M2 Therapy-Related Myeloid Neoplasm, Choriocarcinoma, Plasma Cell Myeloma, Hepatocellular Carcinoma, anaplastic large cell lymphoma, primitive neuroectodermal tumor-medulloblastoma, M4 acute myeloid leukemia, B Acute Lymphoblastic Leukemia, Acute Leukemia of Ambiguous Lineage, Osteosarcoma, Hodgkin Lymphoma, Mesothelioma, chondrosarcoma, Glioblastoma Multiforme, Malignant Melanoma, carcinosarcoma-malignant mesodermal mixed tumor, bronchioloalveolar adenocarcinoma, chronic lymphocytic leukemia-small lymphocytic lymphoma, micropapillary carcinoma, diffuse large B cell lymphoma, myelodysplastic syndrome, giant cell carcinoma, teratoma, multipotential sarcoma, Small Cell Carcinoma, ASTROCYTOMA, Fibrosarcoma, mucoepidermoid carcinoma, Rhabdomyosarcoma, L1 Acute T-Cell Lymphoblastic Leukemia, Glioma, Anaplastic Astrocytoma, Non-small cell carcinoma, Large Cell Carcinoma, mucinous carcinoma, Acute Myeloid Leukemia, malignant fibrous histiocytoma-pleomorphic sarcoma, clear cell carcinoma, B cell lymphoma unspecified, Anaplastic Carcinoma, Ewings sarcoma-peripheral primitive neuroectodermal tumor, undifferentiated carcinoma, Sarcoma, Embryonal Rhabdomyosarcoma, epithelioid sarcoma, renal cell carcinoma, carcinoid-endocrine tumor, Synovial Sarcoma, lymphoid neoplasm, rhabdoid tumor, Refractory Anemia with Excess Blasts, Liposarcoma, biphasic mesothelioma, adrenal cortical carcinoma, adenosquamous carcinoma, L2 Acute T-Cell Lymphoblastic Leukemia, chronic myeloid leukemia, Micropapillary Serous Carcinoma, desmoplastic, acute leukemia, Retinoblastoma, teratocarcinoma, clear cell renal cell carcinoma, Follicular Lymphoma, Wilms Tumor, M7 acute myeloid leukemia, gliosarcoma, embryonal carcinoma, Leiomyosarcoma, medullary carcinoma, granulosa cell tumor, papillary carcinoma, NS Acute Lymphoblastic Leukemia, papillary transitional cell carcinoma, small cell adenocarcinoma, epithelial dysplasia, hyperplasia, tubular adenocarcinoma, metaplasia, papillary ductal carcinoma, chronic eosinophilic leukemia-hypereosinophilic syndrome, #N/A, malignant trichilemmal cyst, Medullary Breast Carcinoma, L2 Acute Lymphoblastic Leukemia, Osteoblastic Osteosarcoma\"\n", "Sample Characteristics Dictionary:\n", "{0: ['cosmic id: 924101', 'cosmic id: 906800', 'cosmic id: 687452', 'cosmic id: 924100', 'cosmic id: 910924', 'cosmic id: 906798', 'cosmic id: 906797', 'cosmic id: 910922', 'cosmic id: 905947', 'cosmic id: 924102', 'cosmic id: 687562', 'cosmic id: 910921', 'cosmic id: 687563', 'cosmic id: 910784', 'cosmic id: 906792', 'cosmic id: 906794', 'cosmic id: 906804', 'cosmic id: 906793', 'cosmic id: 910935', 'cosmic id: 910851', 'cosmic id: 910925', 'cosmic id: 905948', 'cosmic id: 910934', 'cosmic id: 905949', 'cosmic id: 684052', 'cosmic id: 910920', 'cosmic id: 906791', 'cosmic id: 905950', 'cosmic id: 906803', 'cosmic id: 906790'], 1: ['disease state: L2 Acute Lymphoblastic Leukemia', 'disease state: NS Acute Lymphoblastic Leukemia', 'disease state: carcinoma', 'disease state: adenocarcinoma', 'disease state: transitional cell carcinoma', 'disease state: clear cell renal cell carcinoma', 'disease state: anaplastic carcinoma', 'disease state: glioblastoma multiforme', 'disease state: malignant melanoma', 'disease state: rhabdomyosarcoma', 'disease state: mucoepidermoid carcinoma', 'disease state: squamous cell carcinoma', 'disease state: renal cell carcinoma', 'disease state: neuroblastoma', 'disease state: Acute Lymphoblastic Leukemia', 'disease state: M5 acute myeloid leukemia', 'disease state: plasma cell myeloma', 'disease state: L1 Acute T-Cell Lymphoblastic Leukemia', 'disease state: astrocytoma', 'disease state: B Acute Lymphoblastic Leukemia', 'disease state: B cell lymphoma unspecified', 'disease state: papillary carcinoma', 'disease state: papillary transitional cell carcinoma', 'disease state: Burkitt lymphoma', 'disease state: hairy cell leukemia', 'disease state: hyperplasia', 'disease state: papillary ductal carcinoma', 'disease state: blast phase chronic myeloid leukemia', 'disease state: hepatocellular carcinoma', 'disease state: Adult T-Cell Leukemia/Lymphoma'], 2: ['disease location: Hematopoietic and Lymphoid Tissue', 'disease location: bladder', 'disease location: prostate', 'disease location: stomach', 'disease location: ureter', 'disease location: kidney', 'disease location: thyroid', 'disease location: frontal lobe', 'disease location: skin', 'disease location: brain', 'disease location: striated muscle', 'disease location: submaxillary', 'disease location: ovary', 'disease location: lung', 'disease location: autonomic ganglia', 'disease location: endometrium', 'disease location: pancreas', 'disease location: head neck', 'disease location: cervix', 'disease location: breast', 'disease location: colon', 'disease location: liver', 'disease location: gingiva', 'disease location: tongue', 'disease location: vulva', 'disease location: bone', 'disease location: rectum', 'disease location: esophagus', 'disease location: central nervous system', 'disease location: posterior fossa'], 3: ['organism part: Leukemia', 'organism part: Urinary tract', 'organism part: Prostate', 'organism part: Stomach', 'organism part: Kidney', 'organism part: Thyroid Gland', 'organism part: Brain', 'organism part: Skin', 'organism part: Muscle', 'organism part: Head and Neck', 'organism part: Ovary', 'organism part: Lung', 'organism part: Autonomic Ganglion', 'organism part: Endometrium', 'organism part: Pancreas', 'organism part: Cervix', 'organism part: Breast', 'organism part: Colorectal', 'organism part: Liver', 'organism part: Vulva', 'organism part: Bone', 'organism part: Oesophagus', 'organism part: BiliaryTract', 'organism part: Connective and Soft Tissue', 'organism part: Lymphoma', 'organism part: Pleura', 'organism part: Testis', 'organism part: Placenta', 'organism part: Adrenal Gland', 'organism part: Unknow'], 4: ['sample: 736', 'sample: 494', 'sample: 7', 'sample: 746', 'sample: 439', 'sample: 168', 'sample: 152', 'sample: 37', 'sample: 450', 'sample: 42', 'sample: 526', 'sample: 462', 'sample: 451', 'sample: 486', 'sample: 429', 'sample: 47', 'sample: 755', 'sample: 71', 'sample: 72', 'sample: 474', 'sample: 364', 'sample: 537', 'sample: 110', 'sample: 316', 'sample: 33', 'sample: 408', 'sample: 201', 'sample: 38', 'sample: 9', 'sample: 190'], 5: ['cell line code: 749', 'cell line code: 493', 'cell line code: 505', 'cell line code: 760', 'cell line code: 437', 'cell line code: 151', 'cell line code: 134', 'cell line code: 449', 'cell line code: 85', 'cell line code: 529', 'cell line code: 461', 'cell line code: 450', 'cell line code: 485', 'cell line code: 426', 'cell line code: 59', 'cell line code: 769', 'cell line code: 48', 'cell line code: 38', 'cell line code: 473', 'cell line code: 353', 'cell line code: 541', 'cell line code: 54', 'cell line code: 302', 'cell line code: 25', 'cell line code: 402', 'cell line code: 184', 'cell line code: 63', 'cell line code: 29', 'cell line code: 173', 'cell line code: 553'], 6: ['supplier: DSMZ', 'supplier: ATCC', 'supplier: Unspecified', 'supplier: DTP', 'supplier: HSRRB', 'supplier: ICLC', 'supplier: RIKEN', 'supplier: ECCC', 'supplier: JCRB'], 7: ['affy_batch: 1', 'affy_batch: 2'], 8: ['crna plate: 8', 'crna plate: 6', 'crna plate: 11', 'crna plate: 5', 'crna plate: 2', 'crna plate: 12', 'crna plate: 4', 'crna plate: 3', 'crna plate: 7']}\n" ] } ], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "646ec30e", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "b41be572", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:29.478399Z", "iopub.status.busy": "2025-03-25T07:59:29.478277Z", "iopub.status.idle": "2025-03-25T07:59:29.524064Z", "shell.execute_reply": "2025-03-25T07:59:29.523726Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data preview: {'GSM1687570': [0.0], 'GSM1687571': [0.0], 'GSM1687572': [0.0], 'GSM1687573': [0.0], 'GSM1687574': [0.0], 'GSM1687575': [0.0], 'GSM1687576': [0.0], 'GSM1687577': [0.0], 'GSM1687578': [0.0], 'GSM1687579': [0.0], 'GSM1687580': [0.0], 'GSM1687581': [0.0], 'GSM1687582': [0.0], 'GSM1687583': [0.0], 'GSM1687584': [0.0], 'GSM1687585': [0.0], 'GSM1687586': [0.0], 'GSM1687587': [0.0], 'GSM1687588': [0.0], 'GSM1687589': [0.0], 'GSM1687590': [0.0], 'GSM1687591': [0.0], 'GSM1687592': [0.0], 'GSM1687593': [0.0], 'GSM1687594': [0.0], 'GSM1687595': [0.0], 'GSM1687596': [0.0], 'GSM1687597': [0.0], 'GSM1687598': [0.0], 'GSM1687599': [0.0], 'GSM1687600': [0.0], 'GSM1687601': [0.0], 'GSM1687602': [0.0], 'GSM1687603': [0.0], 'GSM1687604': [0.0], 'GSM1687605': [0.0], 'GSM1687606': [0.0], 'GSM1687607': [0.0], 'GSM1687608': [0.0], 'GSM1687609': [0.0], 'GSM1687610': [0.0], 'GSM1687611': [0.0], 'GSM1687612': [0.0], 'GSM1687613': [0.0], 'GSM1687614': [0.0], 'GSM1687615': [0.0], 'GSM1687616': [0.0], 'GSM1687617': [0.0], 'GSM1687618': [0.0], 'GSM1687619': [0.0], 'GSM1687620': [0.0], 'GSM1687621': [0.0], 'GSM1687622': [0.0], 'GSM1687623': [0.0], 'GSM1687624': [0.0], 'GSM1687625': [0.0], 'GSM1687626': [0.0], 'GSM1687627': [0.0], 'GSM1687628': [0.0], 'GSM1687629': [0.0], 'GSM1687630': [0.0], 'GSM1687631': [0.0], 'GSM1687632': [0.0], 'GSM1687633': [0.0], 'GSM1687634': [0.0], 'GSM1687635': [0.0], 'GSM1687636': [0.0], 'GSM1687637': [0.0], 'GSM1687638': [0.0], 'GSM1687639': [0.0], 'GSM1687640': [0.0], 'GSM1687641': [0.0], 'GSM1687642': [0.0], 'GSM1687643': [0.0], 'GSM1687644': [0.0], 'GSM1687645': [0.0], 'GSM1687646': [0.0], 'GSM1687647': [0.0], 'GSM1687648': [0.0], 'GSM1687649': [0.0], 'GSM1687650': [0.0], 'GSM1687651': [0.0], 'GSM1687652': [0.0], 'GSM1687653': [0.0], 'GSM1687654': [0.0], 'GSM1687655': [0.0], 'GSM1687656': [0.0], 'GSM1687657': [0.0], 'GSM1687658': [0.0], 'GSM1687659': [0.0], 'GSM1687660': [0.0], 'GSM1687661': [0.0], 'GSM1687662': [0.0], 'GSM1687663': [0.0], 'GSM1687664': [0.0], 'GSM1687665': [0.0], 'GSM1687666': [0.0], 'GSM1687667': [0.0], 'GSM1687668': [0.0], 'GSM1687669': [0.0], 'GSM1687670': [0.0], 'GSM1687671': [0.0], 'GSM1687672': [0.0], 'GSM1687673': [0.0], 'GSM1687674': [0.0], 'GSM1687675': [0.0], 'GSM1687676': [0.0], 'GSM1687677': [0.0], 'GSM1687678': [0.0], 'GSM1687679': [0.0], 'GSM1687680': [0.0], 'GSM1687681': [0.0], 'GSM1687682': [0.0], 'GSM1687683': [0.0], 'GSM1687684': [0.0], 'GSM1687685': [0.0], 'GSM1687686': [0.0], 'GSM1687687': [0.0], 'GSM1687688': [0.0], 'GSM1687689': [0.0], 'GSM1687690': [0.0], 'GSM1687691': [0.0], 'GSM1687692': [0.0], 'GSM1687693': [0.0], 'GSM1687694': [0.0], 'GSM1687695': [0.0], 'GSM1687696': [0.0], 'GSM1687697': [0.0], 'GSM1687698': [0.0], 'GSM1687699': [0.0], 'GSM1687700': [0.0], 'GSM1687701': [0.0], 'GSM1687702': [0.0], 'GSM1687703': [0.0], 'GSM1687704': [0.0], 'GSM1687705': [0.0], 'GSM1687706': [0.0], 'GSM1687707': [0.0], 'GSM1687708': [0.0], 'GSM1687709': [0.0], 'GSM1687710': [0.0], 'GSM1687711': [0.0], 'GSM1687712': [0.0], 'GSM1687713': [0.0], 'GSM1687714': [0.0], 'GSM1687715': [0.0], 'GSM1687716': [0.0], 'GSM1687717': [0.0], 'GSM1687718': [0.0], 'GSM1687719': [0.0], 'GSM1687720': [0.0], 'GSM1687721': [0.0], 'GSM1687722': [0.0], 'GSM1687723': [0.0], 'GSM1687724': [0.0], 'GSM1687725': [0.0], 'GSM1687726': [0.0], 'GSM1687727': [0.0], 'GSM1687728': [0.0], 'GSM1687729': [0.0], 'GSM1687730': [0.0], 'GSM1687731': [0.0], 'GSM1687732': [0.0], 'GSM1687733': [0.0], 'GSM1687734': [0.0], 'GSM1687735': [0.0], 'GSM1687736': [0.0], 'GSM1687737': [0.0], 'GSM1687738': [0.0], 'GSM1687739': [0.0], 'GSM1687740': [0.0], 'GSM1687741': [0.0], 'GSM1687742': [0.0], 'GSM1687743': [0.0], 'GSM1687744': [0.0], 'GSM1687745': [0.0], 'GSM1687746': [0.0], 'GSM1687747': [0.0], 'GSM1687748': [0.0], 'GSM1687749': [0.0], 'GSM1687750': [0.0], 'GSM1687751': [0.0], 'GSM1687752': [0.0], 'GSM1687753': [0.0], 'GSM1687754': [0.0], 'GSM1687755': [0.0], 'GSM1687756': [0.0], 'GSM1687757': [0.0], 'GSM1687758': [0.0], 'GSM1687759': [0.0], 'GSM1687760': [0.0], 'GSM1687761': [0.0], 'GSM1687762': [0.0], 'GSM1687763': [0.0], 'GSM1687764': [0.0], 'GSM1687765': [0.0], 'GSM1687766': [0.0], 'GSM1687767': [0.0], 'GSM1687768': [0.0], 'GSM1687769': [0.0]}\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Callable, Dict, Any, Optional, List\n", "\n", "# 1. Gene Expression Data Availability\n", "# From the background information, this is an Affymetrix gene expression project using HT_HG-U133A arrays\n", "# This indicates that gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# Let's check for trait (Mesothelioma) availability\n", "# From the background information, Mesothelioma is explicitly listed as one of the disease states\n", "# Looking at disease state in row 1 of the sample characteristics\n", "trait_row = 1 # 'disease state' is in row 1\n", "\n", "# Define conversion function for trait\n", "def convert_trait(val):\n", " if val is None:\n", " return None\n", " \n", " if \":\" in val:\n", " val = val.split(\":\", 1)[1].strip().lower()\n", " else:\n", " val = val.lower()\n", " \n", " # Binary classification: 1 for Mesothelioma, 0 for other diseases\n", " if \"mesothelioma\" in val:\n", " return 1\n", " else:\n", " return 0\n", "\n", "# No age information is available in the sample characteristics\n", "age_row = None\n", "\n", "# No gender information is available in the sample characteristics\n", "gender_row = None\n", "\n", "# These functions won't be used since the data is not available, but defining them for completeness\n", "def convert_age(val):\n", " if val is None:\n", " return None\n", " \n", " if \":\" in val:\n", " val = val.split(\":\", 1)[1].strip()\n", " \n", " try:\n", " return float(val)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(val):\n", " if val is None:\n", " return None\n", " \n", " if \":\" in val:\n", " val = val.split(\":\", 1)[1].strip().lower()\n", " else:\n", " val = val.lower()\n", " \n", " if \"female\" in val or \"f\" == val:\n", " return 0\n", " elif \"male\" in val or \"m\" == val:\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\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, \n", " is_trait_available=is_trait_available)\n", "\n", "# 4. Clinical Feature Extraction\n", "if trait_row is not None:\n", " # Extract clinical features using sample characteristics data from previous step\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data, # Using clinical_data from previous step\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age if age_row is not None else None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender if gender_row is not None else None\n", " )\n", " \n", " # Preview the extracted clinical data\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical data preview:\", preview)\n", " \n", " # Save the clinical data to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n" ] }, { "cell_type": "markdown", "id": "1afea218", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "23308be8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:29.525274Z", "iopub.status.busy": "2025-03-25T07:59:29.525158Z", "iopub.status.idle": "2025-03-25T07:59:30.711528Z", "shell.execute_reply": "2025-03-25T07:59:30.711158Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "No subseries references found in the first 1000 lines of the SOFT file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 22277\n", "First 20 gene/probe identifiers:\n", "Index(['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at', '1294_at',\n", " '1316_at', '1320_at', '1405_i_at', '1431_at', '1438_at', '1487_at',\n", " '1494_f_at', '1598_g_at', '160020_at', '1729_at', '1773_at', '177_at',\n", " '179_at', '1861_at'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "89c72022", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "d0525cd1", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:30.712915Z", "iopub.status.busy": "2025-03-25T07:59:30.712793Z", "iopub.status.idle": "2025-03-25T07:59:30.714764Z", "shell.execute_reply": "2025-03-25T07:59:30.714440Z" } }, "outputs": [], "source": [ "# Examine the gene identifiers in the gene expression data\n", "# These appear to be probe IDs from an Affymetrix microarray (e.g., '1007_s_at', '1053_at')\n", "# They are not standard human gene symbols and will need to be mapped to gene symbols\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "d21a9070", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "d833af8a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:30.715979Z", "iopub.status.busy": "2025-03-25T07:59:30.715865Z", "iopub.status.idle": "2025-03-25T07:59:54.222081Z", "shell.execute_reply": "2025-03-25T07:59:54.221696Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1007_s_at', '1053_at', '117_at', '121_at', '1255_g_at'], 'GB_ACC': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'SPOT_ID': [nan, nan, nan, nan, nan], 'Species Scientific Name': ['Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens', 'Homo sapiens'], 'Annotation Date': ['Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007', 'Mar 8, 2007'], 'Sequence Type': ['Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence', 'Exemplar sequence'], 'Sequence Source': [nan, nan, nan, nan, nan], 'Target Description': ['U48705 /FEATURE=mRNA /DEFINITION=HSU48705 Human receptor tyrosine kinase DDR gene, complete cds', 'M87338 /FEATURE= /DEFINITION=HUMA1SBU Human replication factor C, 40-kDa subunit (A1) mRNA, complete cds', \"X51757 /FEATURE=cds /DEFINITION=HSP70B Human heat-shock protein HSP70B' gene\", 'X69699 /FEATURE= /DEFINITION=HSPAX8A H.sapiens Pax8 mRNA', 'L36861 /FEATURE=expanded_cds /DEFINITION=HUMGCAPB Homo sapiens guanylate cyclase activating protein (GCAP) gene exons 1-4, complete cds'], 'Representative Public ID': ['U48705', 'M87338', 'X51757', 'X69699', 'L36861'], 'Gene Title': ['discoidin domain receptor family, member 1', 'replication factor C (activator 1) 2, 40kDa', \"heat shock 70kDa protein 6 (HSP70B')\", 'paired box gene 8', 'guanylate cyclase activator 1A (retina)'], 'Gene Symbol': ['DDR1', 'RFC2', 'HSPA6', 'PAX8', 'GUCA1A'], 'ENTREZ_GENE_ID': ['780', '5982', '3310', '7849', '2978'], 'RefSeq Transcript ID': ['NM_001954 /// NM_013993 /// NM_013994', 'NM_002914 /// NM_181471', 'NM_002155 /// XM_001134322', 'NM_003466 /// NM_013951 /// NM_013952 /// NM_013953 /// NM_013992', 'NM_000409'], 'Gene Ontology Biological Process': ['0006468 // protein amino acid phosphorylation // inferred from electronic annotation /// 0007155 // cell adhesion // inferred from electronic annotation /// 0007155 // cell adhesion // traceable author statement /// 0007169 // transmembrane receptor protein tyrosine kinase signaling pathway // inferred from electronic annotation', '0006260 // DNA replication // inferred from electronic annotation', '0006457 // protein folding // inferred from electronic annotation /// 0006986 // response to unfolded protein // traceable author statement /// 0006986 // response to unfolded protein // inferred from electronic annotation', '0001656 // metanephros development // inferred from electronic annotation /// 0006183 // GTP biosynthesis // inferred from electronic annotation /// 0006228 // UTP biosynthesis // inferred from electronic annotation /// 0006241 // CTP biosynthesis // inferred from electronic annotation /// 0006350 // transcription // inferred from electronic annotation /// 0009887 // organ morphogenesis // inferred from electronic annotation /// 0030154 // cell differentiation // inferred from electronic annotation /// 0045893 // positive regulation of transcription, DNA-dependent // inferred from sequence or structural similarity /// 0006355 // regulation of transcription, DNA-dependent // inferred from electronic annotation /// 0007275 // development // inferred from electronic annotation /// 0009653 // morphogenesis // traceable author statement', '0007165 // signal transduction // non-traceable author statement /// 0007601 // visual perception // traceable author statement /// 0050896 // response to stimulus // inferred from electronic annotation /// 0007601 // visual perception // inferred from electronic annotation'], 'Gene Ontology Cellular Component': ['0005615 // extracellular space // inferred from electronic annotation /// 0005887 // integral to plasma membrane // traceable author statement /// 0016020 // membrane // inferred from electronic annotation /// 0016021 // integral to membrane // inferred from electronic annotation', '0005634 // nucleus // inferred from electronic annotation /// 0005663 // DNA replication factor C complex // traceable author statement /// 0005663 // DNA replication factor C complex // inferred from electronic annotation', nan, '0005634 // nucleus // inferred from electronic annotation /// 0005654 // nucleoplasm // inferred from sequence or structural similarity /// 0005667 // transcription factor complex // inferred from electronic annotation', nan], 'Gene Ontology Molecular Function': ['0000166 // nucleotide binding // inferred from electronic annotation /// 0004674 // protein serine/threonine kinase activity // inferred from electronic annotation /// 0004713 // protein-tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // inferred from electronic annotation /// 0004714 // transmembrane receptor protein tyrosine kinase activity // traceable author statement /// 0004872 // receptor activity // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation /// 0016740 // transferase activity // inferred from electronic annotation /// 0004672 // protein kinase activity // inferred from electronic annotation /// 0016301 // kinase activity // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0003677 // DNA binding // inferred from electronic annotation /// 0005515 // protein binding // inferred from physical interaction /// 0005524 // ATP binding // traceable author statement /// 0017111 // nucleoside-triphosphatase activity // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0000166 // nucleotide binding // inferred from electronic annotation /// 0005524 // ATP binding // inferred from electronic annotation', '0003700 // transcription factor activity // traceable author statement /// 0004550 // nucleoside diphosphate kinase activity // inferred from electronic annotation /// 0004996 // thyroid-stimulating hormone receptor activity // traceable author statement /// 0005515 // protein binding // inferred from sequence or structural similarity /// 0005524 // ATP binding // inferred from electronic annotation /// 0016563 // transcriptional activator activity // inferred from sequence or structural similarity /// 0003677 // DNA binding // inferred from electronic annotation', '0005509 // calcium ion binding // inferred from electronic annotation /// 0008048 // calcium sensitive guanylate cyclase activator activity // traceable author statement']}\n" ] } ], "source": [ "# 1. 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", "# 2. 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": "251cd5f5", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "5beca18b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:54.223534Z", "iopub.status.busy": "2025-03-25T07:59:54.223401Z", "iopub.status.idle": "2025-03-25T07:59:56.661923Z", "shell.execute_reply": "2025-03-25T07:59:56.661548Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 10 genes after mapping:\n", "Index(['A2BP1', 'A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAK1',\n", " 'AAMP', 'AANAT'],\n", " dtype='object', name='Gene')\n", "Number of genes after mapping: 13046\n" ] } ], "source": [ "# 1. Analyze gene identifiers and data structure\n", "# From looking at the data, these are the mappings:\n", "# - Gene identifiers in the gene expression data are stored under 'ID' in the gene annotation dataframe\n", "# - Gene symbols are stored under 'Gene Symbol' in the gene annotation dataframe\n", "\n", "# 2. Get gene mapping dataframe\n", "prob_col = 'ID'\n", "gene_col = 'Gene Symbol'\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col, gene_col)\n", "\n", "# Extract the gene expression data first\n", "expression_df = get_genetic_data(matrix_file)\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(expression_df, mapping_df)\n", "\n", "# Print the first few rows of the mapped gene data\n", "print(\"First 10 genes after mapping:\")\n", "print(gene_data.index[:10])\n", "print(\"Number of genes after mapping:\", len(gene_data))\n" ] }, { "cell_type": "markdown", "id": "7a7a99c9", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "16915bba", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:59:56.663348Z", "iopub.status.busy": "2025-03-25T07:59:56.663226Z", "iopub.status.idle": "2025-03-25T08:00:28.294912Z", "shell.execute_reply": "2025-03-25T08:00:28.294516Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Top 10 gene indices before normalization: ['A2BP1', 'A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAK1', 'AAMP', 'AANAT']\n", "Top 10 gene indices after normalization: ['A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADAC', 'AAK1', 'AAMDC', 'AAMP', 'AANAT']\n", "Shape of normalized gene data: (12700, 798)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene data to ../../output/preprocess/Mesothelioma/gene_data/GSE68950.csv\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved clinical data to ../../output/preprocess/Mesothelioma/clinical_data/GSE68950.csv\n", "Shape of linked data: (798, 12701)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (798, 12701)\n", "For the feature 'Mesothelioma', the least common label is '1.0' with 6 occurrences. This represents 0.75% of the dataset.\n", "The distribution of the feature 'Mesothelioma' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved processed linked data to ../../output/preprocess/Mesothelioma/GSE68950.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "print(f\"Top 10 gene indices before normalization: {gene_data.index[:10].tolist()}\")\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Top 10 gene indices after normalization: {normalized_gene_data.index[:10].tolist()}\")\n", "print(f\"Shape of normalized gene data: {normalized_gene_data.shape}\")\n", "\n", "# Create directory for gene data file if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "# Save the normalized gene data\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Extract clinical features using the clinical data from step 1\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", "# Extract clinical features using the convert_trait function from step 2\n", "selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=1, # From step 2\n", " convert_trait=convert_trait,\n", " age_row=None,\n", " convert_age=None,\n", " gender_row=None,\n", " convert_gender=None\n", ")\n", "\n", "# Save clinical 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\"Saved clinical data to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "print(f\"Shape of linked data after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Determine if the trait and demographic features are biased\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 6. Validate the dataset and save cohort 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=True,\n", " is_biased=is_trait_biased,\n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data from juvenile myositis (JM) and childhood-onset lupus (cSLE) skin biopsies.\"\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Saved processed linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset validation failed. Final linked data not saved.\")" ] } ], "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 }