{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "a4b99aa7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:30.454878Z", "iopub.status.busy": "2025-03-25T07:57:30.454657Z", "iopub.status.idle": "2025-03-25T07:57:30.620258Z", "shell.execute_reply": "2025-03-25T07:57:30.619817Z" } }, "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 = \"Mesothelioma\"\n", "cohort = \"GSE112154\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Mesothelioma\"\n", "in_cohort_dir = \"../../input/GEO/Mesothelioma/GSE112154\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Mesothelioma/GSE112154.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Mesothelioma/gene_data/GSE112154.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Mesothelioma/clinical_data/GSE112154.csv\"\n", "json_path = \"../../output/preprocess/Mesothelioma/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "c3f2fd9b", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "e08d4c64", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:30.621686Z", "iopub.status.busy": "2025-03-25T07:57:30.621548Z", "iopub.status.idle": "2025-03-25T07:57:30.789812Z", "shell.execute_reply": "2025-03-25T07:57:30.789208Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the directory:\n", "['GSE112154_family.soft.gz', 'GSE112154_series_matrix.txt.gz']\n", "SOFT file: ../../input/GEO/Mesothelioma/GSE112154/GSE112154_family.soft.gz\n", "Matrix file: ../../input/GEO/Mesothelioma/GSE112154/GSE112154_series_matrix.txt.gz\n", "Background Information:\n", "!Series_title\t\"Gene expression profiling of diffuse malignant peritoneal mesothelioma\"\n", "!Series_summary\t\"Diffuse malignant peritoneal mesothelioma (DMPM) is a rapidly lethal malignancy. The comprehension of the molecular features of DMPM is of utmost importance for the fruitful management of the disease, especially in patients who fail standard treatments and have a poor prognosis due to the lack of effective alternative therapeutic options.\"\n", "!Series_overall_design\t\"Gene expression profiling was carried out on a series of 45 frozen surgical specimens of diffuse malignant peritoneal mesothelioma (DMPM), 3 normal peritoneum samples and 2 patient-derived cell lines.\"\n", "Sample Characteristics Dictionary:\n", "{0: ['sample type: normal peritoneum', 'sample type: DMPM cell line', 'sample type: DMPM frozen tumor specimen']}\n" ] } ], "source": [ "# 1. Check what files are actually in the directory\n", "import os\n", "print(\"Files in the directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# 2. Find appropriate files with more flexible pattern matching\n", "soft_file = None\n", "matrix_file = None\n", "\n", "for file in files:\n", " file_path = os.path.join(in_cohort_dir, file)\n", " # Look for files that might contain SOFT or matrix data with various possible extensions\n", " if 'soft' in file.lower() or 'family' in file.lower() or file.endswith('.soft.gz'):\n", " soft_file = file_path\n", " if 'matrix' in file.lower() or file.endswith('.txt.gz') or file.endswith('.tsv.gz'):\n", " matrix_file = file_path\n", "\n", "if not soft_file:\n", " print(\"Warning: Could not find a SOFT file. Using the first .gz file as fallback.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if gz_files:\n", " soft_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "if not matrix_file:\n", " print(\"Warning: Could not find a matrix file. Using the second .gz file as fallback if available.\")\n", " gz_files = [f for f in files if f.endswith('.gz')]\n", " if len(gz_files) > 1 and soft_file != os.path.join(in_cohort_dir, gz_files[1]):\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[1])\n", " elif len(gz_files) == 1 and not soft_file:\n", " matrix_file = os.path.join(in_cohort_dir, gz_files[0])\n", "\n", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# 3. Read files if found\n", "if soft_file and matrix_file:\n", " # 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", " \n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " \n", " # Obtain the sample characteristics dictionary from the clinical dataframe\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " \n", " # 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", " except Exception as e:\n", " print(f\"Error processing files: {e}\")\n", " # Try swapping files if first attempt fails\n", " print(\"Trying to swap SOFT and matrix files...\")\n", " temp = soft_file\n", " soft_file = matrix_file\n", " matrix_file = temp\n", " try:\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)\n", " sample_characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Background Information:\")\n", " print(background_info)\n", " print(\"Sample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", " except Exception as e:\n", " print(f\"Still error after swapping: {e}\")\n", "else:\n", " print(\"Could not find necessary files for processing.\")\n" ] }, { "cell_type": "markdown", "id": "1ed19933", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "69e73ae0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:30.791547Z", "iopub.status.busy": "2025-03-25T07:57:30.791435Z", "iopub.status.idle": "2025-03-25T07:57:30.798613Z", "shell.execute_reply": "2025-03-25T07:57:30.798016Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Features Preview:\n", "{0: [0.0]}\n", "Clinical data saved to ../../output/preprocess/Mesothelioma/clinical_data/GSE112154.csv\n" ] } ], "source": [ "import pandas as pd\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any\n", "import numpy as np\n", "\n", "# This function will convert DMPM status value\n", "def convert_trait(value: str) -> int:\n", " if value is None:\n", " return None\n", " \n", " # Extract actual value (after colon)\n", " if ':' in value:\n", " value = value.split(':', 1)[1].strip()\n", " \n", " # Convert to binary\n", " if 'DMPM frozen tumor specimen' in value:\n", " return 1 # Mesothelioma positive\n", " elif 'normal peritoneum' in value:\n", " return 0 # Mesothelioma negative\n", " else:\n", " return None # DMPM cell lines are not considered in our analysis\n", "\n", "# No age data is provided in the sample characteristics\n", "convert_age = None\n", "\n", "# No gender data is provided in the sample characteristics\n", "convert_gender = None\n", "\n", "# Determine data availability\n", "trait_row = 0 # Data about DMPM status is available in row 0\n", "age_row = None # No age data is available\n", "gender_row = None # No gender data is available\n", "\n", "# Check if gene expression data is available\n", "# Based on the series title and overall design, this dataset contains gene expression profiles\n", "is_gene_available = True\n", "\n", "# Check if trait data is available\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info\n", "validate_and_save_cohort_info(\n", " is_final=False,\n", " cohort=cohort,\n", " info_path=json_path,\n", " is_gene_available=is_gene_available,\n", " is_trait_available=is_trait_available\n", ")\n", "\n", "# Only proceed with clinical feature extraction if trait data is available\n", "if trait_row is not None:\n", " # Get the clinical data from the previous step\n", " clinical_data = pd.DataFrame({0: ['sample type: normal peritoneum', 'sample type: DMPM cell line', 'sample type: DMPM frozen tumor specimen']})\n", " \n", " # Extract clinical features\n", " selected_clinical_df = geo_select_clinical_features(\n", " clinical_df=clinical_data,\n", " trait=trait,\n", " trait_row=trait_row,\n", " convert_trait=convert_trait,\n", " age_row=age_row,\n", " convert_age=convert_age,\n", " gender_row=gender_row,\n", " convert_gender=convert_gender\n", " )\n", " \n", " # Preview the extracted clinical features\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Clinical Features Preview:\")\n", " print(preview)\n", " \n", " # Save clinical data 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, index=False)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "7220715e", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "02b77caa", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:30.800383Z", "iopub.status.busy": "2025-03-25T07:57:30.800240Z", "iopub.status.idle": "2025-03-25T07:57:31.061058Z", "shell.execute_reply": "2025-03-25T07:57:31.060496Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\n", "No subseries references found in the first 1000 lines of the SOFT file.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene data extraction result:\n", "Number of rows: 47323\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. First get the path to the soft and matrix files\n", "soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# 2. Looking more carefully at the background information\n", "# This is a SuperSeries which doesn't contain direct gene expression data\n", "# Need to investigate the soft file to find the subseries\n", "print(\"This appears to be a SuperSeries. Looking at the SOFT file to find potential subseries:\")\n", "\n", "# Open the SOFT file to try to identify subseries\n", "with gzip.open(soft_file, 'rt') as f:\n", " subseries_lines = []\n", " for i, line in enumerate(f):\n", " if 'Series_relation' in line and 'SuperSeries of' in line:\n", " subseries_lines.append(line.strip())\n", " if i > 1000: # Limit search to first 1000 lines\n", " break\n", "\n", "# Display the subseries found\n", "if subseries_lines:\n", " print(\"Found potential subseries references:\")\n", " for line in subseries_lines:\n", " print(line)\n", "else:\n", " print(\"No subseries references found in the first 1000 lines of the SOFT file.\")\n", "\n", "# Despite trying to extract gene data, we expect it might fail because this is a SuperSeries\n", "try:\n", " gene_data = get_genetic_data(matrix_file)\n", " print(\"\\nGene data extraction result:\")\n", " print(\"Number of rows:\", len(gene_data))\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", " print(\"This confirms the dataset is a SuperSeries without direct gene expression data.\")\n" ] }, { "cell_type": "markdown", "id": "586093db", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "b402b75e", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:31.062835Z", "iopub.status.busy": "2025-03-25T07:57:31.062677Z", "iopub.status.idle": "2025-03-25T07:57:31.065274Z", "shell.execute_reply": "2025-03-25T07:57:31.064821Z" } }, "outputs": [], "source": [ "# The identifiers starting with \"ILMN_\" are Illumina microarray probe IDs, not gene symbols\n", "# These need to be mapped to human gene symbols for consistency with other datasets\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "ad78d89b", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "6e6eada6", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:31.066894Z", "iopub.status.busy": "2025-03-25T07:57:31.066789Z", "iopub.status.idle": "2025-03-25T07:57:36.135772Z", "shell.execute_reply": "2025-03-25T07:57:36.135123Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene annotation preview:\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" ] } ], "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": "668939da", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "2bc514e8", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:36.137737Z", "iopub.status.busy": "2025-03-25T07:57:36.137573Z", "iopub.status.idle": "2025-03-25T07:57:36.351362Z", "shell.execute_reply": "2025-03-25T07:57:36.350786Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping preview:\n", "{'ID': ['ILMN_1343048', 'ILMN_1343049', 'ILMN_1343050', 'ILMN_1343052', 'ILMN_1343059'], 'Gene': ['phage_lambda_genome', 'phage_lambda_genome', 'phage_lambda_genome:low', 'phage_lambda_genome:low', 'thrB']}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene expression data preview after mapping:\n", "Shape: (21464, 50)\n", "First 5 gene symbols: ['A1BG', 'A1CF', 'A26C3', 'A2BP1', 'A2LD1']\n" ] } ], "source": [ "# 1. Identify the relevant columns in the gene annotation dataframe\n", "# From the preview, we can see that 'ID' contains the probe identifiers (ILMN_*) which match the gene expression data\n", "# 'Symbol' column contains the gene symbols we want to map to\n", "\n", "# 2. Get gene mapping dataframe by extracting the relevant columns\n", "gene_mapping = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')\n", "\n", "# Show the first few rows of the mapping to verify\n", "print(\"Gene mapping preview:\")\n", "print(preview_df(gene_mapping))\n", "\n", "# 3. Apply gene mapping to convert probe-level measurements to gene expression\n", "gene_data = apply_gene_mapping(gene_data, gene_mapping)\n", "\n", "# Preview the resulting gene expression data\n", "print(\"\\nGene expression data preview after mapping:\")\n", "print(f\"Shape: {gene_data.shape}\")\n", "print(f\"First 5 gene symbols: {gene_data.index[:5].tolist()}\")\n" ] }, { "cell_type": "markdown", "id": "23af635d", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "18b4040c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:57:36.352888Z", "iopub.status.busy": "2025-03-25T07:57:36.352766Z", "iopub.status.idle": "2025-03-25T07:57:43.253404Z", "shell.execute_reply": "2025-03-25T07:57:43.252766Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shape of gene data after normalization: (20259, 50)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Saved normalized gene data to ../../output/preprocess/Mesothelioma/gene_data/GSE112154.csv\n", "Number of samples: 50\n", "Sample characteristics dictionary:\n", "{0: ['sample type: normal peritoneum', 'sample type: DMPM cell line', 'sample type: DMPM frozen tumor specimen']}\n", "Clinical data preview:\n", " Mesothelioma\n", "GSM3058890 1\n", "GSM3058891 1\n", "GSM3058892 1\n", "GSM3058893 1\n", "GSM3058894 1\n", "Saved clinical data to ../../output/preprocess/Mesothelioma/clinical_data/GSE112154.csv\n", "Shape of linked data: (50, 20260)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Shape of linked data after handling missing values: (50, 20260)\n", "Quartiles for 'Mesothelioma':\n", " 25%: 1.0\n", " 50% (Median): 1.0\n", " 75%: 1.0\n", "Min: 1\n", "Max: 1\n", "The distribution of the feature 'Mesothelioma' in this dataset is severely biased.\n", "\n", "Dataset validation failed due to biased trait variable. Final linked data not saved.\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "gene_data_normalized = normalize_gene_symbols_in_index(gene_data)\n", "print(f\"Shape of gene data after normalization: {gene_data_normalized.shape}\")\n", "os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", "gene_data_normalized.to_csv(out_gene_data_file)\n", "print(f\"Saved normalized gene data to {out_gene_data_file}\")\n", "\n", "# 2. Create clinical data from the sample IDs in the gene expression data\n", "# Since all samples are from tumor tissue, they all have mesothelioma (but this is not useful as a trait)\n", "sample_ids = gene_data.columns.tolist()\n", "print(f\"Number of samples: {len(sample_ids)}\")\n", "\n", "# Extract gender information from the original matrix file\n", "gender_data = {}\n", "try:\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " \n", " # Read the matrix file to extract sample characteristics\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \n", " # Display unique values in each row of clinical data\n", " characteristics_dict = get_unique_values_by_row(clinical_data)\n", " print(\"Sample characteristics dictionary:\")\n", " print(characteristics_dict)\n", " \n", " # Try to find gender information in the characteristics\n", " gender_row = None\n", " for idx, values in characteristics_dict.items():\n", " if any('sex:' in str(v).lower() for v in values):\n", " gender_row = idx\n", " break\n", " \n", " if gender_row is not None:\n", " # Extract gender data from the row\n", " for col in clinical_data.columns:\n", " if col != '!Sample_geo_accession':\n", " continue\n", " \n", " for idx, row in clinical_data.iterrows():\n", " if idx == gender_row:\n", " for i, sample_id in enumerate(clinical_data.iloc[0].values):\n", " if i > 0 and sample_id in sample_ids: # Skip the first column (header)\n", " gender_val = clinical_data.iloc[idx, i]\n", " if isinstance(gender_val, str) and 'sex:' in gender_val.lower():\n", " gender = 0 if 'f' in gender_val.lower() else 1 if 'm' in gender_val.lower() else None\n", " gender_data[sample_id] = gender\n", "except Exception as e:\n", " print(f\"Error extracting gender data: {e}\")\n", "\n", "# Create a clinical dataframe\n", "clinical_df = pd.DataFrame(index=sample_ids)\n", "clinical_df['Mesothelioma'] = 1 # All samples have mesothelioma\n", "\n", "# Add gender if available\n", "if gender_data:\n", " clinical_df['Gender'] = clinical_df.index.map(lambda x: gender_data.get(x))\n", " print(f\"Added gender data for {sum(pd.notna(clinical_df['Gender']))} samples\")\n", "\n", "print(\"Clinical data preview:\")\n", "print(clinical_df.head())\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\"Saved clinical data to {out_clinical_data_file}\")\n", "\n", "# 3. Link clinical and genetic data (transpose gene expression data to have samples as rows)\n", "linked_data = pd.concat([clinical_df, gene_data_normalized.T], axis=1)\n", "print(f\"Shape of linked data: {linked_data.shape}\")\n", "\n", "# 4. Handle missing values in the linked data\n", "linked_data_cleaned = handle_missing_values(linked_data, 'Mesothelioma')\n", "print(f\"Shape of linked data after handling missing values: {linked_data_cleaned.shape}\")\n", "\n", "# 5. Check if the trait is biased (it will be since all samples are mesothelioma)\n", "is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data_cleaned, 'Mesothelioma')\n", "\n", "# 6. Validate the dataset and save 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, # We do have trait data, it's just that all values are the same\n", " is_biased=is_trait_biased, # This will be True since all samples have the same trait value\n", " df=unbiased_linked_data,\n", " note=\"Dataset contains gene expression data from mesothelioma patients only (no controls), making trait biased.\"\n", ")\n", "\n", "# 7. Save the linked data if it's usable\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\"Saved processed linked data to {out_data_file}\")\n", "else:\n", " print(\"Dataset validation failed due to biased trait variable. Final 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 }