{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "35e9ad93", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:44.608784Z", "iopub.status.busy": "2025-03-25T06:00:44.608569Z", "iopub.status.idle": "2025-03-25T06:00:44.776148Z", "shell.execute_reply": "2025-03-25T06:00:44.775766Z" } }, "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 = \"GSE98460\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Osteoarthritis\"\n", "in_cohort_dir = \"../../input/GEO/Osteoarthritis/GSE98460\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Osteoarthritis/GSE98460.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Osteoarthritis/gene_data/GSE98460.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Osteoarthritis/clinical_data/GSE98460.csv\"\n", "json_path = \"../../output/preprocess/Osteoarthritis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "78a5cae0", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "bf1069aa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:44.777645Z", "iopub.status.busy": "2025-03-25T06:00:44.777497Z", "iopub.status.idle": "2025-03-25T06:00:44.923618Z", "shell.execute_reply": "2025-03-25T06:00:44.923261Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Transcriptional Analysis of Articular Cartilage in Knee Osteoarthritis: Relationship with Obesity\"\n", "!Series_summary\t\"Objective: To examine the changes in tibial plateau cartilage in relation to body mass index (BMI) in patients with end-stage osteoarthritis (OA). Design: Knees were obtained from 23 OA patients (3 non-obese, 20 obese) at the time of total knee replacement. RNA prepared from cartilage was probed for differentially expressed (DE) gene transcripts using RNA microarrays and validated via real-time PCR. Differences with regard to age, sex, and between medial and lateral compartments were also queried. Results: Microarrays revealed that numerous transcripts were significantly DE between non-obese and obese patients (≥1.5-fold) using pooled and separate data from medial and lateral compartments. Correlation analyses showed that 706 transcripts (459 positively, 247 negatively) were significantly correlated with BMI. Among these, HS3ST6, HSD17B12, and FAM26F were positively correlated while STAC3, PRSS21, and EDA were negatively correlated. Differentially correlated transcripts represented important biological processes e.g. cellular metabolic processes, anatomical structure morphogenesis and cellular response to growth factors. Although age and sex had some effect on transcript expression, most intriguing results were observed for comparison between medial and lateral compartments. Transcripts (MMP13, CLEC3A, MATN3, EPYC, SCARNA5, COL2A1) elevated in the medial compartment represented skeletal system development, cartilage development, collagen and proteoglycan metabolism, and extracellular matrix organization. Likewise, transcripts (SELE, CTSS, VSIG4, F13A1, and STEAP4) repressed in medial compartment represented host immune response, cell migration, wound healing, cell proliferation and response to cytokines. PCR data confirmed expression of DE transcripts. Conclusions: This study supports molecular interaction between obesity and OA and implies that BMI is an important determinant of transcript-level changes in cartilage.\"\n", "!Series_overall_design\t\"Total RNA obtained from isolated from medial and lateral tibial plateau cartilage from patients undergoing total knee arthroplasty.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['tissue: tibial plateau cartilage'], 1: ['diagnosis: osteoarthritis (OA)'], 2: ['age (years): 59', 'age (years): 52', 'age (years): 53', 'age (years): 57', 'age (years): 66', 'age (years): 71', 'age (years): 65', 'age (years): 68', 'age (years): 56', 'age (years): 51', 'age (years): 61', 'age (years): 72', 'age (years): 58', 'age (years): 70', 'age (years): 54'], 3: ['Sex: Female', 'Sex: Male'], 4: ['bmi (kg/m2): 39', 'bmi (kg/m2): 43', 'bmi (kg/m2): 41', 'bmi (kg/m2): 35', 'bmi (kg/m2): 27', 'bmi (kg/m2): 42', 'bmi (kg/m2): 37', 'bmi (kg/m2): 40', 'bmi (kg/m2): 34', 'bmi (kg/m2): 38', 'bmi (kg/m2): 32', 'bmi (kg/m2): 31'], 5: ['side: Right', 'side: Left']}\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": "df889c1c", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "49be7e1b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:44.924777Z", "iopub.status.busy": "2025-03-25T06:00:44.924667Z", "iopub.status.idle": "2025-03-25T06:00:44.932139Z", "shell.execute_reply": "2025-03-25T06:00:44.931849Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical features:\n", "{'Osteoarthritis': [1, 1, 1, 1, 1], 'Age': [59, 52, 53, 57, 66], 'Gender': [0, 1, 0, 1, 0]}\n", "Clinical data saved to ../../output/preprocess/Osteoarthritis/clinical_data/GSE98460.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# From the background information, we can see this dataset contains transcriptional analysis data from RNA microarrays\n", "# This suggests it contains gene expression data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# For trait (Osteoarthritis), the data is in row 1 - all patients have OA\n", "trait_row = 1\n", "\n", "# For age, the data is in row 2\n", "age_row = 2\n", "\n", "# For gender, the data is in row 3\n", "gender_row = 3\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " # Handle None values\n", " if value is None:\n", " return None\n", " # All patients have osteoarthritis according to row 1\n", " # Binary conversion: 1 for OA, 0 for non-OA\n", " # In this case, all are OA\n", " if \"osteoarthritis\" in value.lower():\n", " return 1\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " # Handle None values\n", " if value is None:\n", " return None\n", " # Extract age value after colon\n", " try:\n", " age_str = value.split(\": \")[1]\n", " return int(age_str)\n", " except (IndexError, ValueError):\n", " return None\n", "\n", "def convert_gender(value):\n", " # Handle None values\n", " if value is None:\n", " return None\n", " # Binary conversion: 0 for female, 1 for male\n", " try:\n", " gender = value.split(\": \")[1].strip()\n", " if gender.lower() == \"female\":\n", " return 0\n", " elif gender.lower() == \"male\":\n", " return 1\n", " else:\n", " return None\n", " except (IndexError, ValueError):\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Initial filtering on usability\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", "if trait_row is not None:\n", " # Create the clinical data DataFrame properly formatted for geo_select_clinical_features\n", " # We need to create a DataFrame where each column is a sample\n", " \n", " # First get the maximum number of samples across all characteristics\n", " sample_char_dict = {\n", " 0: ['tissue: tibial plateau cartilage'], \n", " 1: ['diagnosis: osteoarthritis (OA)'], \n", " 2: ['age (years): 59', 'age (years): 52', 'age (years): 53', 'age (years): 57', 'age (years): 66', \n", " 'age (years): 71', 'age (years): 65', 'age (years): 68', 'age (years): 56', 'age (years): 51', \n", " 'age (years): 61', 'age (years): 72', 'age (years): 58', 'age (years): 70', 'age (years): 54'], \n", " 3: ['Sex: Female', 'Sex: Male'], \n", " 4: ['bmi (kg/m2): 39', 'bmi (kg/m2): 43', 'bmi (kg/m2): 41', 'bmi (kg/m2): 35', 'bmi (kg/m2): 27', \n", " 'bmi (kg/m2): 42', 'bmi (kg/m2): 37', 'bmi (kg/m2): 40', 'bmi (kg/m2): 34', 'bmi (kg/m2): 38', \n", " 'bmi (kg/m2): 32', 'bmi (kg/m2): 31'], \n", " 5: ['side: Right', 'side: Left']\n", " }\n", " \n", " # Determine the samples directly in a suitable format for our needs\n", " samples = []\n", " \n", " # Find the feature with the most values to determine how many samples we have\n", " max_samples = max(len(values) for values in sample_char_dict.values())\n", " \n", " # For trait (OA), we'll duplicate the value for all samples since all patients have OA\n", " trait_values = [sample_char_dict[trait_row][0]] * max_samples\n", " \n", " # For age and gender, we need to find which samples have which values\n", " # This dataset seems to have the values grouped but not explicitly mapped to samples\n", " # Based on the data, we'll have to make some assumptions\n", " \n", " # Create a DataFrame with the features we care about\n", " clinical_df = pd.DataFrame({\n", " trait: [convert_trait(trait_values[i]) if i < len(trait_values) else None for i in range(max_samples)],\n", " 'Age': [convert_age(sample_char_dict[age_row][i]) if i < len(sample_char_dict[age_row]) else None for i in range(max_samples)],\n", " 'Gender': [convert_gender(sample_char_dict[gender_row][i % len(sample_char_dict[gender_row])]) for i in range(max_samples)]\n", " })\n", " \n", " # Preview the dataframe\n", " preview = preview_df(clinical_df)\n", " print(\"Preview of clinical features:\")\n", " print(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", " clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "a8b22dd2", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "d6539c8b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:44.933182Z", "iopub.status.busy": "2025-03-25T06:00:44.933074Z", "iopub.status.idle": "2025-03-25T06:00:45.129632Z", "shell.execute_reply": "2025-03-25T06:00:45.129296Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Osteoarthritis/GSE98460/GSE98460_series_matrix.txt.gz\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (53617, 46)\n", "First 20 gene/probe identifiers:\n", "Index(['16650001', '16650003', '16650005', '16650007', '16650009', '16650011',\n", " '16650013', '16650015', '16650017', '16650019', '16650021', '16650023',\n", " '16650025', '16650027', '16650029', '16650031', '16650033', '16650035',\n", " '16650037', '16650041'],\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": "4224d143", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "0001f7aa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:45.130845Z", "iopub.status.busy": "2025-03-25T06:00:45.130723Z", "iopub.status.idle": "2025-03-25T06:00:45.132707Z", "shell.execute_reply": "2025-03-25T06:00:45.132412Z" } }, "outputs": [], "source": [ "# Examining the gene identifiers from the previous step's output\n", "# The identifiers appear to be numeric IDs (like '16650001', '16650003', etc.)\n", "# These are likely probe IDs or some other technical identifiers, not standard human gene symbols\n", "# Human gene symbols would typically be alphanumeric like \"BRCA1\", \"TP53\", etc.\n", "\n", "# Since these identifiers need mapping to standard gene symbols for meaningful analysis\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "3220cb44", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "db0066f2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:45.133738Z", "iopub.status.busy": "2025-03-25T06:00:45.133632Z", "iopub.status.idle": "2025-03-25T06:00:47.911088Z", "shell.execute_reply": "2025-03-25T06:00:47.910543Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'RANGE_STRAND', 'RANGE_START', 'RANGE_END', 'total_probes', 'GB_ACC', 'SPOT_ID', 'RANGE_GB']\n", "{'ID': ['16657436', '16657440', '16657445', '16657447', '16657450'], 'RANGE_STRAND': ['+', '+', '+', '+', '+'], 'RANGE_START': [12190.0, 29554.0, 69091.0, 160446.0, 317811.0], 'RANGE_END': [13639.0, 31109.0, 70008.0, 161525.0, 328581.0], 'total_probes': [25.0, 28.0, 8.0, 13.0, 36.0], 'GB_ACC': ['NR_046018', nan, nan, nan, 'NR_024368'], 'SPOT_ID': ['chr1:12190-13639', 'chr1:29554-31109', 'chr1:69091-70008', 'chr1:160446-161525', 'chr1:317811-328581'], 'RANGE_GB': ['NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10', 'NC_000001.10']}\n", "\n", "Searching for platform information in SOFT file:\n", "!Series_platform_id = GPL16686\n", "\n", "Searching for gene symbol information in SOFT file:\n", "Found references to gene symbols:\n", "!Platform_relation = Alternative to: GPL25483 (Gene symbol version)\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": "ae018947", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "6fdbd7d2", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:47.912723Z", "iopub.status.busy": "2025-03-25T06:00:47.912603Z", "iopub.status.idle": "2025-03-25T06:00:51.673283Z", "shell.execute_reply": "2025-03-25T06:00:51.672631Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Checking for GPL16686 platform annotation...\n", "Found 17623 probe IDs with RefSeq accessions out of 2520409 total\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Created mapping for 47833 probes\n", "Preview of mapping dataframe:\n", " ID Gene\n", "0 16657436 [NR_046018]\n", "1 16657440 [CHR1_29554_31109]\n", "2 16657445 [CHR1_69091_70008]\n", "3 16657447 [CHR1_160446_161525]\n", "4 16657450 [NR_024368]\n", "Mapped gene expression data shape: (0, 46)\n", "Sample of gene symbols after mapping:\n", "No genes were successfully mapped.\n", "Using original probe IDs as gene identifiers\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Osteoarthritis/gene_data/GSE98460.csv\n" ] } ], "source": [ "# 1. Let's take a different approach for mapping probe IDs to gene symbols\n", "# Since this is platform GPL16686, let's first check if there's any platform-specific annotation\n", "\n", "# We can't find standard gene symbols directly, so we'll need to:\n", "# 1. Extract RefSeq accessions from GB_ACC column \n", "# 2. Map these RefSeq accessions to gene symbols using external mappings\n", "# 3. For probes without accessions, we'll have to use other identifiers\n", "\n", "# Check if there's a platform annotation file we can download\n", "print(\"\\nChecking for GPL16686 platform annotation...\")\n", "try:\n", " # Use the annotation data we already have\n", " # First, let's count how many valid GB_ACC entries we have\n", " valid_acc_count = gene_annotation['GB_ACC'].notna().sum()\n", " print(f\"Found {valid_acc_count} probe IDs with RefSeq accessions out of {len(gene_annotation)} total\")\n", " \n", " # Create an initial mapping using RefSeq accessions\n", " mapping_df = pd.DataFrame()\n", " mapping_df['ID'] = gene_annotation['ID']\n", " \n", " # For gene extraction, we'll use a direct approach mapping RefSeq accessions\n", " def extract_genes_from_refseq(acc):\n", " if pd.isna(acc):\n", " return []\n", " \n", " # Extract potential gene symbols from RefSeq accession\n", " acc_str = str(acc)\n", " \n", " # Check for known gene symbol patterns in the accession description\n", " gene_matches = re.findall(r'\\(([A-Z0-9]+)\\)', acc_str)\n", " if gene_matches:\n", " return gene_matches\n", " \n", " # If no gene symbols in parentheses, treat the accession as the gene ID\n", " # This isn't ideal but gives us something to work with\n", " return [acc_str]\n", " \n", " # Apply extraction to the GB_ACC column\n", " gene_annotation['Gene'] = gene_annotation['GB_ACC'].apply(extract_genes_from_refseq)\n", " \n", " # For entries without genes extracted, get them from the spot ID if possible\n", " empty_genes = gene_annotation['Gene'].apply(lambda x: len(x) == 0)\n", " \n", " # Use the SPOT_ID column to extract potential genomic features\n", " def extract_from_spot_id(spot_id):\n", " if pd.isna(spot_id):\n", " return []\n", " \n", " # Extract chromosome and location\n", " match = re.match(r'chr(\\w+):(\\d+)-(\\d+)', str(spot_id))\n", " if match:\n", " chrom, start, end = match.groups()\n", " # Use a simplified format for genomic features\n", " return [f\"CHR{chrom}_{start}_{end}\"]\n", " return []\n", " \n", " # Apply to rows without gene symbols\n", " gene_annotation.loc[empty_genes, 'Gene'] = gene_annotation.loc[empty_genes, 'SPOT_ID'].apply(extract_from_spot_id)\n", " \n", " # Create the final mapping dataframe\n", " mapping_df['Gene'] = gene_annotation['Gene']\n", " \n", " # Filter out rows without gene information\n", " mapping_df = mapping_df[mapping_df['Gene'].apply(len) > 0]\n", " \n", " print(f\"\\nCreated mapping for {len(mapping_df)} probes\")\n", " print(\"Preview of mapping dataframe:\")\n", " print(mapping_df.head())\n", " \n", " # 3. Apply gene mapping using our custom mapping dataframe\n", " gene_data_mapped = apply_gene_mapping(gene_data, mapping_df)\n", " \n", " print(f\"Mapped gene expression data shape: {gene_data_mapped.shape}\")\n", " print(\"Sample of gene symbols after mapping:\")\n", " if len(gene_data_mapped) > 0:\n", " print(gene_data_mapped.index[:10])\n", " else:\n", " print(\"No genes were successfully mapped.\")\n", " \n", " # Try to normalize gene symbols if possible\n", " try:\n", " if len(gene_data_mapped) > 0:\n", " gene_data_normalized = normalize_gene_symbols_in_index(gene_data_mapped)\n", " print(f\"Normalized gene expression data shape: {gene_data_normalized.shape}\")\n", " print(\"First few gene symbols after normalization:\")\n", " print(gene_data_normalized.index[:10])\n", " # Use the normalized data\n", " gene_data = gene_data_normalized\n", " else:\n", " # If mapping failed, fall back to original probe IDs\n", " print(\"Using original probe IDs as gene identifiers\")\n", " gene_data = gene_data\n", " except Exception as e:\n", " print(f\"Error normalizing gene symbols: {e}\")\n", " # Fallback to unmapped data if normalization fails\n", " print(\"Using mapped data without normalization\")\n", " gene_data = gene_data_mapped if len(gene_data_mapped) > 0 else gene_data\n", " \n", " # Save the gene data to file regardless of mapping success\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", " \n", "except Exception as e:\n", " print(f\"Error during gene mapping: {e}\")\n", " # Fallback: save the original gene data without mapping\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\"Original gene expression data saved to {out_gene_data_file} without mapping\")\n" ] }, { "cell_type": "markdown", "id": "e5188cf4", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "9a4e28ea", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:00:51.675131Z", "iopub.status.busy": "2025-03-25T06:00:51.675008Z", "iopub.status.idle": "2025-03-25T06:00:52.819309Z", "shell.execute_reply": "2025-03-25T06:00:52.818782Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape: (53617, 46)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Osteoarthritis/gene_data/GSE98460.csv\n", "Loaded clinical data from file\n", "Clinical data shape: (15, 3)\n", "Clinical data preview: {'Osteoarthritis': [1, 1, 1, 1, 1], 'Age': [59, 52, 53, 57, 66], 'Gender': [0, 1, 0, 1, 0]}\n", "Clinical data index: [0, 1, 2, 3, 4]\n", "Clinical data columns: ['Osteoarthritis', 'Age', 'Gender']\n", "Clinical data for linking shape: (3, 15)\n", "Clinical data for linking index: ['Osteoarthritis', 'Age', 'Gender']\n", "Gene data for linking shape: (53617, 46)\n", "Gene data for linking index sample: ['16650001', '16650003', '16650005', '16650007', '16650009']\n", "Linked data shape before handling missing values: (61, 53620)\n", "Linked data columns sample: ['Osteoarthritis', 'Age', 'Gender', '16650001', '16650003', '16650005', '16650007', '16650009', '16650011', '16650013']\n", "Linked data shape after handling missing values: (0, 2)\n", "Quartiles for 'Osteoarthritis':\n", " 25%: nan\n", " 50% (Median): nan\n", " 75%: nan\n", "Min: nan\n", "Max: nan\n", "The distribution of the feature 'Osteoarthritis' in this dataset is fine.\n", "\n", "Quartiles for 'Age':\n", " 25%: nan\n", " 50% (Median): nan\n", " 75%: nan\n", "Min: nan\n", "Max: nan\n", "The distribution of the feature 'Age' in this dataset is fine.\n", "\n", "Abnormality detected in the cohort: GSE98460. Preprocessing failed.\n", "Dataset deemed not usable due to quality issues - linked data not saved\n" ] } ], "source": [ "# 1. Save the gene data since we already extracted it in the previous step\n", "print(f\"Gene data shape: {gene_data.shape}\")\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", "\n", "# 2. Load clinical data from the file we saved in step 2\n", "try:\n", " clinical_features_df = pd.read_csv(out_clinical_data_file)\n", " print(\"Loaded clinical data from file\")\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " # If we can't load the file, recreate it from the original data\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Use the original conversion functions from step 2\n", " def convert_trait(value):\n", " # All patients have osteoarthritis according to row 1\n", " if value is None:\n", " return None\n", " if \"osteoarthritis\" in value.lower():\n", " return 1\n", " else:\n", " return None\n", "\n", " def convert_age(value):\n", " if value is None:\n", " return None\n", " try:\n", " age_str = value.split(\": \")[1]\n", " return int(age_str)\n", " except (IndexError, ValueError):\n", " return None\n", "\n", " def convert_gender(value):\n", " if value is None:\n", " return None\n", " try:\n", " gender = value.split(\": \")[1].strip()\n", " if gender.lower() == \"female\":\n", " return 0\n", " elif gender.lower() == \"male\":\n", " return 1\n", " else:\n", " return None\n", " except (IndexError, ValueError):\n", " return None\n", " \n", " clinical_features_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", " clinical_features_df.to_csv(out_clinical_data_file, index=True)\n", "\n", "# Print clinical data shape and preview\n", "print(\"Clinical data shape:\", clinical_features_df.shape)\n", "print(\"Clinical data preview:\", preview_df(clinical_features_df.T if clinical_features_df.shape[0] < 5 else clinical_features_df))\n", "\n", "# 3. Link clinical and genetic data\n", "# Debug the structure of clinical_features_df\n", "print(\"Clinical data index:\", clinical_features_df.index.tolist()[:5]) # First 5 indices\n", "print(\"Clinical data columns:\", clinical_features_df.columns.tolist())\n", "\n", "# Prepare clinical data with proper format (samples as columns, features as rows)\n", "if trait in clinical_features_df.columns:\n", " # If trait is a column, data is likely in sample-per-row format, transpose it\n", " clinical_for_linking = clinical_features_df.set_index('Unnamed: 0').T if 'Unnamed: 0' in clinical_features_df.columns else clinical_features_df.T\n", "else:\n", " # If trait is not a column, data might already be in feature-per-row format\n", " clinical_for_linking = clinical_features_df\n", "\n", "print(\"Clinical data for linking shape:\", clinical_for_linking.shape)\n", "print(\"Clinical data for linking index:\", clinical_for_linking.index.tolist())\n", "print(\"Gene data for linking shape:\", gene_data.shape)\n", "print(\"Gene data for linking index sample:\", gene_data.index.tolist()[:5])\n", "\n", "# Ensure trait is in the index of clinical_for_linking\n", "if trait not in clinical_for_linking.index and 'Osteoarthritis' in clinical_for_linking.index:\n", " # Rename index for consistency\n", " clinical_for_linking = clinical_for_linking.rename(index={'Osteoarthritis': trait})\n", "\n", "# Link the data\n", "linked_data = geo_link_clinical_genetic_data(clinical_for_linking, gene_data)\n", "print(f\"Linked data shape before handling missing values: {linked_data.shape}\")\n", "print(\"Linked data columns sample:\", linked_data.columns.tolist()[:10])\n", "\n", "# 4. Handle missing values\n", "# Check if trait is in linked_data columns\n", "if trait in linked_data.columns:\n", " trait_col = trait\n", "elif 'Osteoarthritis' in linked_data.columns:\n", " trait_col = 'Osteoarthritis'\n", "else:\n", " # Fallback: try to identify the trait column\n", " possible_trait_cols = [col for col in linked_data.columns if 'osteo' in col.lower()]\n", " trait_col = possible_trait_cols[0] if possible_trait_cols else linked_data.columns[0]\n", " print(f\"Using '{trait_col}' as the trait column\")\n", "\n", "# Handle missing values with the identified trait column\n", "linked_data = handle_missing_values(linked_data, trait_col)\n", "print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", "\n", "# 5. Evaluate bias in trait and demographic features\n", "# If trait_col is different from the global trait variable, update it\n", "is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait_col)\n", "\n", "# 6. Conduct final quality validation\n", "note = \"Dataset contains expression data from tibial plateau cartilage in osteoarthritis patients, with BMI and other clinical variables. All patients have osteoarthritis according to the metadata.\"\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\")" ] } ], "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 }