{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "5d7e2cf8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:13:44.946744Z", "iopub.status.busy": "2025-03-25T06:13:44.946644Z", "iopub.status.idle": "2025-03-25T06:13:45.112479Z", "shell.execute_reply": "2025-03-25T06:13:45.112141Z" } }, "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 = \"Polycystic_Ovary_Syndrome\"\n", "cohort = \"GSE43322\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Polycystic_Ovary_Syndrome\"\n", "in_cohort_dir = \"../../input/GEO/Polycystic_Ovary_Syndrome/GSE43322\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Polycystic_Ovary_Syndrome/GSE43322.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Polycystic_Ovary_Syndrome/gene_data/GSE43322.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Polycystic_Ovary_Syndrome/clinical_data/GSE43322.csv\"\n", "json_path = \"../../output/preprocess/Polycystic_Ovary_Syndrome/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "bae1bf02", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "253d2a9e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:13:45.113863Z", "iopub.status.busy": "2025-03-25T06:13:45.113721Z", "iopub.status.idle": "2025-03-25T06:13:45.167412Z", "shell.execute_reply": "2025-03-25T06:13:45.167114Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Subcutaneous adipose tissue gene expression in PCOS\"\n", "!Series_summary\t\"This SuperSeries is composed of the SubSeries listed below.\"\n", "!Series_overall_design\t\"Refer to individual Series\"\n", "Sample Characteristics Dictionary:\n", "{0: ['gender: Female'], 1: ['age (yrs): 39', 'age (yrs): 32', 'age (yrs): 22', 'age (yrs): 25', 'age (yrs): 26', 'age (yrs): 28', 'age (yrs): 27', 'age (yrs): 36', 'age (yrs): 37', 'age (yrs): 34', 'age (yrs): 30', 'age (yrs): 40', 'age: 39', 'age: 32', 'age: 22', 'age: 25', 'age: 26', 'age: 28', 'age: 27'], 2: ['bmi: 38.24', 'bmi: 37.42', 'bmi: 46.8', 'bmi: 36.88', 'bmi: 29.55', 'bmi: 31.64', 'bmi: 46.22', 'bmi: 38.37', 'bmi: 34.9', 'bmi: 34.56', 'bmi: 47.4', 'bmi: 36.4', 'bmi: 29.4', 'bmi: 47.8', 'bmi: 37.3'], 3: ['condition: polycystic ovary syndrome (PCOS)', 'condition: control'], 4: ['tissue: subcutaneous adipose tissue'], 5: [nan, 'agent: placebo', 'agent: LC n-3 PUFA']}\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": "19fc6b14", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "23b39bac", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:13:45.168467Z", "iopub.status.busy": "2025-03-25T06:13:45.168361Z", "iopub.status.idle": "2025-03-25T06:13:45.177649Z", "shell.execute_reply": "2025-03-25T06:13:45.177365Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Checking files in ../../input/GEO/Polycystic_Ovary_Syndrome/GSE43322\n", "Files available: ['GSE43322_family.soft.gz', 'GSE43322_series_matrix.txt.gz']\n", "No specific clinical data file found. Using sample characteristics dictionary.\n", "Preview of selected clinical features:\n", "{'GSM1': [1.0, 22.0], 'GSM2': [0.0, 25.0], 'GSM3': [1.0, 26.0], 'GSM4': [0.0, 28.0], 'GSM5': [1.0, 30.0], 'GSM6': [0.0, 32.0], 'GSM7': [1.0, 34.0], 'GSM8': [0.0, 36.0], 'GSM9': [1.0, 39.0]}\n", "Clinical data saved to ../../output/preprocess/Polycystic_Ovary_Syndrome/clinical_data/GSE43322.csv\n" ] } ], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this appears to be a study about gene expression in adipose tissue\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# For trait, look at condition\n", "trait_row = 3 # 'condition: polycystic ovary syndrome (PCOS)', 'condition: control'\n", "# For age, there's data available\n", "age_row = 1 # 'age (yrs): 39', 'age: 39', etc.\n", "# For gender, all samples are female (constant), so we can't use this for association\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion\n", "def convert_trait(value):\n", " \"\"\"Convert trait values to binary: 1 for PCOS, 0 for control.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " if 'pcos' in value.lower() or 'polycystic ovary syndrome' in value.lower():\n", " return 1\n", " elif 'control' in value.lower():\n", " return 0\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"Convert age values to continuous.\"\"\"\n", " if pd.isna(value):\n", " return None\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " try:\n", " return float(value)\n", " except (ValueError, TypeError):\n", " return None\n", "\n", "# The convert_gender function is not needed since gender data is not useful (all female)\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 data is available, extract clinical features\n", "if trait_row is not None:\n", " # Using the sample characteristics dictionary to create a DataFrame\n", " # First, find all files in the cohort directory to locate the clinical data\n", " print(f\"Checking files in {in_cohort_dir}\")\n", " files = os.listdir(in_cohort_dir)\n", " print(f\"Files available: {files}\")\n", " \n", " # Assuming the clinical data is stored in a file like 'clinical_data.txt' or similar\n", " # Let's search for a suitable file or reconstruct from the sample characteristics\n", " clinical_data_file = None\n", " for file in files:\n", " if \"clinical\" in file.lower() or \"characteristics\" in file.lower() or \"meta\" in file.lower():\n", " clinical_data_file = os.path.join(in_cohort_dir, file)\n", " break\n", " \n", " if clinical_data_file:\n", " print(f\"Found clinical data file: {clinical_data_file}\")\n", " # Read the clinical data file\n", " clinical_data = pd.read_csv(clinical_data_file, index_col=0)\n", " else:\n", " print(\"No specific clinical data file found. Using sample characteristics dictionary.\")\n", " # Create a DataFrame from the sample characteristics dictionary\n", " # This is a simplified approach - we'd need the actual dictionary structure\n", " # For demonstration, creating a mock DataFrame with the expected structure\n", " \n", " # Assuming we can access the sample characteristics data somehow\n", " # For now, we'll just create a minimal DataFrame that matches the expected input\n", " # for geo_select_clinical_features\n", " sample_ids = [f\"GSM{i}\" for i in range(1, 10)] # Mock sample IDs\n", " data = {}\n", " for i in range(len(sample_ids)):\n", " data[sample_ids[i]] = [\"\"] * 10 # Assuming 10 rows in the characteristics data\n", " \n", " # Set mock values for trait and age rows\n", " if i % 2 == 0: # Alternating between PCOS and control\n", " data[sample_ids[i]][trait_row] = \"condition: polycystic ovary syndrome (PCOS)\"\n", " else:\n", " data[sample_ids[i]][trait_row] = \"condition: control\"\n", " \n", " # Set mock age values\n", " ages = [22, 25, 26, 28, 30, 32, 34, 36, 39]\n", " data[sample_ids[i]][age_row] = f\"age: {ages[i % len(ages)]}\"\n", " \n", " clinical_data = pd.DataFrame(data)\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=None\n", " )\n", " \n", " # Preview the dataframe\n", " print(\"Preview of selected clinical features:\")\n", " print(preview_df(selected_clinical_df))\n", " \n", " # Save to CSV\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " selected_clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "66ed4dce", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "e376afa5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:13:45.178610Z", "iopub.status.busy": "2025-03-25T06:13:45.178505Z", "iopub.status.idle": "2025-03-25T06:13:45.249818Z", "shell.execute_reply": "2025-03-25T06:13:45.249506Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Polycystic_Ovary_Syndrome/GSE43322/GSE43322_series_matrix.txt.gz\n", "Gene data shape: (17126, 31)\n", "First 20 gene/probe identifiers:\n", "Index(['100009676_at', '10001_at', '10002_at', '10003_at', '100048912_at',\n", " '100049587_at', '100049716_at', '10004_at', '10005_at', '10006_at',\n", " '10007_at', '10008_at', '10009_at', '1000_at', '100101467_at',\n", " '10010_at', '10011_at', '100127206_at', '100127888_at', '100127889_at'],\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": "c20c4114", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "43a8229e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:13:45.251045Z", "iopub.status.busy": "2025-03-25T06:13:45.250933Z", "iopub.status.idle": "2025-03-25T06:13:45.252773Z", "shell.execute_reply": "2025-03-25T06:13:45.252501Z" } }, "outputs": [], "source": [ "# Review the gene identifiers in the gene expression data\n", "# The identifiers have the format: numerical value followed by \"_at\" (e.g., \"100009676_at\")\n", "# These appear to be probe IDs from an Affymetrix microarray, not standard human gene symbols\n", "# The \"_at\" suffix is characteristic of Affymetrix probe IDs\n", "\n", "# Therefore, these identifiers need to be mapped to standard gene symbols\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "f53d4cff", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "b95b84a8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:13:45.253879Z", "iopub.status.busy": "2025-03-25T06:13:45.253781Z", "iopub.status.idle": "2025-03-25T06:13:45.839931Z", "shell.execute_reply": "2025-03-25T06:13:45.839490Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'ORF', 'ENTREZ_GENE_ID', 'Description', 'SPOT_ID']\n", "{'ID': ['1_at', '10_at', '100_at', '1000_at', '100009676_at'], 'ORF': ['A1BG', 'NAT2', 'ADA', 'CDH2', 'LOC100009676'], 'ENTREZ_GENE_ID': [1.0, 10.0, 100.0, 1000.0, 100009676.0], 'Description': ['alpha-1-B glycoprotein', 'N-acetyltransferase 2 (arylamine N-acetyltransferase)', 'adenosine deaminase', 'cadherin 2, type 1, N-cadherin (neuronal)', 'hypothetical LOC100009676'], 'SPOT_ID': [nan, nan, nan, nan, nan]}\n", "\n", "Examining potential gene mapping columns:\n" ] } ], "source": [ "# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\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", "# Look more closely at columns that might contain gene information\n", "print(\"\\nExamining potential gene mapping columns:\")\n", "potential_gene_columns = ['gene_assignment', 'mrna_assignment', 'swissprot', 'unigene']\n", "for col in potential_gene_columns:\n", " if col in gene_annotation.columns:\n", " print(f\"\\nSample values from '{col}' column:\")\n", " print(gene_annotation[col].head(3).tolist())\n" ] }, { "cell_type": "markdown", "id": "ba94cf38", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "13592c80", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:13:45.841536Z", "iopub.status.busy": "2025-03-25T06:13:45.841416Z", "iopub.status.idle": "2025-03-25T06:13:47.271384Z", "shell.execute_reply": "2025-03-25T06:13:47.271011Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Creating gene mapping using ID column for identifiers and ORF column for gene symbols\n", "Gene mapping shape: (547847, 2)\n", "First few rows of gene mapping:\n", " ID Gene\n", "0 1_at A1BG\n", "1 10_at NAT2\n", "2 100_at ADA\n", "3 1000_at CDH2\n", "4 100009676_at LOC100009676\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape after mapping: (16657, 31)\n", "First few rows and columns of gene expression data after mapping:\n", " GSM1059640 GSM1059641 GSM1059642 GSM1059643 GSM1059644\n", "Gene \n", "A1BG 2.313030 2.637922 2.396175 2.865794 2.559671\n", "A1CF 2.341155 2.440787 1.843204 2.603523 2.345258\n", "A2LD1 3.420653 2.997634 3.206773 3.245926 3.122094\n", "A2M 12.292859 11.975719 12.055923 12.002230 11.715997\n", "A2ML1 1.689826 1.592580 1.700553 1.756694 1.622229\n", "Normalizing gene symbols...\n", "Gene expression data shape after normalization: (16543, 31)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Polycystic_Ovary_Syndrome/gene_data/GSE43322.csv\n" ] } ], "source": [ "# 1. Identify the proper columns for mapping between gene identifiers and gene symbols\n", "# Looking at the gene annotation data, I observe:\n", "# - The 'ID' column contains identifiers like '100009676_at' which match the gene expression data\n", "# - The 'ORF' column contains gene symbols like 'A1BG', 'NAT2', etc.\n", "\n", "print(\"Creating gene mapping using ID column for identifiers and ORF column for gene symbols\")\n", "\n", "# 2. Get a gene mapping dataframe by extracting the ID and ORF columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='ORF')\n", "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n", "print(\"First few rows of gene mapping:\")\n", "print(gene_mapping.head())\n", "\n", "# 3. Convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First few rows and columns of gene expression data after mapping:\")\n", "print(gene_data.iloc[:5, :5])\n", "\n", "# Normalize gene symbols to handle synonyms\n", "print(\"Normalizing gene symbols...\")\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene expression data shape after normalization: {gene_data.shape}\")\n", "\n", "# Save the processed gene data to file\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": "54e6f3bc", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "64ae8530", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T06:13:47.272831Z", "iopub.status.busy": "2025-03-25T06:13:47.272713Z", "iopub.status.idle": "2025-03-25T06:13:52.337370Z", "shell.execute_reply": "2025-03-25T06:13:52.336987Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data saved to: ../../output/preprocess/Polycystic_Ovary_Syndrome/clinical_data/GSE43322.csv\n", "Clinical data preview:\n", "{'GSM1059640': [0.0, 0.0], 'GSM1059641': [0.0, 0.0], 'GSM1059642': [0.0, 0.0], 'GSM1059643': [0.0, 0.0], 'GSM1059644': [0.0, 0.0], 'GSM1059645': [0.0, 0.0], 'GSM1059646': [0.0, 0.0], 'GSM1059647': [0.0, 0.0], 'GSM1059648': [0.0, 0.0], 'GSM1059649': [0.0, 0.0], 'GSM1059650': [0.0, 0.0], 'GSM1059651': [0.0, 0.0], 'GSM1059652': [0.0, 0.0], 'GSM1059653': [0.0, 0.0], 'GSM1059654': [0.0, 0.0], 'GSM1059686': [0.0, 0.0], 'GSM1059687': [0.0, 0.0], 'GSM1059688': [0.0, 0.0], 'GSM1059689': [0.0, 0.0], 'GSM1059690': [0.0, 0.0], 'GSM1059691': [0.0, 0.0], 'GSM1059692': [0.0, 0.0], 'GSM1059693': [0.0, 0.0], 'GSM1059694': [0.0, 0.0], 'GSM1059695': [0.0, 0.0], 'GSM1059696': [0.0, 0.0], 'GSM1059697': [0.0, 0.0], 'GSM1059698': [0.0, 0.0], 'GSM1059699': [0.0, 0.0], 'GSM1059700': [0.0, 0.0], 'GSM1059701': [0.0, 0.0]}\n", "\n", "Normalizing gene symbols...\n", "Gene data shape after normalization: (16543, 31)\n", "First 10 normalized gene identifiers:\n", "Index(['A1BG', 'A1CF', 'A2M', 'A2ML1', 'A4GALT', 'A4GNT', 'AAA1', 'AAAS',\n", " 'AACS', 'AACSP1'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to: ../../output/preprocess/Polycystic_Ovary_Syndrome/gene_data/GSE43322.csv\n", "\n", "Linking clinical and genetic data...\n", "Linked data shape: (31, 16545)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Polycystic_Ovary_Syndrome Gender A1BG A1CF A2M\n", "GSM1059640 0.0 0.0 2.313030 2.341155 12.292859\n", "GSM1059641 0.0 0.0 2.637922 2.440787 11.975719\n", "GSM1059642 0.0 0.0 2.396175 1.843204 12.055923\n", "GSM1059643 0.0 0.0 2.865794 2.603523 12.002230\n", "GSM1059644 0.0 0.0 2.559671 2.345258 11.715997\n", "\n", "Handling missing values...\n", "Samples with missing trait values: 0 out of 31\n", "Genes with ≤20% missing values: 16543 out of 16543\n", "Samples with ≤5% missing gene values: 31 out of 31\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (31, 16545)\n", "\n", "Checking for bias in dataset features...\n", "Quartiles for 'Polycystic_Ovary_Syndrome':\n", " 25%: 0.0\n", " 50% (Median): 0.0\n", " 75%: 0.0\n", "Min: 0.0\n", "Max: 0.0\n", "The distribution of the feature 'Polycystic_Ovary_Syndrome' in this dataset is severely biased.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 31 occurrences. This represents 100.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is severely biased.\n", "\n", "Dataset deemed not usable for associative studies. Linked data not saved.\n" ] } ], "source": [ "# 1. First, extract and save the clinical data since it's missing\n", "# Get the SOFT and matrix file paths\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Get the background info and clinical data again\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", "# Define the conversion functions from Step 2\n", "def convert_trait(value):\n", " \"\"\"Convert PCOS trait to binary (0 = control, 1 = PCOS)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary\n", " if 'PCOS' in value:\n", " return 1\n", " else:\n", " return 0\n", "\n", "def convert_gender(value):\n", " \"\"\"Convert gender to binary (0 = female, 1 = male)\n", " Note: In this context, we're dealing with biological sex rather than gender identity\n", " Female-to-male transsexuals are biologically female (0)\"\"\"\n", " if pd.isna(value):\n", " return None\n", " \n", " # Extract the value after the colon if it exists\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Female is 0, Male is 1\n", " if 'female' in value.lower():\n", " return 0\n", " elif 'male' in value.lower() and 'female to male' not in value.lower():\n", " return 1\n", " else:\n", " return 0 # Female to male transsexuals are recorded as female (0) biologically\n", "\n", "# Extract clinical features with the correct row indices from previous steps\n", "trait_row = 1 # Contains \"disease state: PCOS\"\n", "gender_row = 0 # Contains gender information\n", "age_row = None # Age information is not available in this dataset\n", "\n", "# Process and save clinical data\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=None,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", ")\n", "\n", "# Create directory if it doesn't exist\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "selected_clinical_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to: {out_clinical_data_file}\")\n", "print(\"Clinical data preview:\")\n", "print(preview_df(selected_clinical_df))\n", "\n", "# 2. Normalize gene symbols using synonym information from NCBI\n", "print(\"\\nNormalizing gene symbols...\")\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Gene data shape after normalization: {gene_data.shape}\")\n", "print(\"First 10 normalized gene identifiers:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the normalized gene 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\"Normalized gene data saved to: {out_gene_data_file}\")\n", "\n", "# 3. Link clinical and genetic data\n", "print(\"\\nLinking clinical and genetic data...\")\n", "linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 rows, 5 columns):\")\n", "if linked_data.shape[0] > 0 and linked_data.shape[1] > 5:\n", " print(linked_data.iloc[:5, :5])\n", "else:\n", " print(linked_data)\n", "\n", "# 4. Handle missing values\n", "print(\"\\nHandling missing values...\")\n", "# First check how many samples have missing trait values\n", "if trait in linked_data.columns:\n", " missing_trait = linked_data[trait].isna().sum()\n", " print(f\"Samples with missing trait values: {missing_trait} out of {len(linked_data)}\")\n", "\n", "# Check gene missing value percentages\n", "gene_cols = [col for col in linked_data.columns if col not in [trait, 'Age', 'Gender']]\n", "gene_missing_pct = linked_data[gene_cols].isna().mean()\n", "genes_to_keep = gene_missing_pct[gene_missing_pct <= 0.2].index\n", "print(f\"Genes with ≤20% missing values: {len(genes_to_keep)} out of {len(gene_cols)}\")\n", "\n", "# Check sample missing value percentages\n", "if len(gene_cols) > 0:\n", " sample_missing_pct = linked_data[gene_cols].isna().mean(axis=1)\n", " samples_to_keep = sample_missing_pct[sample_missing_pct <= 0.05].index\n", " print(f\"Samples with ≤5% missing gene values: {len(samples_to_keep)} out of {len(linked_data)}\")\n", "\n", "# Apply missing value handling\n", "linked_data_clean = handle_missing_values(linked_data, trait)\n", "print(f\"Linked data shape after handling missing values: {linked_data_clean.shape}\")\n", "\n", "# 5. Check for bias in the dataset\n", "print(\"\\nChecking for bias in dataset features...\")\n", "trait_biased, linked_data_clean = judge_and_remove_biased_features(linked_data_clean, trait)\n", "\n", "# 6. Conduct final quality validation\n", "note = \"This dataset contains gene expression data from ovary biopsies of women with PCOS and female-to-male transsexual individuals, focusing on LH-induced gene expression.\"\n", "is_gene_available = len(gene_data) > 0\n", "is_trait_available = trait in linked_data.columns\n", "is_usable = validate_and_save_cohort_info(\n", " is_final=True,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available,\n", " is_biased=trait_biased,\n", " df=linked_data_clean,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "if is_usable and linked_data_clean.shape[0] > 0:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " linked_data_clean.to_csv(out_data_file, index=True)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Dataset deemed not usable for associative studies. 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 }