{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "4e6b4834", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:05.347315Z", "iopub.status.busy": "2025-03-25T05:59:05.347095Z", "iopub.status.idle": "2025-03-25T05:59:05.515099Z", "shell.execute_reply": "2025-03-25T05:59:05.514743Z" } }, "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 = \"GSE141934\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Osteoarthritis\"\n", "in_cohort_dir = \"../../input/GEO/Osteoarthritis/GSE141934\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Osteoarthritis/GSE141934.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Osteoarthritis/gene_data/GSE141934.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Osteoarthritis/clinical_data/GSE141934.csv\"\n", "json_path = \"../../output/preprocess/Osteoarthritis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "55060b05", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "a9e2c551", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:05.516349Z", "iopub.status.busy": "2025-03-25T05:59:05.516210Z", "iopub.status.idle": "2025-03-25T05:59:05.604669Z", "shell.execute_reply": "2025-03-25T05:59:05.604364Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptional data of inflamatory arthritis T 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. CD4+ 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 GSE80513.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient: 1072', 'patient: 1085', 'patient: 1076', 'patient: 1087', 'patient: 1080', 'patient: 1088', 'patient: 1083', 'patient: 1094', 'patient: 1050', 'patient: 1067', 'patient: 1051', 'patient: 1054', 'patient: 1070', 'patient: 1058', 'patient: 2010', 'patient: 2012', 'patient: 2029', 'patient: 2075', 'patient: 2062', 'patient: 2078', 'patient: 2086', 'patient: 2087', 'patient: 2067', 'patient: 2072', 'patient: 2090', 'patient: 1019', 'patient: 1020', 'patient: 1003', 'patient: 1008', 'patient: 2030'], 1: ['gender: F', 'gender: M'], 2: ['age: 50', 'age: 43', 'age: 66', 'age: 55', 'age: 52', 'age: 54', 'age: 63', 'age: 61', 'age: 58', 'age: 79', 'age: 69', 'age: 57', 'age: 46', 'age: 44', 'age: 59', 'age: 81', 'age: 60', 'age: 92', 'age: 45', 'age: 47', 'age: 27', 'age: 38', 'age: 51', 'age: 70', 'age: 56', 'age: 53', 'age: 74', 'age: 49', 'age: 31', 'age: 65'], 3: ['tissue: peripheral blood'], 4: ['cell type: CD4+ T cells'], 5: ['first_diagnosis: Rheumatoid Arthritis', 'first_diagnosis: Undifferentiated Inflammatory Arthritis', 'first_diagnosis: Reactive Arthritis', 'first_diagnosis: Crystal Arthritis', 'first_diagnosis: Psoriatic Arthritis', 'first_diagnosis: Non-Inflammatory', 'first_diagnosis: Other Inflammatory Arthritis', 'first_diagnosis: Enteropathic Arthritis', 'first_diagnosis: Undifferentiated Spondylo-Arthropathy', 'first_diagnosis: Unknown'], 6: ['working_diagnosis: Rheumatoid Arthritis', 'working_diagnosis: Psoriatic Arthritis', 'working_diagnosis: Reactive Arthritis', 'working_diagnosis: Crystal Arthritis', 'working_diagnosis: Osteoarthritis', 'working_diagnosis: Non-Inflammatory', 'working_diagnosis: Undifferentiated Inflammatory Arthritis', 'working_diagnosis: Other Inflammatory Arthritis', 'working_diagnosis: Enteropathic Arthritis', 'working_diagnosis: Undifferentiated Spondylo-Arthropathy', 'working_diagnosis: Unknown']}\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": "1312ed95", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "d5057121", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:05.605909Z", "iopub.status.busy": "2025-03-25T05:59:05.605799Z", "iopub.status.idle": "2025-03-25T05:59:05.610775Z", "shell.execute_reply": "2025-03-25T05:59:05.610477Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Trait row identified: 6\n", "Age row identified: 2\n", "Gender row identified: 1\n", "Gene data available: True\n", "Trait data available: True\n", "Conversion functions defined for trait, age, and gender\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the background description, this dataset contains transcriptional data \n", "# from CD4+ T cells, which indicates gene expression data is available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "\n", "# For trait (Osteoarthritis):\n", "# From the sample characteristics, we can see the disease status in the 'working_diagnosis' field (row 6)\n", "# This includes 'Osteoarthritis' which is our trait of interest\n", "trait_row = 6\n", "\n", "# For age:\n", "# Age is clearly available in row 2\n", "age_row = 2\n", "\n", "# For gender:\n", "# Gender is available in row 1\n", "gender_row = 1\n", "\n", "# 2.2 Data Type Conversion\n", "\n", "def convert_trait(value):\n", " \"\"\"Convert working_diagnosis to binary (0 or 1) based on Osteoarthritis status.\"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # 1 if the diagnosis is Osteoarthritis, 0 otherwise\n", " if value.lower() == 'osteoarthritis':\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age to continuous numeric value.\"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 for female, 1 for male).\"\"\"\n", " if pd.isna(value) or not isinstance(value, str):\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if value.upper() == 'F':\n", " return 0\n", " elif value.upper() == 'M':\n", " return 1\n", " else:\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info (initial filtering)\n", "is_usable = 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", "# We'll need to wait for the next step where we should get the actual clinical data\n", "# For now, let's just inform about the identified rows and conversions\n", "print(f\"Trait row identified: {trait_row}\")\n", "print(f\"Age row identified: {age_row}\")\n", "print(f\"Gender row identified: {gender_row}\")\n", "print(f\"Gene data available: {is_gene_available}\")\n", "print(f\"Trait data available: {is_trait_available}\")\n", "print(\"Conversion functions defined for trait, age, and gender\")\n" ] }, { "cell_type": "markdown", "id": "09e54672", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "f1af6a82", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:05.611919Z", "iopub.status.busy": "2025-03-25T05:59:05.611814Z", "iopub.status.idle": "2025-03-25T05:59:05.754790Z", "shell.execute_reply": "2025-03-25T05:59:05.754410Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Osteoarthritis/GSE141934/GSE141934_series_matrix.txt.gz\n", "Gene data shape: (11710, 100)\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_1651347', 'ILMN_1651378', 'ILMN_1651385', 'ILMN_1651403',\n", " 'ILMN_1651405', 'ILMN_1651429', 'ILMN_1651433', 'ILMN_1651438'],\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": "2b11882f", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "4948cdd9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:05.756194Z", "iopub.status.busy": "2025-03-25T05:59:05.756081Z", "iopub.status.idle": "2025-03-25T05:59:05.758136Z", "shell.execute_reply": "2025-03-25T05:59:05.757819Z" } }, "outputs": [], "source": [ "# Analyzing the gene identifiers\n", "# The IDs with \"ILMN_\" prefix are Illumina probe IDs, not human gene symbols\n", "# These 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": "82c0bd35", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "05071084", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:05.759505Z", "iopub.status.busy": "2025-03-25T05:59:05.759398Z", "iopub.status.idle": "2025-03-25T05:59:08.899606Z", "shell.execute_reply": "2025-03-25T05:59:08.899266Z" } }, "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", "ILMN_1651228\tHomo sapiens\tRefSeq\tNM_001031.4\tILMN_992\tRPS28\tNM_001031.4\tNM_001031.4\t\t6234\t71565158\tNM_001031.4\tRPS28\tNP_001022.1\tILMN_1651228\t650349\tS\t329\tCGCCACACGTAACTGAGATGCTCCTTTAAATAAAGCGTTTGTGTTTCAAG\t19\t+\t8293227-8293276\t19p13.2d\t\"Homo sapiens ribosomal protein S28 (RPS28), mRNA.\"\t\"The living contents of a cell; the matter contained within (but not including) the plasma membrane, usually taken to exclude large vacuoles and masses of secretory or ingested material. In eukaryotes it includes the nucleus and cytoplasm [goid 5622] [evidence IEA]; That part of the cytoplasm that does not contain membranous or particulate subcellular components [goid 5829] [pmid 12588972] [evidence EXP]; An intracellular organelle, about 200 A in diameter, consisting of RNA and protein. It is the site of protein biosynthesis resulting from translation of messenger RNA (mRNA). It consists of two subunits, one large and one small, each containing only protein and RNA. Both the ribosome and its subunits are characterized by their sedimentation coefficients, expressed in Svedberg units (symbol: S). Hence, the prokaryotic ribosome (70S) comprises a large (50S) subunit and a small (30S) subunit, while the eukaryotic ribosome (80S) comprises a large (60S) subunit and a small (40S) subunit. Two sites on the ribosomal large subunit are involved in translation, namely the aminoacyl site (A site) and peptidyl site (P site). Ribosomes from prokaryotes, eukaryotes, mitochondria, and chloroplasts have characteristically distinct ribosomal proteins [goid 5840] [evidence IEA]; The small subunit of the ribosome that is found in the cytosol of the cell. The cytosol is that part of the cytoplasm that does not contain membranous or particulate subcellular components [goid 22627] [pmid 15883184] [evidence IDA]\"\tThe successive addition of amino acid residues to a nascent polypeptide chain during protein biosynthesis [goid 6414] [pmid 15189156] [evidence EXP]\tThe action of a molecule that contributes to the structural integrity of the ribosome [goid 3735] [pmid 15883184] [evidence IDA]; Interacting selectively with any protein or protein complex (a complex of two or more proteins that may include other nonprotein molecules) [goid 5515] [pmid 17353931] [evidence IPI]\t\t\tNM_001031.4\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": "0b827b3a", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "287afbd5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:08.901480Z", "iopub.status.busy": "2025-03-25T05:59:08.901326Z", "iopub.status.idle": "2025-03-25T05:59:09.601162Z", "shell.execute_reply": "2025-03-25T05:59:09.600762Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (44837, 2)\n", "Sample of gene mapping data:\n", " ID Gene\n", "0 ILMN_1343048 phage_lambda_genome\n", "1 ILMN_1343049 phage_lambda_genome\n", "2 ILMN_1343050 phage_lambda_genome:low\n", "3 ILMN_1343052 phage_lambda_genome:low\n", "4 ILMN_1343059 thrB\n", "Gene expression data shape after mapping: (8340, 100)\n", "First few rows of gene expression data:\n", " GSM4216498 GSM4216499 GSM4216500 GSM4216501 GSM4216502 \\\n", "Gene \n", "A2LD1 6.624761 6.623393 6.723056 6.903384 6.048768 \n", "AACS 5.615109 5.192011 5.095448 5.465379 5.257583 \n", "AADACL1 13.308954 12.461564 12.518904 13.477049 13.164655 \n", "AAGAB 8.607497 8.284817 8.830837 8.128734 8.351699 \n", "AAK1 9.258350 8.017645 9.570424 7.815827 10.240408 \n", "\n", " GSM4216503 GSM4216504 GSM4216505 GSM4216506 GSM4216507 ... \\\n", "Gene ... \n", "A2LD1 6.557294 6.276624 6.693970 7.367760 5.750950 ... \n", "AACS 4.876709 5.472327 4.943130 5.676548 5.547506 ... \n", "AADACL1 12.661551 13.501444 13.766897 13.226293 13.602111 ... \n", "AAGAB 8.169147 8.137851 8.276188 8.087209 8.333052 ... \n", "AAK1 8.246759 8.534204 7.908607 9.775862 9.826000 ... \n", "\n", " GSM4216588 GSM4216589 GSM4216590 GSM4216591 GSM4216592 \\\n", "Gene \n", "A2LD1 6.863724 6.975783 6.771991 6.278479 6.794510 \n", "AACS 5.346321 6.186861 5.385705 5.374298 5.242745 \n", "AADACL1 13.666755 14.003245 14.017516 13.184242 13.741404 \n", "AAGAB 7.990156 8.048509 8.688550 8.532083 8.614191 \n", "AAK1 8.406194 7.648013 7.366056 8.111105 9.183801 \n", "\n", " GSM4216593 GSM4216594 GSM4216595 GSM4216596 GSM4216597 \n", "Gene \n", "A2LD1 7.090105 6.516512 6.707926 6.715707 7.924908 \n", "AACS 5.665443 5.000639 5.913520 5.655599 5.774701 \n", "AADACL1 13.811879 14.013834 13.251450 13.254498 13.041138 \n", "AAGAB 8.509040 7.988815 8.042588 8.755565 8.714670 \n", "AAK1 8.914431 8.308685 8.879457 10.160098 7.908208 \n", "\n", "[5 rows x 100 columns]\n", "Gene expression data shape after normalization: (8143, 100)\n", "First few gene symbols after normalization:\n", "Index(['AACS', 'AAGAB', 'AAK1', 'AAMDC', 'AAMP', 'AAR2', 'AARS1', 'AARS2',\n", " 'AARSD1', 'AASDH'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Osteoarthritis/gene_data/GSE141934.csv\n" ] } ], "source": [ "# 1. Determine which columns contain probe IDs and gene symbols\n", "# From the gene annotation preview, we can see:\n", "# - 'ID' column contains the probe identifiers (e.g., ILMN_1343048)\n", "# - 'Symbol' column contains the gene symbols\n", "\n", "# 2. Create a gene mapping dataframe\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"Sample of gene mapping data:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply gene mapping to convert probe-level data to gene-level expression data\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First few rows of gene expression data:\")\n", "print(gene_data.head())\n", "\n", "# 4. Clean and normalize gene symbols in the index\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n", "print(\"First few gene symbols after normalization:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the gene expression 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": "1565d6fa", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "45679f2c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:59:09.603035Z", "iopub.status.busy": "2025-03-25T05:59:09.602881Z", "iopub.status.idle": "2025-03-25T05:59:13.266979Z", "shell.execute_reply": "2025-03-25T05:59:13.266585Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (8143, 100)\n", "Gene data column names (sample IDs):\n", "Index(['GSM4216498', 'GSM4216499', 'GSM4216500', 'GSM4216501', 'GSM4216502'], dtype='object')\n", "\n", "Raw clinical data structure:\n", "Clinical data shape: (7, 101)\n", "Clinical data columns: Index(['!Sample_geo_accession', 'GSM4216498', 'GSM4216499', 'GSM4216500',\n", " 'GSM4216501'],\n", " dtype='object')\n", "\n", "Sample characteristics dictionary:\n", "{0: ['patient: 1072', 'patient: 1085', 'patient: 1076', 'patient: 1087', 'patient: 1080', 'patient: 1088', 'patient: 1083', 'patient: 1094', 'patient: 1050', 'patient: 1067', 'patient: 1051', 'patient: 1054', 'patient: 1070', 'patient: 1058', 'patient: 2010', 'patient: 2012', 'patient: 2029', 'patient: 2075', 'patient: 2062', 'patient: 2078', 'patient: 2086', 'patient: 2087', 'patient: 2067', 'patient: 2072', 'patient: 2090', 'patient: 1019', 'patient: 1020', 'patient: 1003', 'patient: 1008', 'patient: 2030'], 1: ['gender: F', 'gender: M'], 2: ['age: 50', 'age: 43', 'age: 66', 'age: 55', 'age: 52', 'age: 54', 'age: 63', 'age: 61', 'age: 58', 'age: 79', 'age: 69', 'age: 57', 'age: 46', 'age: 44', 'age: 59', 'age: 81', 'age: 60', 'age: 92', 'age: 45', 'age: 47', 'age: 27', 'age: 38', 'age: 51', 'age: 70', 'age: 56', 'age: 53', 'age: 74', 'age: 49', 'age: 31', 'age: 65'], 3: ['tissue: peripheral blood'], 4: ['cell type: CD4+ T cells'], 5: ['first_diagnosis: Rheumatoid Arthritis', 'first_diagnosis: Undifferentiated Inflammatory Arthritis', 'first_diagnosis: Reactive Arthritis', 'first_diagnosis: Crystal Arthritis', 'first_diagnosis: Psoriatic Arthritis', 'first_diagnosis: Non-Inflammatory', 'first_diagnosis: Other Inflammatory Arthritis', 'first_diagnosis: Enteropathic Arthritis', 'first_diagnosis: Undifferentiated Spondylo-Arthropathy', 'first_diagnosis: Unknown'], 6: ['working_diagnosis: Rheumatoid Arthritis', 'working_diagnosis: Psoriatic Arthritis', 'working_diagnosis: Reactive Arthritis', 'working_diagnosis: Crystal Arthritis', 'working_diagnosis: Osteoarthritis', 'working_diagnosis: Non-Inflammatory', 'working_diagnosis: Undifferentiated Inflammatory Arthritis', 'working_diagnosis: Other Inflammatory Arthritis', 'working_diagnosis: Enteropathic Arthritis', 'working_diagnosis: Undifferentiated Spondylo-Arthropathy', 'working_diagnosis: Unknown']}\n", "\n", "Values in trait row:\n", "['!Sample_characteristics_ch1' 'working_diagnosis: Rheumatoid Arthritis'\n", " 'working_diagnosis: Psoriatic Arthritis'\n", " 'working_diagnosis: Reactive Arthritis'\n", " 'working_diagnosis: Crystal Arthritis']\n", "\n", "Created clinical features dataframe:\n", "Shape: (1, 100)\n", " GSM4216498 GSM4216499 GSM4216500 GSM4216501 GSM4216502\n", "Osteoarthritis 0 0 0 0 0\n", "\n", "Linked data shape before handling missing values: (100, 8144)\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: (100, 8144)\n", "For the feature 'Osteoarthritis', the least common label is '1' with 5 occurrences. This represents 5.00% 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/GSE141934.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 }