{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "4232e627", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:42.588644Z", "iopub.status.busy": "2025-03-25T07:31:42.588535Z", "iopub.status.idle": "2025-03-25T07:31:42.749738Z", "shell.execute_reply": "2025-03-25T07:31:42.749380Z" } }, "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 = \"Liver_Cancer\"\n", "cohort = \"GSE66843\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Liver_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Liver_Cancer/GSE66843\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Liver_Cancer/GSE66843.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Liver_Cancer/gene_data/GSE66843.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Liver_Cancer/clinical_data/GSE66843.csv\"\n", "json_path = \"../../output/preprocess/Liver_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "a21ee325", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "c4d6ab39", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:42.751175Z", "iopub.status.busy": "2025-03-25T07:31:42.751027Z", "iopub.status.idle": "2025-03-25T07:31:42.840823Z", "shell.execute_reply": "2025-03-25T07:31:42.840515Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"A cell-based model unravels drivers for hepatocarcinogenesis and targets for clinical chemoprevention\"\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: ['time post infection: Day 3 post infection', 'time post infection: Day 7 post infection', 'time post infection: Day 10 post infection'], 1: ['infection: Mock infection (control)', 'infection: HCV Jc1 infection'], 2: ['cell line: Huh7.5.1']}\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": "a0518d00", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "2573845b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:42.841951Z", "iopub.status.busy": "2025-03-25T07:31:42.841840Z", "iopub.status.idle": "2025-03-25T07:31:42.865808Z", "shell.execute_reply": "2025-03-25T07:31:42.865510Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of clinical features:\n", "{'GSM1633236': [0.0], 'GSM1633237': [0.0], 'GSM1633238': [1.0], 'GSM1633239': [1.0], 'GSM1633240': [1.0], 'GSM1633241': [0.0], 'GSM1633242': [0.0], 'GSM1633243': [0.0], 'GSM1633244': [1.0], 'GSM1633245': [1.0], 'GSM1633246': [1.0], 'GSM1633247': [0.0], 'GSM1633248': [0.0], 'GSM1633249': [0.0], 'GSM1633250': [1.0], 'GSM1633251': [1.0], 'GSM1633252': [1.0]}\n", "Clinical features saved to ../../output/preprocess/Liver_Cancer/clinical_data/GSE66843.csv\n" ] } ], "source": [ "# 1. Check for gene expression data availability\n", "# Based on the background information, this seems to be a cell line study with HCV infection\n", "# It's likely that gene expression data is available, but it's not explicitly confirmed in the background information\n", "# Let's set is_gene_available to True, since it's a common type of data in GEO series\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# Looking at sample characteristics:\n", "# Key 0: Time post infection (Day 3, 7, 10) - This is a time variable, not our trait of interest\n", "# Key 1: Infection status (Mock vs HCV) - This could be our trait of interest as it's related to liver disease\n", "# Key 2: Cell line (constant Huh7.5.1) - This is constant across samples\n", "\n", "# For trait: Liver cancer could be inferred from HCV infection status\n", "trait_row = 1 # Infection status (Mock vs HCV)\n", "\n", "# For age: No age data is available (cell line study)\n", "age_row = None\n", "\n", "# For gender: No gender data is available (cell line study)\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert HCV infection status to binary values:\n", " 1 for HCV infection (risk factor for liver cancer)\n", " 0 for Mock infection (control)\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after the colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " if 'HCV' in value:\n", " return 1 # HCV infection (risk factor for liver cancer)\n", " elif 'Mock' in value:\n", " return 0 # Control\n", " else:\n", " return None\n", "\n", "def convert_age(value):\n", " # Not used but defined for completeness\n", " return None\n", "\n", "def convert_gender(value):\n", " # Not used but defined for completeness\n", " return None\n", "\n", "# 3. Save metadata\n", "is_trait_available = trait_row is not None\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 (only if trait_row is not None)\n", "if trait_row is not None:\n", " # Extract clinical features\n", " clinical_features = 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(clinical_features)\n", " print(\"Preview of clinical features:\")\n", " print(preview)\n", " \n", " # Save clinical features to CSV\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical features saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "0502d8b5", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "f71f9b0f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:42.866899Z", "iopub.status.busy": "2025-03-25T07:31:42.866794Z", "iopub.status.idle": "2025-03-25T07:31:42.967352Z", "shell.execute_reply": "2025-03-25T07:31:42.966995Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Matrix file found: ../../input/GEO/Liver_Cancer/GSE66843/GSE66843-GPL10558_series_matrix.txt.gz\n", "Gene data shape: (46116, 17)\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": "48f1849b", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "c23956b0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:42.968786Z", "iopub.status.busy": "2025-03-25T07:31:42.968571Z", "iopub.status.idle": "2025-03-25T07:31:42.970461Z", "shell.execute_reply": "2025-03-25T07:31:42.970177Z" } }, "outputs": [], "source": [ "# The gene identifiers start with \"ILMN_\" which indicates these are Illumina probe IDs\n", "# These are not standard human gene symbols and need to be mapped to gene symbols\n", "# Illumina probe IDs (ILMN_) are specific to Illumina microarray platforms and require mapping\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "77dbd49f", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "bdced562", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:42.971607Z", "iopub.status.busy": "2025-03-25T07:31:42.971506Z", "iopub.status.idle": "2025-03-25T07:31:45.440019Z", "shell.execute_reply": "2025-03-25T07:31:45.439618Z" } }, "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", "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": "4b41a1bf", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "ef590092", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:45.441423Z", "iopub.status.busy": "2025-03-25T07:31:45.441302Z", "iopub.status.idle": "2025-03-25T07:31:45.878362Z", "shell.execute_reply": "2025-03-25T07:31:45.878017Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "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", "Gene mapping shape: (44837, 2)\n", "Gene expression data after mapping:\n", "Shape: (21125, 17)\n", "First few gene symbols:\n", "Index(['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1', 'A2M', 'A2ML1', 'A3GALT2',\n", " 'A4GALT', 'A4GNT'],\n", " dtype='object', name='Gene')\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "After normalization:\n", "Shape: (19956, 17)\n", "First few 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/Liver_Cancer/gene_data/GSE66843.csv\n" ] } ], "source": [ "# 1. Identify the columns for gene mapping\n", "# From examining the gene annotation data, we can see:\n", "# - 'ID' column contains the Illumina probe IDs (ILMN_*)\n", "# - 'Symbol' column contains the gene symbols we want to map to\n", "\n", "# 2. Get the gene mapping dataframe\n", "gene_mapping = get_gene_mapping(\n", " annotation=gene_annotation,\n", " prob_col='ID', # Column containing probe IDs\n", " gene_col='Symbol' # Column containing gene symbols\n", ")\n", "\n", "print(\"Gene mapping preview:\")\n", "print(gene_mapping.head())\n", "print(f\"Gene mapping shape: {gene_mapping.shape}\")\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression data\n", "gene_data = apply_gene_mapping(\n", " expression_df=gene_data, # Probe-level expression data\n", " mapping_df=gene_mapping # Mapping between probes and genes\n", ")\n", "\n", "print(\"Gene expression data after mapping:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(\"First few gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Normalize gene symbols to handle synonyms\n", "gene_data = normalize_gene_symbols_in_index(gene_data)\n", "print(\"\\nAfter normalization:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(\"First few normalized gene symbols:\")\n", "print(gene_data.index[:10])\n", "\n", "# Save the gene expression data\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": "45ec925e", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "9ee01ecb", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:31:45.879825Z", "iopub.status.busy": "2025-03-25T07:31:45.879711Z", "iopub.status.idle": "2025-03-25T07:31:52.666860Z", "shell.execute_reply": "2025-03-25T07:31:52.666526Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical data saved to: ../../output/preprocess/Liver_Cancer/clinical_data/GSE66843.csv\n", "Clinical data preview:\n", "{'GSM1633236': [0.0, 0.0], 'GSM1633237': [0.0, 0.0], 'GSM1633238': [0.0, 0.0], 'GSM1633239': [0.0, 0.0], 'GSM1633240': [0.0, 0.0], 'GSM1633241': [0.0, 0.0], 'GSM1633242': [0.0, 0.0], 'GSM1633243': [0.0, 0.0], 'GSM1633244': [0.0, 0.0], 'GSM1633245': [0.0, 0.0], 'GSM1633246': [0.0, 0.0], 'GSM1633247': [0.0, 0.0], 'GSM1633248': [0.0, 0.0], 'GSM1633249': [0.0, 0.0], 'GSM1633250': [0.0, 0.0], 'GSM1633251': [0.0, 0.0], 'GSM1633252': [0.0, 0.0]}\n", "\n", "Normalizing gene symbols...\n", "Gene data shape after normalization: (19956, 17)\n", "First 10 normalized gene identifiers:\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": [ "Normalized gene data saved to: ../../output/preprocess/Liver_Cancer/gene_data/GSE66843.csv\n", "\n", "Linking clinical and genetic data...\n", "Linked data shape: (17, 19958)\n", "Linked data preview (first 5 rows, 5 columns):\n", " Liver_Cancer Gender A1BG A1BG-AS1 A1CF\n", "GSM1633236 0.0 0.0 175.902881 84.928332 2058.146767\n", "GSM1633237 0.0 0.0 175.467437 87.225868 1601.515698\n", "GSM1633238 0.0 0.0 185.163824 89.011397 1713.037609\n", "GSM1633239 0.0 0.0 175.411354 85.778853 1508.079221\n", "GSM1633240 0.0 0.0 181.091704 84.390770 1556.390170\n", "\n", "Handling missing values...\n", "Samples with missing trait values: 0 out of 17\n", "Genes with ≤20% missing values: 19956 out of 19956\n", "Samples with ≤5% missing gene values: 17 out of 17\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (17, 19958)\n", "\n", "Checking for bias in dataset features...\n", "Quartiles for 'Liver_Cancer':\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 'Liver_Cancer' in this dataset is severely biased.\n", "\n", "For the feature 'Gender', the least common label is '0.0' with 17 occurrences. This represents 100.00% of the dataset.\n", "The distribution of the feature 'Gender' in this dataset is severely biased.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "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 }