{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "422ea267", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:14.149169Z", "iopub.status.busy": "2025-03-25T05:59:14.148970Z", "iopub.status.idle": "2025-03-25T05:59:14.312820Z", "shell.execute_reply": "2025-03-25T05:59:14.312491Z" } }, "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 = \"Osteoarthritis\"\n", "cohort = \"GSE142049\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Osteoarthritis\"\n", "in_cohort_dir = \"../../input/GEO/Osteoarthritis/GSE142049\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Osteoarthritis/GSE142049.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Osteoarthritis/gene_data/GSE142049.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Osteoarthritis/clinical_data/GSE142049.csv\"\n", "json_path = \"../../output/preprocess/Osteoarthritis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "cac2a3d8", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "e68f7d83", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:14.314220Z", "iopub.status.busy": "2025-03-25T05:59:14.314080Z", "iopub.status.idle": "2025-03-25T05:59:14.405941Z", "shell.execute_reply": "2025-03-25T05:59:14.405645Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptional data of inflamatory arthritis B cells\"\n", "!Series_summary\t\"With a focus on rheumatoid arthritis (RA), we sought new insight into genetic mechanisms of adaptive immune dysregulation to help prioritise molecular pathways for targeting in this and related immune pathologies. Whole genome methylation and transcriptional data from isolated CD4+ T cells and B cells of >100 genotyped and phenotyped inflammatory arthritis patients, all of whom were naïve to immunomodulatory treatments, were obtained. Analysis integrated these comprehensive data with GWAS findings across IMDs and other publically available resources.\"\n", "!Series_overall_design\t\"Suspected inflammatory arthritis patients of Northern European ancestry were recruited prior to treatment with immunomodulatory drugs. RA patients were classified using current, internationally accepted criteria, and matched with disease controls in respect of demographic and clinical characteristics. CD19+ B cells were isolated from fresh peripheral blood using magnetic bead-based positive selection, with isolation of paired, high-integrity RNA and DNA using the AllPrep DNA/RNA Mini Kit (Qiagen, UK). The majority of samples are from GSE100648.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient: 2367', 'patient: 2390', 'patient: 2368', 'patient: 2437', 'patient: 2439', 'patient: 2379', 'patient: 1010', 'patient: 841', 'patient: 926', 'patient: 948', 'patient: 898', 'patient: 980', 'patient: 2145', 'patient: 2036', 'patient: 2040', 'patient: 2029', 'patient: 2044', 'patient: 2030', 'patient: 2045', 'patient: 2231', 'patient: 2257', 'patient: 2233', 'patient: 2261', 'patient: 1070', 'patient: 1054', 'patient: 1072', 'patient: 1076', 'patient: 1080', 'patient: 1083', 'patient: 2047'], 1: ['gender: M', 'gender: F'], 2: ['age: 82', 'age: 29', 'age: 61', 'age: 56', 'age: 55', 'age: 72', 'age: 50', 'age: 22', 'age: 53', 'age: 54', 'age: 20', 'age: 49', 'age: 59', 'age: 57', 'age: 35', 'age: 58', 'age: 69', 'age: 46', 'age: 66', 'age: 52', 'age: 63', 'age: 51', 'age: 60', 'age: 92', 'age: 65', 'age: 73', 'age: 43', 'age: 67', 'age: 27', 'age: 32'], 3: ['tissue: peripheral blood'], 4: ['cell type: CD19+ B cells'], 5: ['first_diagnosis: Undifferentiated Spondylo-Arthropathy', 'first_diagnosis: Other Inflammatory Arthritis', 'first_diagnosis: Undifferentiated Inflammatory Arthritis', 'first_diagnosis: Rheumatoid Arthritis', 'first_diagnosis: Crystal Arthritis', 'first_diagnosis: Enteropathic Arthritis', 'first_diagnosis: Osteoarthritis', 'first_diagnosis: Psoriatic Arthritis', 'first_diagnosis: Reactive Arthritis', 'first_diagnosis: Non-Inflammatory'], 6: ['working_diagnosis: Undifferentiated Spondylo-Arthropathy', 'working_diagnosis: Other Inflammatory Arthritis', 'working_diagnosis: Rheumatoid Arthritis', 'working_diagnosis: Reactive Arthritis', 'working_diagnosis: Enteropathic Arthritis', 'working_diagnosis: Psoriatic Arthritis', 'working_diagnosis: Osteoarthritis', 'working_diagnosis: Crystal Arthritis', 'working_diagnosis: Non-Inflammatory', 'working_diagnosis: Undifferentiated Inflammatory Arthritis', 'working_diagnosis: Lupus/Other CTD-Associated']}\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": "5c637f43", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "896c5908", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:14.407022Z", "iopub.status.busy": "2025-03-25T05:59:14.406908Z", "iopub.status.idle": "2025-03-25T05:59:14.422089Z", "shell.execute_reply": "2025-03-25T05:59:14.421798Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical data:\n", "{'GSM4218229': [0.0, 82.0, 1.0], 'GSM4218230': [0.0, 29.0, 1.0], 'GSM4218231': [0.0, 61.0, 0.0], 'GSM4218232': [0.0, 56.0, 1.0], 'GSM4218233': [0.0, 55.0, 0.0], 'GSM4218234': [0.0, 72.0, 1.0], 'GSM4218235': [0.0, 50.0, 0.0], 'GSM4218236': [0.0, 22.0, 1.0], 'GSM4218237': [0.0, 61.0, 1.0], 'GSM4218238': [0.0, 53.0, 0.0], 'GSM4218239': [0.0, 54.0, 0.0], 'GSM4218240': [0.0, 20.0, 0.0], 'GSM4218241': [0.0, 49.0, 0.0], 'GSM4218242': [0.0, 61.0, 1.0], 'GSM4218243': [1.0, 53.0, 0.0], 'GSM4218244': [0.0, 59.0, 1.0], 'GSM4218245': [0.0, 56.0, 0.0], 'GSM4218246': [0.0, 57.0, 1.0], 'GSM4218247': [0.0, 55.0, 1.0], 'GSM4218248': [0.0, 56.0, 0.0], 'GSM4218249': [0.0, 35.0, 0.0], 'GSM4218250': [0.0, 58.0, 0.0], 'GSM4218251': [0.0, 69.0, 1.0], 'GSM4218252': [0.0, 46.0, 0.0], 'GSM4218253': [1.0, 57.0, 0.0], 'GSM4218254': [0.0, 50.0, 0.0], 'GSM4218255': [0.0, 66.0, 0.0], 'GSM4218256': [0.0, 52.0, 0.0], 'GSM4218257': [0.0, 63.0, 0.0], 'GSM4218258': [0.0, 51.0, 1.0], 'GSM4218259': [0.0, 50.0, 0.0], 'GSM4218260': [0.0, 66.0, 1.0], 'GSM4218261': [0.0, 58.0, 0.0], 'GSM4218262': [0.0, 60.0, 1.0], 'GSM4218263': [0.0, 92.0, 1.0], 'GSM4218264': [0.0, 65.0, 1.0], 'GSM4218265': [0.0, 60.0, 0.0], 'GSM4218266': [1.0, 57.0, 1.0], 'GSM4218267': [0.0, 73.0, 0.0], 'GSM4218268': [0.0, 43.0, 0.0], 'GSM4218269': [0.0, 55.0, 1.0], 'GSM4218270': [0.0, 46.0, 0.0], 'GSM4218271': [0.0, 54.0, 0.0], 'GSM4218272': [0.0, 63.0, 0.0], 'GSM4218273': [0.0, 61.0, 1.0], 'GSM4218274': [0.0, 56.0, 0.0], 'GSM4218275': [0.0, 67.0, 0.0], 'GSM4218276': [0.0, 27.0, 0.0], 'GSM4218277': [0.0, 73.0, 0.0], 'GSM4218278': [0.0, 32.0, 0.0], 'GSM4218279': [0.0, 54.0, 0.0], 'GSM4218280': [0.0, 61.0, 1.0], 'GSM4218281': [0.0, 22.0, 0.0], 'GSM4218282': [0.0, 52.0, 0.0], 'GSM4218283': [0.0, 51.0, 0.0], 'GSM4218284': [0.0, 53.0, 0.0], 'GSM4218285': [0.0, 70.0, 0.0], 'GSM4218286': [0.0, 56.0, 0.0], 'GSM4218287': [0.0, 40.0, 0.0], 'GSM4218288': [0.0, 59.0, 0.0], 'GSM4218289': [0.0, 62.0, 1.0], 'GSM4218290': [0.0, 32.0, 0.0], 'GSM4218291': [0.0, 82.0, 0.0], 'GSM4218292': [0.0, 45.0, 0.0], 'GSM4218293': [0.0, 69.0, 0.0], 'GSM4218294': [0.0, 57.0, 1.0], 'GSM4218295': [0.0, 79.0, 1.0], 'GSM4218296': [0.0, 65.0, 1.0], 'GSM4218297': [0.0, 68.0, 0.0], 'GSM4218298': [0.0, 43.0, 0.0], 'GSM4218299': [0.0, 57.0, 0.0], 'GSM4218300': [0.0, 81.0, 0.0], 'GSM4218301': [0.0, 50.0, 0.0], 'GSM4218302': [0.0, 57.0, 0.0], 'GSM4218303': [0.0, 45.0, 0.0], 'GSM4218304': [0.0, 47.0, 0.0], 'GSM4218305': [0.0, 70.0, 0.0], 'GSM4218306': [0.0, 74.0, 1.0], 'GSM4218307': [0.0, 26.0, 0.0], 'GSM4218308': [0.0, 38.0, 0.0], 'GSM4218309': [0.0, 74.0, 0.0], 'GSM4218310': [0.0, 45.0, 1.0], 'GSM4218311': [0.0, 50.0, 0.0], 'GSM4218312': [0.0, 51.0, 1.0], 'GSM4218313': [0.0, 53.0, 0.0], 'GSM4218314': [0.0, 69.0, 0.0], 'GSM4218315': [0.0, 71.0, 1.0], 'GSM4218316': [0.0, 82.0, 1.0], 'GSM4218317': [0.0, 39.0, 0.0], 'GSM4218318': [0.0, 51.0, 0.0], 'GSM4218319': [0.0, 43.0, 0.0], 'GSM4218320': [0.0, 69.0, 0.0], 'GSM4218321': [0.0, 79.0, 0.0], 'GSM4218322': [1.0, 52.0, 0.0], 'GSM4218323': [0.0, 53.0, 0.0], 'GSM4218324': [1.0, 38.0, 0.0], 'GSM4218325': [0.0, 41.0, 0.0], 'GSM4218326': [0.0, 50.0, 0.0], 'GSM4218327': [0.0, 77.0, 0.0], 'GSM4218328': [0.0, 62.0, 0.0], 'GSM4218329': [0.0, 50.0, 0.0], 'GSM4218330': [0.0, 54.0, 0.0], 'GSM4218331': [0.0, 43.0, 1.0], 'GSM4218332': [0.0, 62.0, 0.0], 'GSM4218333': [0.0, 70.0, 1.0], 'GSM4218334': [0.0, 68.0, 0.0], 'GSM4218335': [0.0, 63.0, 0.0], 'GSM4218336': [1.0, 56.0, 1.0], 'GSM4218337': [0.0, 74.0, 0.0], 'GSM4218338': [0.0, 46.0, 0.0], 'GSM4218339': [0.0, 44.0, 0.0], 'GSM4218340': [0.0, 56.0, 0.0], 'GSM4218341': [0.0, 68.0, 0.0], 'GSM4218342': [0.0, 57.0, 0.0]}\n", "Clinical data saved to ../../output/preprocess/Osteoarthritis/clinical_data/GSE142049.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains transcriptional data\n", "# from CD19+ B cells, which suggests gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# Trait data: Look for Osteoarthritis in the sample characteristics\n", "# Keys 5 and 6 contain diagnosis information, with key 6 having \"working_diagnosis: Osteoarthritis\"\n", "trait_row = 6 # working_diagnosis field contains Osteoarthritis\n", "\n", "# Age data: Available in key 2\n", "age_row = 2 # age field\n", "\n", "# Gender data: Available in key 1\n", "gender_row = 1 # gender field\n", "\n", "# 2.2 Data Type Conversion Functions\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert osteoarthritis diagnosis to binary (0/1)\"\"\"\n", " if value is None or ':' not in value:\n", " return None\n", " \n", " diagnosis = value.split(':', 1)[1].strip()\n", " # Return 1 if diagnosis is Osteoarthritis, 0 otherwise\n", " if diagnosis == 'Osteoarthritis':\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age string to numeric value\"\"\"\n", " if value is None or ':' not in value:\n", " return None\n", " \n", " age_str = value.split(':', 1)[1].strip()\n", " try:\n", " return int(age_str)\n", " except ValueError:\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male)\"\"\"\n", " if value is None or ':' not in value:\n", " return None\n", " \n", " gender = value.split(':', 1)[1].strip()\n", " if gender.upper() == 'F':\n", " return 0\n", " elif gender.upper() == 'M':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata - Initial filtering\n", "# Trait data availability is determined by whether trait_row is None\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info (initial filtering)\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", "# Since trait_row is not None, we need to extract clinical features\n", "if trait_row is not None:\n", " # Create directory for clinical data if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Load the clinical data (assuming it was previously loaded to clinical_data)\n", " # Extract clinical features using the geo_select_clinical_features function\n", " clinical_df = geo_select_clinical_features(\n", " 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 dataframe\n", " print(\"Preview of clinical data:\")\n", " print(preview_df(clinical_df))\n", " \n", " # Save clinical data to CSV\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "d37b9f7d", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "1e0da9ca", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:14.423050Z", "iopub.status.busy": "2025-03-25T05:59:14.422943Z", "iopub.status.idle": "2025-03-25T05:59:14.575492Z", "shell.execute_reply": "2025-03-25T05:59:14.575122Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Osteoarthritis/GSE142049/GSE142049_series_matrix.txt.gz\n", "Gene data shape: (11809, 114)\n", "First 20 gene/probe identifiers:\n", "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651262', 'ILMN_1651278',\n", " 'ILMN_1651315', 'ILMN_1651316', 'ILMN_1651341', 'ILMN_1651343',\n", " 'ILMN_1651346', 'ILMN_1651347', 'ILMN_1651378', 'ILMN_1651385',\n", " 'ILMN_1651405', 'ILMN_1651415', 'ILMN_1651429', 'ILMN_1651433'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the SOFT and matrix file paths again \n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "print(f\"Matrix file found: {matrix_file}\")\n", "\n", "# 2. Use the get_genetic_data function from the library to get the gene_data\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " \n", " # 3. Print the first 20 row IDs (gene or probe identifiers)\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" ] }, { "cell_type": "markdown", "id": "74c81843", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "79357f24", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:14.576751Z", "iopub.status.busy": "2025-03-25T05:59:14.576632Z", "iopub.status.idle": "2025-03-25T05:59:14.578514Z", "shell.execute_reply": "2025-03-25T05:59:14.578244Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers in the gene expression data\n", "# These identifiers start with \"ILMN_\" which indicates they are Illumina probe IDs\n", "# from a microarray platform, not standard human gene symbols\n", "# Illumina probe IDs need to be mapped to human gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "30f9795c", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "18b94065", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:14.579685Z", "iopub.status.busy": "2025-03-25T05:59:14.579585Z", "iopub.status.idle": "2025-03-25T05:59:17.701326Z", "shell.execute_reply": "2025-03-25T05:59:17.700953Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'Species', 'Source', 'Search_Key', 'Transcript', 'ILMN_Gene', 'Source_Reference_ID', 'RefSeq_ID', 'Unigene_ID', 'Entrez_Gene_ID', 'GI', 'Accession', 'Symbol', 'Protein_Product', 'Probe_Id', 'Array_Address_Id', 'Probe_Type', 'Probe_Start', 'SEQUENCE', 'Chromosome', 'Probe_Chr_Orientation', 'Probe_Coordinates', 'Cytoband', 'Definition', 'Ontology_Component', 'Ontology_Process', 'Ontology_Function', 'Synonyms', 'Obsolete_Probe_Id', 'GB_ACC']\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Species': [nan, nan, nan, nan, nan], 'Source': [nan, nan, nan, nan, nan], 'Search_Key': [nan, nan, nan, nan, nan], 'Transcript': [nan, nan, nan, nan, nan], 'ILMN_Gene': [nan, nan, nan, nan, nan], 'Source_Reference_ID': [nan, nan, nan, nan, nan], 'RefSeq_ID': [nan, nan, nan, nan, nan], 'Unigene_ID': [nan, nan, nan, nan, nan], 'Entrez_Gene_ID': [nan, nan, nan, nan, nan], 'GI': [nan, nan, nan, nan, nan], 'Accession': [nan, nan, nan, nan, nan], 'Symbol': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB'], 'Protein_Product': [nan, nan, nan, nan, 'thrB'], 'Probe_Id': [nan, nan, nan, nan, nan], 'Array_Address_Id': [5090180.0, 6510136.0, 7560739.0, 1450438.0, 1240647.0], 'Probe_Type': [nan, nan, nan, nan, nan], 'Probe_Start': [nan, nan, nan, nan, nan], 'SEQUENCE': ['GAATAAAGAACAATCTGCTGATGATCCCTCCGTGGATCTGATTCGTGTAA', 'CCATGTGATACGAGGGCGCGTAGTTTGCATTATCGTTTTTATCGTTTCAA', 'CCGACAGATGTATGTAAGGCCAACGTGCTCAAATCTTCATACAGAAAGAT', 'TCTGTCACTGTCAGGAAAGTGGTAAAACTGCAACTCAATTACTGCAATGC', 'CTTGTGCCTGAGCTGTCAAAAGTAGAGCACGTCGCCGAGATGAAGGGCGC'], 'Chromosome': [nan, nan, nan, nan, nan], 'Probe_Chr_Orientation': [nan, nan, nan, nan, nan], 'Probe_Coordinates': [nan, nan, nan, nan, nan], 'Cytoband': [nan, nan, nan, nan, nan], 'Definition': [nan, nan, nan, nan, nan], 'Ontology_Component': [nan, nan, nan, nan, nan], 'Ontology_Process': [nan, nan, nan, nan, nan], 'Ontology_Function': [nan, nan, nan, nan, nan], 'Synonyms': [nan, nan, nan, nan, nan], 'Obsolete_Probe_Id': [nan, nan, nan, nan, nan], 'GB_ACC': [nan, nan, nan, nan, nan]}\n", "\n", "Searching for platform information in SOFT file:\n", "Platform ID not found in first 100 lines\n", "\n", "Searching for gene symbol information in SOFT file:\n", "Found references to gene symbols:\n", "#ILMN_Gene = Internal gene symbol\n", "#Symbol = Gene symbol from the source database\n", "#Synonyms = Gene symbol synonyms from Refseq\n", "ID\tSpecies\tSource\tSearch_Key\tTranscript\tILMN_Gene\tSource_Reference_ID\tRefSeq_ID\tUnigene_ID\tEntrez_Gene_ID\tGI\tAccession\tSymbol\tProtein_Product\tProbe_Id\tArray_Address_Id\tProbe_Type\tProbe_Start\tSEQUENCE\tChromosome\tProbe_Chr_Orientation\tProbe_Coordinates\tCytoband\tDefinition\tOntology_Component\tOntology_Process\tOntology_Function\tSynonyms\tObsolete_Probe_Id\tGB_ACC\n", "\n", "Checking for additional annotation files in the directory:\n", "[]\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. Analyze the gene annotation dataframe to identify which columns contain the gene identifiers and gene symbols\n", "print(\"\\nGene annotation preview:\")\n", "print(f\"Columns in gene annotation: {gene_annotation.columns.tolist()}\")\n", "print(preview_df(gene_annotation, n=5))\n", "\n", "# Let's look for platform information in the SOFT file to understand the annotation better\n", "print(\"\\nSearching for platform information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " for i, line in enumerate(f):\n", " if '!Series_platform_id' in line:\n", " print(line.strip())\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Platform ID not found in first 100 lines\")\n", " break\n", "\n", "# Check if the SOFT file includes any reference to gene symbols\n", "print(\"\\nSearching for gene symbol information in SOFT file:\")\n", "with gzip.open(soft_file, 'rt') as f:\n", " gene_symbol_lines = []\n", " for i, line in enumerate(f):\n", " if 'GENE_SYMBOL' in line or 'gene_symbol' in line.lower() or 'symbol' in line.lower():\n", " gene_symbol_lines.append(line.strip())\n", " if i > 1000 and len(gene_symbol_lines) > 0: # Limit search but ensure we found something\n", " break\n", " \n", " if gene_symbol_lines:\n", " print(\"Found references to gene symbols:\")\n", " for line in gene_symbol_lines[:5]: # Show just first 5 matches\n", " print(line)\n", " else:\n", " print(\"No explicit gene symbol references found in first 1000 lines\")\n", "\n", "# Look for alternative annotation files or references in the directory\n", "print(\"\\nChecking for additional annotation files in the directory:\")\n", "all_files = os.listdir(in_cohort_dir)\n", "print([f for f in all_files if 'annotation' in f.lower() or 'platform' in f.lower() or 'gpl' in f.lower()])\n" ] }, { "cell_type": "markdown", "id": "b9799a59", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "71cafc05", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:17.702696Z", "iopub.status.busy": "2025-03-25T05:59:17.702577Z", "iopub.status.idle": "2025-03-25T05:59:18.387482Z", "shell.execute_reply": "2025-03-25T05:59:18.387116Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping shape: (44837, 2)\n", "Preview of gene mapping:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Gene': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB']}\n", "Gene expression data shape after mapping: (8480, 114)\n", "First 10 gene symbols after mapping:\n", "['A2LD1', 'AAAS', 'AADACL1', 'AAGAB', 'AAMP', 'AARS', 'AARS2', 'AARSD1', 'AASDH', 'AASDHPPT']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Osteoarthritis/gene_data/GSE142049.csv\n" ] } ], "source": [ "# 1. Examine the gene identifiers from the expression data and the annotation data\n", "# From previous output, we can see:\n", "# - Gene expression data index contains Illumina probe IDs like 'ILMN_1343291'\n", "# - Gene annotation dataframe has 'ID' column that contains the same format of identifiers\n", "# - 'Symbol' column in gene annotation contains gene symbols\n", "\n", "# 2. Extract gene mapping using the get_gene_mapping function\n", "gene_mapping = get_gene_mapping(gene_annotation, 'ID', 'Symbol')\n", "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n", "print(\"Preview of gene mapping:\")\n", "print(preview_df(gene_mapping, n=5))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "# This handles many-to-many relationships by dividing expression values for probes \n", "# that map to multiple genes, then summing values for each gene\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First 10 gene symbols after mapping:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# Create directory for gene data if it doesn't exist\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "\n", "# Save gene expression data to CSV file\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": "ba9c6a07", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "33d37909", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:18.388890Z", "iopub.status.busy": "2025-03-25T05:59:18.388763Z", "iopub.status.idle": "2025-03-25T05:59:22.313324Z", "shell.execute_reply": "2025-03-25T05:59:22.312834Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (8480, 114)\n", "Gene data column names (sample IDs):\n", "Index(['GSM4218229', 'GSM4218230', 'GSM4218231', 'GSM4218232', 'GSM4218233'], dtype='object')\n", "\n", "Raw clinical data structure:\n", "Clinical data shape: (7, 115)\n", "Clinical data columns: Index(['!Sample_geo_accession', 'GSM4218229', 'GSM4218230', 'GSM4218231',\n", " 'GSM4218232'],\n", " dtype='object')\n", "\n", "Sample characteristics dictionary:\n", "{0: ['patient: 2367', 'patient: 2390', 'patient: 2368', 'patient: 2437', 'patient: 2439', 'patient: 2379', 'patient: 1010', 'patient: 841', 'patient: 926', 'patient: 948', 'patient: 898', 'patient: 980', 'patient: 2145', 'patient: 2036', 'patient: 2040', 'patient: 2029', 'patient: 2044', 'patient: 2030', 'patient: 2045', 'patient: 2231', 'patient: 2257', 'patient: 2233', 'patient: 2261', 'patient: 1070', 'patient: 1054', 'patient: 1072', 'patient: 1076', 'patient: 1080', 'patient: 1083', 'patient: 2047'], 1: ['gender: M', 'gender: F'], 2: ['age: 82', 'age: 29', 'age: 61', 'age: 56', 'age: 55', 'age: 72', 'age: 50', 'age: 22', 'age: 53', 'age: 54', 'age: 20', 'age: 49', 'age: 59', 'age: 57', 'age: 35', 'age: 58', 'age: 69', 'age: 46', 'age: 66', 'age: 52', 'age: 63', 'age: 51', 'age: 60', 'age: 92', 'age: 65', 'age: 73', 'age: 43', 'age: 67', 'age: 27', 'age: 32'], 3: ['tissue: peripheral blood'], 4: ['cell type: CD19+ B cells'], 5: ['first_diagnosis: Undifferentiated Spondylo-Arthropathy', 'first_diagnosis: Other Inflammatory Arthritis', 'first_diagnosis: Undifferentiated Inflammatory Arthritis', 'first_diagnosis: Rheumatoid Arthritis', 'first_diagnosis: Crystal Arthritis', 'first_diagnosis: Enteropathic Arthritis', 'first_diagnosis: Osteoarthritis', 'first_diagnosis: Psoriatic Arthritis', 'first_diagnosis: Reactive Arthritis', 'first_diagnosis: Non-Inflammatory'], 6: ['working_diagnosis: Undifferentiated Spondylo-Arthropathy', 'working_diagnosis: Other Inflammatory Arthritis', 'working_diagnosis: Rheumatoid Arthritis', 'working_diagnosis: Reactive Arthritis', 'working_diagnosis: Enteropathic Arthritis', 'working_diagnosis: Psoriatic Arthritis', 'working_diagnosis: Osteoarthritis', 'working_diagnosis: Crystal Arthritis', 'working_diagnosis: Non-Inflammatory', 'working_diagnosis: Undifferentiated Inflammatory Arthritis', 'working_diagnosis: Lupus/Other CTD-Associated']}\n", "\n", "Values in trait row:\n", "['!Sample_characteristics_ch1'\n", " 'working_diagnosis: Undifferentiated Spondylo-Arthropathy'\n", " 'working_diagnosis: Other Inflammatory Arthritis'\n", " 'working_diagnosis: Rheumatoid Arthritis'\n", " 'working_diagnosis: Reactive Arthritis']\n", "\n", "Created clinical features dataframe:\n", "Shape: (1, 114)\n", " GSM4218229 GSM4218230 GSM4218231 GSM4218232 GSM4218233\n", "Osteoarthritis 0 0 0 0 0\n", "\n", "Linked data shape before handling missing values: (114, 8481)\n", "Actual trait column in linked data: Osteoarthritis\n" ] }, { "name": "stderr", "output_type": "stream", "text": [ "/media/techt/DATA/GenoAgent/tools/preprocess.py:455: FutureWarning: Downcasting object dtype arrays on .fillna, .ffill, .bfill is deprecated and will change in a future version. Call result.infer_objects(copy=False) instead. To opt-in to the future behavior, set `pd.set_option('future.no_silent_downcasting', True)`\n", " df[gene_cols] = df[gene_cols].fillna(df[gene_cols].mean())\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (114, 8481)\n", "For the feature 'Osteoarthritis', the least common label is '1' with 6 occurrences. This represents 5.26% of the dataset.\n", "The distribution of the feature 'Osteoarthritis' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Osteoarthritis/GSE142049.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data \n", "# (This was already done in the previous step, so no need to repeat)\n", "print(f\"Normalized gene data shape: {gene_data.shape}\")\n", "\n", "# 2. Examine the sample IDs in the gene expression data to understand the structure\n", "print(\"Gene data column names (sample IDs):\")\n", "print(gene_data.columns[:5]) # Print first 5 for brevity\n", "\n", "# Inspect the clinical data format from the matrix file directly\n", "background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", "print(\"\\nRaw clinical data structure:\")\n", "print(f\"Clinical data shape: {clinical_data.shape}\")\n", "print(f\"Clinical data columns: {clinical_data.columns[:5]}\")\n", "\n", "# Get the sample characteristics to re-extract the disease information\n", "sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", "print(\"\\nSample characteristics dictionary:\")\n", "print(sample_characteristics_dict)\n", "\n", "# 3. Directly create clinical features from the raw data again\n", "# Verify trait row contains the disease information (OA vs RA)\n", "print(\"\\nValues in trait row:\")\n", "trait_values = clinical_data.iloc[trait_row].values\n", "print(trait_values[:5])\n", "\n", "# Create clinical dataframe with proper structure\n", "# First get the sample IDs from gene data as these are our actual sample identifiers\n", "sample_ids = gene_data.columns.tolist()\n", "\n", "# Create the clinical features dataframe with those sample IDs\n", "clinical_features = pd.DataFrame(index=[trait], columns=sample_ids)\n", "\n", "# Fill the clinical features with our trait values by mapping GSM IDs to actual values\n", "for col in clinical_data.columns:\n", " if col in sample_ids:\n", " # Extract the disease value and convert it\n", " disease_val = clinical_data.iloc[trait_row][col]\n", " clinical_features.loc[trait, col] = convert_trait(disease_val)\n", "\n", "print(\"\\nCreated clinical features dataframe:\")\n", "print(f\"Shape: {clinical_features.shape}\")\n", "print(clinical_features.iloc[:, :5]) # Show first 5 columns\n", "\n", "# 4. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", "print(f\"\\nLinked data shape before handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Handle missing values - we need to use the actual column name, not the trait variable\n", "# First identify the actual trait column name in the linked data\n", "trait_column = clinical_features.index[0] # This should be 'Osteoarthritis'\n", "print(f\"Actual trait column in linked data: {trait_column}\")\n", "\n", "# Now handle missing values with the correct column name\n", "linked_data_clean = handle_missing_values(linked_data, trait_column)\n", "print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n", "\n", "# 6. Evaluate bias in trait and demographic features\n", "is_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait_column)\n", "\n", "# 7. Conduct final quality validation\n", "note = \"Dataset contains gene expression data from synovial fibroblasts of RA and OA patients. Data includes high serum and low serum responses.\"\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=(linked_data_clean.shape[0] > 0),\n", " is_biased=is_biased,\n", " df=linked_data_clean,\n", " note=note\n", ")\n", "\n", "# 8. Save linked data if usable\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_clean.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset deemed not usable due to quality issues - 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 }