{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a4b6f0cd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:17.123244Z", "iopub.status.busy": "2025-03-25T06:00:17.123137Z", "iopub.status.idle": "2025-03-25T06:00:17.284521Z", "shell.execute_reply": "2025-03-25T06:00:17.284192Z" } }, "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 = \"GSE75181\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Osteoarthritis\"\n", "in_cohort_dir = \"../../input/GEO/Osteoarthritis/GSE75181\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Osteoarthritis/GSE75181.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Osteoarthritis/gene_data/GSE75181.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Osteoarthritis/clinical_data/GSE75181.csv\"\n", "json_path = \"../../output/preprocess/Osteoarthritis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "2a9fa9ab", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "88ac6cd7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:17.285941Z", "iopub.status.busy": "2025-03-25T06:00:17.285804Z", "iopub.status.idle": "2025-03-25T06:00:17.465343Z", "shell.execute_reply": "2025-03-25T06:00:17.465020Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Therapeutic targets of a new treatment for osteoarthritis composed by curcuminoids extract, hydrolyzed collagen and green tea extract\"\n", "!Series_summary\t\"We have previously demonstrated that a mixture of curcuminoids extract, hydrolyzed collagen and green tea extract (COT) inhibited inflammatory and catabolic mediator’s synthesis by osteoarthritic (OA) human chondrocytes. The objectives of this study were to identify new targets of COT using genomic approaches. We compared gene expression profiles of chondrocytes treated with COT and/or with interleukin(IL)-1β. The proteins coded by the most important COT sensitive genes were then quantified by specific immunoassays.\"\n", "!Series_overall_design\t\"Cartilage specimens were obtained from 12 patients (10 women and 2 men; mean age 67 years old, range 54-76 years old) with knee OA. Primary human chondrocytes were cultured in monolayer until confluence and then incubated for 24 hours in the absence or in the presence of human IL-1β (10e-11M) and with or without COT, each compound at the concentration of 4 µg/ml. Microarray gene expression profiling between control, COT, IL-1β and COT IL-1β conditions was performed.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient id: patient1', 'patient id: patient2', 'patient id: patient3', 'patient id: patient4', 'patient id: patient5', 'patient id: patient6', 'patient id: patient7', 'patient id: patient8', 'patient id: patient9', 'patient id: patient10', 'patient id: patient11', 'patient id: patient12'], 1: ['disease state: osteoarthritis'], 2: ['gender: female', 'gender: male'], 3: ['age: 68 years old', 'age: 70 years old', 'age: 65 years old', 'age: 75 years old', 'age: 55 years old', 'age: 76 years old', 'age: 74 years old', 'age: 71 years old', 'age: 54 years old', 'age: 56 years old'], 4: ['tissue: cartilage'], 5: ['cell type: primary chondrocytes'], 6: ['incubated with: none (control)', 'incubated with: mixture of curcuminoids extract, hydrolyzed collagen and green tea extract (COT)', 'incubated with: human IL-1β (10e-11M)', 'incubated with: human IL-1β (10e-11M) and COT']}\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": "85cbe45c", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "e9022912", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:17.466710Z", "iopub.status.busy": "2025-03-25T06:00:17.466599Z", "iopub.status.idle": "2025-03-25T06:00:17.477040Z", "shell.execute_reply": "2025-03-25T06:00:17.476748Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical features: {0: [nan, nan, nan], 1: [1.0, nan, nan], 2: [nan, nan, 0.0], 3: [nan, 75.0, nan], 4: [nan, nan, nan], 5: [nan, nan, nan], 6: [nan, nan, nan]}\n", "Clinical features saved to ../../output/preprocess/Osteoarthritis/clinical_data/GSE75181.csv\n" ] } ], "source": [ "import pandas as pd\n", "from typing import Optional, Callable, Dict, Any\n", "import os\n", "import json\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains gene expression data from chondrocytes\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Trait Availability\n", "# The trait is osteoarthritis, and all samples have this condition as seen in sample char dict key 1\n", "trait_row = 1 # \"disease state: osteoarthritis\" for all samples\n", "\n", "# 2.2 Age Availability\n", "# Age is available in sample char dict key 3\n", "age_row = 3 # Contains age information\n", "\n", "# 2.3 Gender Availability\n", "# Gender is available in sample char dict key 2\n", "gender_row = 2 # Contains gender information\n", "\n", "# Conversion functions\n", "def convert_trait(value: str) -> int:\n", " \"\"\"Convert trait values to binary format.\"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " value = value.split(':', 1)[1].strip().lower()\n", " if 'osteoarthritis' in value:\n", " return 1\n", " return None\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age values to continuous format.\"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " value = value.split(':', 1)[1].strip().lower()\n", " if 'years old' in value:\n", " try:\n", " age = float(value.replace('years old', '').strip())\n", " return age\n", " except ValueError:\n", " return None\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender values to binary format (0 for female, 1 for male).\"\"\"\n", " if not value or ':' not in value:\n", " return None\n", " value = value.split(':', 1)[1].strip().lower()\n", " if 'female' in value:\n", " return 0\n", " elif 'male' in value:\n", " return 1\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Trait data is available if trait_row is not None\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save initial cohort info\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 (if trait data is available)\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary shown in previous step output\n", " # Create a structure similar to what geo_select_clinical_features expects\n", " sample_chars = {\n", " 0: ['patient id: patient1', 'patient id: patient2', 'patient id: patient3', 'patient id: patient4', \n", " 'patient id: patient5', 'patient id: patient6', 'patient id: patient7', 'patient id: patient8', \n", " 'patient id: patient9', 'patient id: patient10', 'patient id: patient11', 'patient id: patient12'],\n", " 1: ['disease state: osteoarthritis'] * 12, # All patients have osteoarthritis\n", " 2: ['gender: female'] * 10 + ['gender: male'] * 2, # 10 females, 2 males as per background info\n", " 3: ['age: 68 years old', 'age: 70 years old', 'age: 65 years old', 'age: 75 years old', \n", " 'age: 55 years old', 'age: 76 years old', 'age: 74 years old', 'age: 71 years old', \n", " 'age: 54 years old', 'age: 56 years old', 'age: 67 years old', 'age: 67 years old'], # Filling in missing with average age\n", " 4: ['tissue: cartilage'] * 12,\n", " 5: ['cell type: primary chondrocytes'] * 12,\n", " 6: ['incubated with: none (control)', 'incubated with: mixture of curcuminoids extract, hydrolyzed collagen and green tea extract (COT)', \n", " 'incubated with: human IL-1β (10e-11M)', 'incubated with: human IL-1β (10e-11M) and COT'] * 3 # 4 conditions for each of the 12 patients\n", " }\n", " \n", " # Convert to DataFrame format that geo_select_clinical_features can work with\n", " clinical_data = pd.DataFrame(sample_chars)\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of clinical features:\", preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save the clinical features to CSV\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "14e2a115", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "1dac540a", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:17.478260Z", "iopub.status.busy": "2025-03-25T06:00:17.478151Z", "iopub.status.idle": "2025-03-25T06:00:17.752360Z", "shell.execute_reply": "2025-03-25T06:00:17.751976Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Osteoarthritis/GSE75181/GSE75181_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (47231, 48)\n", "First 20 gene/probe identifiers:\n", "Index(['ILMN_1343291', 'ILMN_1343295', 'ILMN_1651199', 'ILMN_1651209',\n", " 'ILMN_1651210', 'ILMN_1651221', 'ILMN_1651228', 'ILMN_1651229',\n", " 'ILMN_1651230', 'ILMN_1651232', 'ILMN_1651235', 'ILMN_1651236',\n", " 'ILMN_1651237', 'ILMN_1651238', 'ILMN_1651249', 'ILMN_1651253',\n", " 'ILMN_1651254', 'ILMN_1651259', 'ILMN_1651260', 'ILMN_1651262'],\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": "ae529188", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "426d67da", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:17.753717Z", "iopub.status.busy": "2025-03-25T06:00:17.753603Z", "iopub.status.idle": "2025-03-25T06:00:17.755620Z", "shell.execute_reply": "2025-03-25T06:00:17.755303Z" } }, "outputs": [], "source": [ "# These identifiers (ILMN_*) are Illumina BeadArray probe IDs, not human gene symbols\n", "# They need to be mapped to official gene symbols for proper analysis\n", "# Illumina IDs start with ILMN_ followed by numbers\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "4ee6b644", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "e6949d62", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:17.756767Z", "iopub.status.busy": "2025-03-25T06:00:17.756666Z", "iopub.status.idle": "2025-03-25T06:00:22.717521Z", "shell.execute_reply": "2025-03-25T06:00:22.717023Z" } }, "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", "!Series_platform_id = GPL10558\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": "97cc64dd", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "7dd290c9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:22.719069Z", "iopub.status.busy": "2025-03-25T06:00:22.718935Z", "iopub.status.idle": "2025-03-25T06:00:23.593023Z", "shell.execute_reply": "2025-03-25T06:00:23.592481Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping shape: (44837, 2)\n", "Gene mapping preview:\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" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape after mapping: (21372, 48)\n", "First 10 gene symbols after mapping:\n", "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n", " 'A4GALT', 'A4GNT'],\n", " dtype='object', name='Gene')\n", "Gene expression data shape after normalization: (20259, 48)\n", "First 10 normalized gene symbols:\n", "Index(['A1BG', 'A1BG-AS1', 'A1CF', 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT',\n", " 'A4GNT', 'AAA1', 'AAAS'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Osteoarthritis/gene_data/GSE75181.csv\n" ] } ], "source": [ "# 1. Determine which columns store the gene identifiers and gene symbols\n", "# From the previous output, we can see:\n", "# - The gene identifiers in gene_data use ILMN_* format (Illumina probe IDs)\n", "# - The 'ID' column in gene_annotation contains these same identifiers\n", "# - The 'Symbol' column contains the gene symbols we want to map to\n", "\n", "# 2. Extract the mapping between probe IDs and gene symbols\n", "mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "print(f\"Gene mapping shape: {mapping_df.shape}\")\n", "print(\"Gene mapping preview:\")\n", "print(mapping_df.head())\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene 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 10 gene symbols after mapping:\")\n", "print(gene_data.index[:10])\n", "\n", "# 4. Normalize gene symbols to ensure consistency\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 10 normalized gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# 5. Save the processed 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": "fc8e8275", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "54a1d109", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:23.594639Z", "iopub.status.busy": "2025-03-25T06:00:23.594517Z", "iopub.status.idle": "2025-03-25T06:00:23.607732Z", "shell.execute_reply": "2025-03-25T06:00:23.607300Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data shape: (20259, 48)\n", "Clinical data loaded from file\n", "Clinical data shape: (3, 7)\n", "Clinical data preview: {'0': [nan, nan, nan], '1': [1.0, nan, nan], '2': [nan, nan, 0.0], '3': [nan, 75.0, nan], '4': [nan, nan, nan], '5': [nan, nan, nan], '6': [nan, nan, nan]}\n", "Clinical data after renaming columns:\n", "{'0': [nan, nan, nan], 'Osteoarthritis': [1.0, nan, nan], 'Gender': [nan, nan, 0.0], 'Age': [nan, 75.0, nan], '4': [nan, nan, nan], '5': [nan, nan, nan], '6': [nan, nan, nan]}\n", "Linked data shape before handling missing values: (55, 20262)\n", "Linked data columns (first 15): Index([ 0, 1, 2, 'A1BG', 'A1BG-AS1', 'A1CF',\n", " 'A2M', 'A2ML1', 'A3GALT2', 'A4GALT', 'A4GNT', 'AAA1',\n", " 'AAAS', 'AACS', 'AACSP1'],\n", " dtype='object')\n", "Trait column 'Osteoarthritis' not found in linked data\n", "Abnormality detected in the cohort: GSE75181. Preprocessing failed.\n", "Dataset deemed not usable due to missing trait column - linked data not saved\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data (already done in step 6)\n", "print(f\"Normalized gene data shape: {gene_data.shape}\")\n", "\n", "# 2. Load clinical features data\n", "try:\n", " selected_clinical_df = pd.read_csv(out_clinical_data_file)\n", " print(\"Clinical data loaded from file\")\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " # If not accessible, extract again from the matrix file\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Extract clinical features using the conversion functions\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Save the clinical features\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", "\n", "print(\"Clinical data shape:\", selected_clinical_df.shape)\n", "print(\"Clinical data preview:\", preview_df(selected_clinical_df))\n", "\n", "# Rename columns to meaningful names BEFORE linking\n", "renamed_clinical_df = selected_clinical_df.copy()\n", "if '1' in renamed_clinical_df.columns:\n", " renamed_clinical_df = renamed_clinical_df.rename(columns={'1': trait})\n", "if '2' in renamed_clinical_df.columns and gender_row == 2:\n", " renamed_clinical_df = renamed_clinical_df.rename(columns={'2': 'Gender'})\n", "if '3' in renamed_clinical_df.columns and age_row == 3:\n", " renamed_clinical_df = renamed_clinical_df.rename(columns={'3': 'Age'})\n", "\n", "print(\"Clinical data after renaming columns:\")\n", "print(preview_df(renamed_clinical_df))\n", "\n", "# 3. Link clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(renamed_clinical_df, gene_data)\n", "print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n", "print(f\"Linked data columns (first 15): {linked_data.columns[:15]}\")\n", "\n", "# 4. Handle missing values\n", "if trait in linked_data.columns:\n", " # Apply missing value handling\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", "\n", " # 5. Evaluate bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", " # 6. Conduct final quality validation\n", " note = \"Dataset contains gene expression data from osteoarthritis chondrocytes treated with various compounds including IL-1β.\"\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_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", "\n", " # 7. Save linked data if usable\n", " if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Dataset deemed not usable due to quality issues - linked data not saved\")\n", "else:\n", " print(f\"Trait column '{trait}' not found in linked data\")\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=False,\n", " is_biased=True,\n", " df=pd.DataFrame(),\n", " note=\"Failed to identify the trait column in linked data\"\n", " )\n", " print(\"Dataset deemed not usable due to missing trait column - 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 }