{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "83af420c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:03:11.436632Z", "iopub.status.busy": "2025-03-25T08:03:11.436153Z", "iopub.status.idle": "2025-03-25T08:03:11.604172Z", "shell.execute_reply": "2025-03-25T08:03:11.603683Z" } }, "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 = \"Endometriosis\"\n", "cohort = \"GSE165004\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Endometriosis\"\n", "in_cohort_dir = \"../../input/GEO/Endometriosis/GSE165004\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Endometriosis/GSE165004.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Endometriosis/gene_data/GSE165004.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Endometriosis/clinical_data/GSE165004.csv\"\n", "json_path = \"../../output/preprocess/Endometriosis/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "5470cb1d", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "ec72f808", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:03:11.605961Z", "iopub.status.busy": "2025-03-25T08:03:11.605773Z", "iopub.status.idle": "2025-03-25T08:03:11.896750Z", "shell.execute_reply": "2025-03-25T08:03:11.896162Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Endometrial Tissue RNA expression in recurrent pregnancy losses and unexplained infertility vs. conrol\"\n", "!Series_summary\t\"Recent studies are directed to decode the genetic signature of endometrial receptivity for better outcomes in assisted reproductive technologies. In this study, we aimed to understand the transcriptomic profile of midsecretory phase endometria of patients with recurrent pregnancy losses (RPL) and unexplained infertility (UI) by comparing with the endometria of healthy fertile women (Controls).\"\n", "!Series_summary\t\"In this prospective cohort study, we took endometrial samples from 24 patients with RPL, 24 patients with UI and 24 Controls at day 19-21 of the menstrual cycle. By performing genomic analysis, we assessed for differentially expressed genes (DEGs) and pathway analysis.\"\n", "!Series_overall_design\t\"All patients involved in this prospective cohort study were recruited from Istanbul University School of Medicine between August 2014 and August 2015. Three cohorts (fertile controls, patients with RPL and UI) were studied and 24 patients were included in each cohort. None of the patients has received a prior infertility treatment and were not under a current treatment. The first cohort comprised fertile control patients who presented to our gynecology department for well woman examinations. The inclusion criteria were regularly cycling women aged under 35 years with at least one live birth, no history of infertility/treatment, no previous miscarriages and no associated gynecologic (endometriosis, fibroids, active or history of pelvic inflammatory disease) or other medical comorbidities (hyperprolactinemia, thyroid disease etc). The remaining cohorts constituted patients who presented to our in vitro fertilization (IVF) unit. The second cohort included patients with RPL with no history of successful pregnancies. The inclusion criteria for this group were regularly cycling women aged under 35 years with at least two consecutive pregnancy losses of 20 weeks or less, normal follicle-stimulating hormone (FSH), luteinizing hormone (LH), estradiol (E2), prolactin (PRL), and thyroid-stimulating hormone (TSH) levels at day 2-3, normal uterine cavity shape and size, and bilateral tubal patency observed on hysterosalpingogram, no mutations detected in Factor V (Leiden) and prothrombin gene analysis, normal antithrombin III, protein C and S activity, negative results for lupus anticoagulant evaluation, cardiolipin antibody (IgM and IgG), and beta2-glycoprotein antibody (IgM and IgG) and normal karyotype. Their partners have normal spermiogram results and normal karyotype. The third cohort was formed by women with UI at least of 18 months of duration. The inclusion criteria for this group were regularly cycling women aged under 35 years with normal FSH, LH, E2, PRL, and TSH levels at day 2-3, normal uterine cavity shape and size, and bilateral tubal patency observed on a hysterosalpingogram. Their partners have normal spermiogram results.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['subject status/group: Control', 'subject status/group: patient with RPL', 'subject status/group: patient with UIF'], 1: ['tissue: Endometrial tissue']}\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": "b311c241", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "6537167d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:03:11.898611Z", "iopub.status.busy": "2025-03-25T08:03:11.898450Z", "iopub.status.idle": "2025-03-25T08:03:11.908261Z", "shell.execute_reply": "2025-03-25T08:03:11.907794Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Data Preview:\n", "{'GSM5024320': [0.0], 'GSM5024321': [0.0], 'GSM5024322': [0.0], 'GSM5024323': [0.0], 'GSM5024324': [0.0], 'GSM5024325': [0.0], 'GSM5024326': [0.0], 'GSM5024327': [0.0], 'GSM5024328': [0.0], 'GSM5024329': [0.0], 'GSM5024330': [0.0], 'GSM5024331': [0.0], 'GSM5024332': [0.0], 'GSM5024333': [0.0], 'GSM5024334': [0.0], 'GSM5024335': [0.0], 'GSM5024336': [0.0], 'GSM5024337': [0.0], 'GSM5024338': [0.0], 'GSM5024339': [0.0], 'GSM5024340': [0.0], 'GSM5024341': [0.0], 'GSM5024342': [0.0], 'GSM5024343': [0.0], 'GSM5024344': [1.0], 'GSM5024345': [1.0], 'GSM5024346': [1.0], 'GSM5024347': [1.0], 'GSM5024348': [1.0], 'GSM5024349': [1.0], 'GSM5024350': [1.0], 'GSM5024351': [1.0], 'GSM5024352': [1.0], 'GSM5024353': [1.0], 'GSM5024354': [1.0], 'GSM5024355': [1.0], 'GSM5024356': [1.0], 'GSM5024357': [1.0], 'GSM5024358': [1.0], 'GSM5024359': [1.0], 'GSM5024360': [1.0], 'GSM5024361': [1.0], 'GSM5024362': [1.0], 'GSM5024363': [1.0], 'GSM5024364': [1.0], 'GSM5024365': [1.0], 'GSM5024366': [1.0], 'GSM5024367': [1.0], 'GSM5024368': [1.0], 'GSM5024369': [1.0], 'GSM5024370': [1.0], 'GSM5024371': [1.0], 'GSM5024372': [1.0], 'GSM5024373': [1.0], 'GSM5024374': [1.0], 'GSM5024375': [1.0], 'GSM5024376': [1.0], 'GSM5024377': [1.0], 'GSM5024378': [1.0], 'GSM5024379': [1.0], 'GSM5024380': [1.0], 'GSM5024381': [1.0], 'GSM5024382': [1.0], 'GSM5024383': [1.0], 'GSM5024384': [1.0], 'GSM5024385': [1.0], 'GSM5024386': [1.0], 'GSM5024387': [1.0], 'GSM5024388': [1.0], 'GSM5024389': [1.0], 'GSM5024390': [1.0], 'GSM5024391': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Endometriosis/clinical_data/GSE165004.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the Series title and summary, this dataset appears to contain RNA expression data\n", "# from endometrial tissue, which indicates gene expression data should be available\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 Data Availability\n", "# Checking the sample characteristics dictionary for trait, age, and gender information\n", "# For trait (endometriosis), we can use row 0 which contains \"subject status/group\"\n", "# Age and gender information are not explicitly available in the sample characteristics\n", "trait_row = 0\n", "age_row = None\n", "gender_row = None\n", "\n", "# 2.2 Data Type Conversion Functions\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert trait values to binary (0 for control, 1 for disease).\n", " In this dataset, endometriosis status is inferred from the study group.\n", " \"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract value after colon if present\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert based on subject status\n", " if 'Control' in value:\n", " return 0 # Control group\n", " elif 'patient with RPL' in value or 'patient with UIF' in value:\n", " return 1 # Patient with condition (RPL or UIF)\n", " return None\n", "\n", "def convert_age(value):\n", " \"\"\"\n", " Convert age values to continuous.\n", " Not applicable for this dataset as age information is not available.\n", " \"\"\"\n", " return None\n", "\n", "def convert_gender(value):\n", " \"\"\"\n", " Convert gender values to binary (0 for female, 1 for male).\n", " Not applicable for this dataset as gender information is not available.\n", " \"\"\"\n", " return None\n", "\n", "# 3. Save Metadata\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Save initial filtering results\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", "# Only do this if trait data is available\n", "if trait_row is not None:\n", " # Extract clinical features\n", " 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 clinical dataframe\n", " preview = preview_df(clinical_df)\n", " print(\"Clinical Data Preview:\")\n", " print(preview)\n", " \n", " # Save the clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_df.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "20553e77", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "5dacd991", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:03:11.909862Z", "iopub.status.busy": "2025-03-25T08:03:11.909749Z", "iopub.status.idle": "2025-03-25T08:03:12.386916Z", "shell.execute_reply": "2025-03-25T08:03:12.386282Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Found data marker at line 61\n", "Header line: \"ID_REF\"\t\"GSM5024320\"\t\"GSM5024321\"\t\"GSM5024322\"\t\"GSM5024323\"\t\"GSM5024324\"\t\"GSM5024325\"\t\"GSM5024326\"\t\"GSM5024327\"\t\"GSM5024328\"\t\"GSM5024329\"\t\"GSM5024330\"\t\"GSM5024331\"\t\"GSM5024332\"\t\"GSM5024333\"\t\"GSM5024334\"\t\"GSM5024335\"\t\"GSM5024336\"\t\"GSM5024337\"\t\"GSM5024338\"\t\"GSM5024339\"\t\"GSM5024340\"\t\"GSM5024341\"\t\"GSM5024342\"\t\"GSM5024343\"\t\"GSM5024344\"\t\"GSM5024345\"\t\"GSM5024346\"\t\"GSM5024347\"\t\"GSM5024348\"\t\"GSM5024349\"\t\"GSM5024350\"\t\"GSM5024351\"\t\"GSM5024352\"\t\"GSM5024353\"\t\"GSM5024354\"\t\"GSM5024355\"\t\"GSM5024356\"\t\"GSM5024357\"\t\"GSM5024358\"\t\"GSM5024359\"\t\"GSM5024360\"\t\"GSM5024361\"\t\"GSM5024362\"\t\"GSM5024363\"\t\"GSM5024364\"\t\"GSM5024365\"\t\"GSM5024366\"\t\"GSM5024367\"\t\"GSM5024368\"\t\"GSM5024369\"\t\"GSM5024370\"\t\"GSM5024371\"\t\"GSM5024372\"\t\"GSM5024373\"\t\"GSM5024374\"\t\"GSM5024375\"\t\"GSM5024376\"\t\"GSM5024377\"\t\"GSM5024378\"\t\"GSM5024379\"\t\"GSM5024380\"\t\"GSM5024381\"\t\"GSM5024382\"\t\"GSM5024383\"\t\"GSM5024384\"\t\"GSM5024385\"\t\"GSM5024386\"\t\"GSM5024387\"\t\"GSM5024388\"\t\"GSM5024389\"\t\"GSM5024390\"\t\"GSM5024391\"\n", "First data line: 1\t16.04322867\t15.40347287\t15.4669395\t14.72857244\t15.80882129\t15.53067649\t15.15167927\t14.55337277\t16.14055719\t15.40623646\t15.25467351\t15.17349668\t16.19113465\t15.47562577\t15.66208174\t14.70747347\t16.10486139\t15.37035048\t15.42876325\t15.42377233\t16.26538617\t15.76140574\t15.85484054\t15.59550261\t16.17910312\t15.50683019\t15.66544664\t15.54171558\t16.33857092\t15.73089139\t15.1576132\t15.55087271\t16.66945828\t15.9297943\t15.49696781\t15.37587985\t15.9083873\t15.19697888\t15.74939633\t14.44660649\t16.0086273\t15.56902617\t15.44531854\t15.89476832\t16.0964873\t15.52716969\t15.15616768\t15.62068029\t16.10239643\t15.90090485\t15.45353263\t15.57225537\t16.05242939\t15.991455\t15.83430272\t15.77449902\t15.78989786\t15.76344479\t15.44852936\t15.51384994\t15.65476078\t15.44531854\t15.28702702\t15.20405136\t15.73616945\t15.73256997\t15.53243337\t15.70189609\t15.20122584\t15.6582036\t15.31632188\t15.79204539\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',\n", " '14', '15', '16', '17', '18', '19', '20'],\n", " dtype='object', name='ID')\n" ] } ], "source": [ "# 1. Get the file paths for the SOFT file and matrix file\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. First, let's examine the structure of the matrix file to understand its format\n", "import gzip\n", "\n", "# Peek at the first few lines of the file to understand its structure\n", "with gzip.open(matrix_file, 'rt') as file:\n", " # Read first 100 lines to find the header structure\n", " for i, line in enumerate(file):\n", " if '!series_matrix_table_begin' in line:\n", " print(f\"Found data marker at line {i}\")\n", " # Read the next line which should be the header\n", " header_line = next(file)\n", " print(f\"Header line: {header_line.strip()}\")\n", " # And the first data line\n", " first_data_line = next(file)\n", " print(f\"First data line: {first_data_line.strip()}\")\n", " break\n", " if i > 100: # Limit search to first 100 lines\n", " print(\"Matrix table marker not found in first 100 lines\")\n", " break\n", "\n", "# 3. Now try to get the genetic data with better error handling\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(gene_data.index[:20])\n", "except KeyError as e:\n", " print(f\"KeyError: {e}\")\n", " \n", " # Alternative approach: manually extract the data\n", " print(\"\\nTrying alternative approach to read the gene data:\")\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Find the start of the data\n", " for line in file:\n", " if '!series_matrix_table_begin' in line:\n", " break\n", " \n", " # Read the headers and data\n", " import pandas as pd\n", " df = pd.read_csv(file, sep='\\t', index_col=0)\n", " print(f\"Column names: {df.columns[:5]}\")\n", " print(f\"First 20 row IDs: {df.index[:20]}\")\n", " gene_data = df\n" ] }, { "cell_type": "markdown", "id": "8810fa5e", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "df19150b", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:03:12.388631Z", "iopub.status.busy": "2025-03-25T08:03:12.388500Z", "iopub.status.idle": "2025-03-25T08:03:12.390828Z", "shell.execute_reply": "2025-03-25T08:03:12.390393Z" } }, "outputs": [], "source": [ "# Based on the gene identifiers shown, I can see the expression data uses numeric probe IDs (1, 2, 3, etc.) \n", "# rather than standard human gene symbols like BRCA1, TP53, etc.\n", "# These appear to be microarray probe IDs that need to be mapped to actual gene symbols.\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "288cd6c5", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "0bfa989c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:03:12.392853Z", "iopub.status.busy": "2025-03-25T08:03:12.392512Z", "iopub.status.idle": "2025-03-25T08:03:19.105566Z", "shell.execute_reply": "2025-03-25T08:03:19.104906Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\n", "{'ID': ['1', '2', '3', '4', '5'], 'COL': ['192', '192', '192', '192', '192'], 'ROW': [328.0, 326.0, 324.0, 322.0, 320.0], 'NAME': ['GE_BrightCorner', 'DarkCorner', 'DarkCorner', 'A_23_P117082', 'A_33_P3246448'], 'SPOT_ID': ['CONTROL', 'CONTROL', 'CONTROL', 'A_23_P117082', 'A_33_P3246448'], 'CONTROL_TYPE': ['pos', 'pos', 'pos', 'FALSE', 'FALSE'], 'REFSEQ': [nan, nan, nan, 'NM_015987', 'NM_080671'], 'GB_ACC': [nan, nan, nan, 'NM_015987', 'NM_080671'], 'LOCUSLINK_ID': [nan, nan, nan, 50865.0, 23704.0], 'GENE_SYMBOL': [nan, nan, nan, 'HEBP1', 'KCNE4'], 'GENE_NAME': [nan, nan, nan, 'heme binding protein 1', 'potassium voltage-gated channel, Isk-related family, member 4'], 'UNIGENE_ID': [nan, nan, nan, 'Hs.642618', 'Hs.348522'], 'ENSEMBL_ID': [nan, nan, nan, 'ENST00000014930', 'ENST00000281830'], 'ACCESSION_STRING': [nan, nan, nan, 'ref|NM_015987|ens|ENST00000014930|gb|AF117615|gb|BC016277', 'ref|NM_080671|ens|ENST00000281830|tc|THC2655788'], 'CHROMOSOMAL_LOCATION': [nan, nan, nan, 'chr12:13127906-13127847', 'chr2:223920197-223920256'], 'CYTOBAND': [nan, nan, nan, 'hs|12p13.1', 'hs|2q36.1'], 'DESCRIPTION': [nan, nan, nan, 'Homo sapiens heme binding protein 1 (HEBP1), mRNA [NM_015987]', 'Homo sapiens potassium voltage-gated channel, Isk-related family, member 4 (KCNE4), mRNA [NM_080671]'], 'GO_ID': [nan, nan, nan, 'GO:0005488(binding)|GO:0005576(extracellular region)|GO:0005737(cytoplasm)|GO:0005739(mitochondrion)|GO:0005829(cytosol)|GO:0007623(circadian rhythm)|GO:0020037(heme binding)', 'GO:0005244(voltage-gated ion channel activity)|GO:0005249(voltage-gated potassium channel activity)|GO:0006811(ion transport)|GO:0006813(potassium ion transport)|GO:0016020(membrane)|GO:0016021(integral to membrane)|GO:0016324(apical plasma membrane)'], 'SEQUENCE': [nan, nan, nan, 'AAGGGGGAAAATGTGATTTGTGCCTGATCTTTCATCTGTGATTCTTATAAGAGCTTTGTC', 'GCAAGTCTCTCTGCACCTATTAAAAAGTGATGTATATACTTCCTTCTTATTCTGTTGAGT']}\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. Use the 'preview_df' function from the library to preview the data and print out the results.\n", "print(\"Gene annotation preview:\")\n", "print(preview_df(gene_annotation))\n" ] }, { "cell_type": "markdown", "id": "a410a020", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "90b06d5f", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:03:19.107478Z", "iopub.status.busy": "2025-03-25T08:03:19.107322Z", "iopub.status.idle": "2025-03-25T08:03:20.430788Z", "shell.execute_reply": "2025-03-25T08:03:20.430152Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data after mapping:\n", "Shape: (20353, 72)\n", "First few genes: ['A1BG', 'A1BG-AS1', 'A1CF', 'A2LD1', 'A2M']\n", "First few samples: ['GSM5024320', 'GSM5024321', 'GSM5024322', 'GSM5024323', 'GSM5024324']\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Endometriosis/gene_data/GSE165004.csv\n" ] } ], "source": [ "# Identify the appropriate columns for mapping\n", "# From the preview, I can see:\n", "# - 'ID' column contains numeric identifiers that match the gene expression data index\n", "# - 'GENE_SYMBOL' column contains the human gene symbols we need\n", "\n", "# 1. Get the gene mapping dataframe\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')\n", "\n", "# 2. Apply the gene mapping to convert probe-level measurements to gene expression data\n", "# Using the library function to handle the many-to-many mapping logic\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# 3. Preview the result to verify\n", "print(\"Gene expression data after mapping:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(f\"First few genes: {list(gene_data.index[:5])}\")\n", "print(f\"First few samples: {list(gene_data.columns[:5])}\")\n", "\n", "# Save the gene expression data\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data.to_csv(out_gene_data_file)\n", "print(f\"Gene expression data saved to {out_gene_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "42ebed83", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "72e03311", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T08:03:20.432594Z", "iopub.status.busy": "2025-03-25T08:03:20.432445Z", "iopub.status.idle": "2025-03-25T08:03:32.280747Z", "shell.execute_reply": "2025-03-25T08:03:32.280108Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Endometriosis/gene_data/GSE165004.csv\n", "Clinical data saved to ../../output/preprocess/Endometriosis/clinical_data/GSE165004.csv\n", "Linked data shape: (72, 19848)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "For the feature 'Endometriosis', the least common label is '0.0' with 24 occurrences. This represents 33.33% of the dataset.\n", "The distribution of the feature 'Endometriosis' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Endometriosis/GSE165004.csv\n" ] } ], "source": [ "# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.\n", "normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "normalized_gene_data.to_csv(out_gene_data_file)\n", "print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "\n", "# Create clinical features directly from clinical_data using the conversion functions defined earlier\n", "clinical_features_df = geo_select_clinical_features(\n", " 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 data\n", "os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", "clinical_features_df.to_csv(out_clinical_data_file)\n", "print(f\"Clinical data saved to {out_clinical_data_file}\")\n", "\n", "# Now link the clinical and genetic data\n", "linked_data = geo_link_clinical_genetic_data(clinical_features_df, normalized_gene_data)\n", "print(\"Linked data shape:\", linked_data.shape)\n", "\n", "# Handle missing values in the linked data\n", "linked_data = handle_missing_values(linked_data, trait)\n", "\n", "# 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)\n", "\n", "# 5. Conduct quality check and save the cohort information.\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_trait_biased, \n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression from monocytes of rheumatoid arthritis patients, with osteoporosis status included in comorbidity information.\"\n", ")\n", "\n", "# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.\n", "if is_usable:\n", " os.makedirs(os.path.dirname(out_data_file), exist_ok=True)\n", " unbiased_linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", "else:\n", " print(\"Data was determined to be unusable and was 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 }