{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "f90b4d02", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:01:54.727986Z", "iopub.status.busy": "2025-03-25T07:01:54.727606Z", "iopub.status.idle": "2025-03-25T07:01:54.893661Z", "shell.execute_reply": "2025-03-25T07:01:54.893283Z" } }, "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 = \"Breast_Cancer\"\n", "cohort = \"GSE234017\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/Breast_Cancer\"\n", "in_cohort_dir = \"../../input/GEO/Breast_Cancer/GSE234017\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/Breast_Cancer/GSE234017.csv\"\n", "out_gene_data_file = \"../../output/preprocess/Breast_Cancer/gene_data/GSE234017.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/Breast_Cancer/clinical_data/GSE234017.csv\"\n", "json_path = \"../../output/preprocess/Breast_Cancer/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "893aa2be", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "15ce0386", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:01:54.895112Z", "iopub.status.busy": "2025-03-25T07:01:54.894960Z", "iopub.status.idle": "2025-03-25T07:01:55.074264Z", "shell.execute_reply": "2025-03-25T07:01:55.073929Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Background Information:\n", "!Series_title\t\"Spatial Transcriptomics Suggests That Alterations 4 Occur in the Preneoplastic Breast Microenvironment of 5 Q2 BRCA1/2 Mutation Carriers\"\n", "!Series_summary\t\"Breast cancer is the most common cancer in females, affecting one in every eight women and accounting for the majority of cancer-related deaths in women worldwide. Germline mutations in the BRCA1 and BRCA2 genes are significant risk factors for specific subtypes of breast cancer. BRCA1 mutations are associated with basal-like breast cancers, whereas BRCA2 mutations are associated with luminal-like disease. Defects in mammary epithelial cell differentiation have been previously recognized in germline BRCA1/2 mutation carriers even before cancer incidence. However, the underlying mechanism is largely unknown. Here, we employ spatial transcriptomics to investigate defects in mammary epithelial cell differentiation accompanied by distinct microenvironmental alterations in preneoplastic breast tissues from BRCA1/2 mutation carriers and normal breast tissues from non-carrier controls. We uncovered spatially defined receptor-ligand interactions in these tissues for the investigation of autocrine and paracrine signaling. We discovered that β1-integrin-mediated autocrine signaling in BRCA2-deficient mammary epithelial cells may differ from BRCA1-deficient mammary epithelial cells. In addition, we found that the epithelial-to-stromal paracrine signaling in the breast tissues of BRCA1/2 mutation carriers is greater than in control tissues. More integrin-ligand pairs were differentially correlated in BRCA1/2-mutant breast tissues than non-carrier breast tissues with more integrin receptor-expressing stromal cells. Implications: These results suggest alterations in the communication between mammary epithelial cells and the microenvironment in BRCA1 and BRCA2 mutation carriers, laying the foundation for designing innovative breast cancer chemo-prevention strategies for high-risk patients.\"\n", "!Series_overall_design\t\"12 patients, 3 genotypes, 4 patients per genotype, 11-15 ROI per patient\"\n", "Sample Characteristics Dictionary:\n", "{0: ['patient: WT.4', 'patient: BRCA2.4', 'patient: BRCA1.4', 'patient: BRCA2.1', 'patient: WT.1', 'patient: BRCA1.1', 'patient: BRCA2.2', 'patient: BRCA1.2', 'patient: WT.2', 'patient: WT.3', 'patient: BRCA2.3', 'patient: BRCA1.3'], 1: ['tissue segment: epithelium', 'tissue segment: stroma'], 2: ['genotype: WT', 'genotype: BRCA2', 'genotype: BRCA1'], 3: ['scan batch: S1', 'scan batch: S5', 'scan batch: S6', 'scan batch: S9', 'scan batch: S13']}\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": "c280792b", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "8cc96551", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:01:55.075568Z", "iopub.status.busy": "2025-03-25T07:01:55.075455Z", "iopub.status.idle": "2025-03-25T07:01:55.097043Z", "shell.execute_reply": "2025-03-25T07:01:55.096729Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Clinical Features Preview:\n", "{'WT.4': [0.0], 'BRCA2.4': [1.0], 'BRCA1.4': [1.0], 'BRCA2.1': [1.0], 'WT.1': [0.0], 'BRCA1.1': [1.0], 'BRCA2.2': [1.0], 'BRCA1.2': [1.0], 'WT.2': [0.0], 'WT.3': [0.0], 'BRCA2.3': [1.0], 'BRCA1.3': [1.0]}\n", "Clinical data saved to ../../output/preprocess/Breast_Cancer/clinical_data/GSE234017.csv\n" ] } ], "source": [ "# 1. Gene Expression Data Availability\n", "# Based on the context, this is a spatial transcriptomics study examining BRCA1/BRCA2 carriers,\n", "# which includes gene expression data\n", "is_gene_available = True\n", "\n", "# 2. Variable Availability and Data Type Conversion\n", "# 2.1 & 2.2 Data Availability and Type Conversion\n", "\n", "# For trait (Breast Cancer - considering BRCA mutation status)\n", "# We can use row 2 which contains 'genotype: WT', 'genotype: BRCA1', 'genotype: BRCA2'\n", "trait_row = 2\n", "\n", "def convert_trait(value):\n", " \"\"\"\n", " Convert genotype values to binary: \n", " - WT (wild type/control) = 0\n", " - BRCA1/BRCA2 mutation = 1\n", " \"\"\"\n", " if isinstance(value, str) and ':' in value:\n", " genotype = value.split(':', 1)[1].strip()\n", " if 'WT' in genotype:\n", " return 0\n", " elif 'BRCA1' in genotype or 'BRCA2' in genotype:\n", " return 1\n", " return None\n", "\n", "# For age - Age information is not available in the sample characteristics\n", "age_row = None\n", "\n", "def convert_age(value):\n", " \"\"\"Placeholder function since age data is not available\"\"\"\n", " return None\n", "\n", "# For gender - Gender information is not explicitly provided, but this is breast tissue,\n", "# so we can infer it's from female patients\n", "# However, since it would be a constant value across all samples, \n", "# we'll consider it as not available for analytical purposes\n", "gender_row = None\n", "\n", "def convert_gender(value):\n", " \"\"\"Placeholder function since gender data is not available\"\"\"\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\n", "if trait_row is not None:\n", " # Create a DataFrame from the sample characteristics dictionary\n", " # The dictionary contains keys as row indices and values as lists of characteristics\n", " sample_chars_dict = {\n", " 0: ['patient: WT.4', 'patient: BRCA2.4', 'patient: BRCA1.4', 'patient: BRCA2.1', 'patient: WT.1', 'patient: BRCA1.1', 'patient: BRCA2.2', 'patient: BRCA1.2', 'patient: WT.2', 'patient: WT.3', 'patient: BRCA2.3', 'patient: BRCA1.3'],\n", " 1: ['tissue segment: epithelium', 'tissue segment: stroma'],\n", " 2: ['genotype: WT', 'genotype: BRCA2', 'genotype: BRCA1'],\n", " 3: ['scan batch: S1', 'scan batch: S5', 'scan batch: S6', 'scan batch: S9', 'scan batch: S13']\n", " }\n", " \n", " # Create a DataFrame with appropriate samples as columns\n", " # We'll use the first row (patient IDs) to create sample names\n", " samples = []\n", " for patient in sample_chars_dict[0]:\n", " patient_id = patient.split(': ')[1].strip()\n", " samples.append(patient_id)\n", " \n", " # Create a DataFrame with characteristics as rows and samples as columns\n", " clinical_data = pd.DataFrame(index=range(len(sample_chars_dict)), columns=samples)\n", " \n", " # Fill in the DataFrame with characteristic values\n", " for row_idx, chars in sample_chars_dict.items():\n", " for char in chars:\n", " if ': ' in char:\n", " value, label = char.split(': ', 1)\n", " # For each sample, if its name contains the label, assign this characteristic\n", " for sample in samples:\n", " if label in sample or sample in label:\n", " clinical_data.iloc[row_idx, clinical_data.columns.get_loc(sample)] = char\n", " \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 features\n", " preview = preview_df(clinical_features)\n", " print(\"Clinical Features Preview:\")\n", " print(preview)\n", " \n", " # Save the clinical features to a CSV file\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n" ] }, { "cell_type": "markdown", "id": "07a62b64", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "09d8b3c9", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:01:55.098257Z", "iopub.status.busy": "2025-03-25T07:01:55.098141Z", "iopub.status.idle": "2025-03-25T07:01:55.270055Z", "shell.execute_reply": "2025-03-25T07:01:55.269678Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SOFT file: ../../input/GEO/Breast_Cancer/GSE234017/GSE234017_family.soft.gz\n", "Matrix file: ../../input/GEO/Breast_Cancer/GSE234017/GSE234017_series_matrix.txt.gz\n", "Found the matrix table marker at line 70\n", "Gene data shape: (11799, 142)\n", "First 20 gene/probe identifiers:\n", "['nan', 'RTS0020877', 'RTS0020879', 'RTS0020880', 'RTS0020881', 'RTS0020882', 'RTS0020883', 'RTS0020885', 'RTS0020886', 'RTS0020888', 'RTS0020892', 'RTS0020894', 'RTS0020895', 'RTS0020898', 'RTS0020904', 'RTS0020906', 'RTS0020907', 'RTS0020915', 'RTS0020917', 'RTS0020920']\n" ] } ], "source": [ "# 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", "print(f\"SOFT file: {soft_file}\")\n", "print(f\"Matrix file: {matrix_file}\")\n", "\n", "# Set gene availability flag\n", "is_gene_available = True # Initially assume gene data is available\n", "\n", "# First check if the matrix file contains the expected marker\n", "found_marker = False\n", "marker_row = None\n", "try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " for i, line in enumerate(file):\n", " if \"!series_matrix_table_begin\" in line:\n", " found_marker = True\n", " marker_row = i\n", " print(f\"Found the matrix table marker at line {i}\")\n", " break\n", " \n", " if not found_marker:\n", " print(\"Warning: Could not find '!series_matrix_table_begin' marker in the file.\")\n", " is_gene_available = False\n", " \n", " # If marker was found, try to extract gene data\n", " if is_gene_available:\n", " try:\n", " # Try using the library function\n", " gene_data = get_genetic_data(matrix_file)\n", " \n", " if gene_data.shape[0] == 0:\n", " print(\"Warning: Extracted gene data has 0 rows.\")\n", " is_gene_available = False\n", " else:\n", " print(f\"Gene data shape: {gene_data.shape}\")\n", " # Print the first 20 gene/probe identifiers\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20].tolist())\n", " except Exception as e:\n", " print(f\"Error extracting gene data with get_genetic_data(): {e}\")\n", " is_gene_available = False\n", " \n", " # If gene data extraction failed, examine file content to diagnose\n", " if not is_gene_available:\n", " print(\"Examining file content to diagnose the issue:\")\n", " try:\n", " with gzip.open(matrix_file, 'rt') as file:\n", " # Print lines around the marker if found\n", " if marker_row is not None:\n", " for i, line in enumerate(file):\n", " if i >= marker_row - 2 and i <= marker_row + 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " if i > marker_row + 10:\n", " break\n", " else:\n", " # If marker not found, print first 10 lines\n", " for i, line in enumerate(file):\n", " if i < 10:\n", " print(f\"Line {i}: {line.strip()[:100]}...\")\n", " else:\n", " break\n", " except Exception as e2:\n", " print(f\"Error examining file: {e2}\")\n", " \n", "except Exception as e:\n", " print(f\"Error processing file: {e}\")\n", " is_gene_available = False\n", "\n", "# Update validation information if gene data extraction failed\n", "if not is_gene_available:\n", " print(\"Gene expression data could not be successfully extracted from this dataset.\")\n", " # Update the validation record since gene data isn't available\n", " is_trait_available = False # We already determined trait data isn't available in step 2\n", " validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path,\n", " is_gene_available=is_gene_available, is_trait_available=is_trait_available)\n" ] }, { "cell_type": "markdown", "id": "1b3e535b", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "48663208", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:01:55.271451Z", "iopub.status.busy": "2025-03-25T07:01:55.271323Z", "iopub.status.idle": "2025-03-25T07:01:55.273304Z", "shell.execute_reply": "2025-03-25T07:01:55.272981Z" } }, "outputs": [], "source": [ "# Based on the gene identifiers shown, these are not standard human gene symbols\n", "# They appear to be probe IDs or custom identifiers (starting with \"RTS\") that would need \n", "# to be mapped to standard gene symbols for biological interpretation\n", "\n", "requires_gene_mapping = True\n" ] }, { "cell_type": "markdown", "id": "564d7fa4", "metadata": {}, "source": [ "### Step 5: Gene Annotation" ] }, { "cell_type": "code", "execution_count": 6, "id": "e2c206b7", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:01:55.274567Z", "iopub.status.busy": "2025-03-25T07:01:55.274453Z", "iopub.status.idle": "2025-03-25T07:01:56.676193Z", "shell.execute_reply": "2025-03-25T07:01:56.675760Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "Gene annotation preview:\n", "Columns in gene annotation: ['ID', 'ORF']\n", "{'ID': ['RTS0050057', 'RTS0020877', 'RTS0032443'], 'ORF': ['A1BG', 'A2M', 'A4GALT']}\n", "\n", "Examining ID and ORF columns format (first 3 rows):\n", "Row 0: ID=RTS0050057, ORF=A1BG\n", "Row 1: ID=RTS0020877, ORF=A2M\n", "Row 2: ID=RTS0032443, ORF=A4GALT\n", "\n", "ORF column completeness: 1687399/1687399 rows (100.00%)\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=3))\n", "\n", "# Looking at the output, it appears the gene symbols are in the 'ORF' column\n", "# and the probe IDs are in the 'ID' column\n", "print(\"\\nExamining ID and ORF columns format (first 3 rows):\")\n", "if 'ID' in gene_annotation.columns and 'ORF' in gene_annotation.columns:\n", " for i in range(min(3, len(gene_annotation))):\n", " print(f\"Row {i}: ID={gene_annotation['ID'].iloc[i]}, ORF={gene_annotation['ORF'].iloc[i]}\")\n", "\n", " # Check the quality and completeness of the mapping\n", " non_null_symbols = gene_annotation['ORF'].notna().sum()\n", " total_rows = len(gene_annotation)\n", " print(f\"\\nORF column completeness: {non_null_symbols}/{total_rows} rows ({non_null_symbols/total_rows:.2%})\")\n" ] }, { "cell_type": "markdown", "id": "d5bd09a1", "metadata": {}, "source": [ "### Step 6: Gene Identifier Mapping" ] }, { "cell_type": "code", "execution_count": 7, "id": "43004b6c", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:01:56.677728Z", "iopub.status.busy": "2025-03-25T07:01:56.677601Z", "iopub.status.idle": "2025-03-25T07:02:00.463544Z", "shell.execute_reply": "2025-03-25T07:02:00.463161Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene mapping dataframe shape: (1687256, 2)\n", "First 5 rows of mapping data:\n", "{'ID': ['RTS0050057', 'RTS0020877', 'RTS0032443', 'RTS0032147', 'RTS0031938'], 'Gene': ['A1BG', 'A2M', 'A4GALT', 'A4GNT', 'AAAS']}\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data shape after mapping: (11792, 142)\n", "First 10 gene symbols in the processed gene data:\n", "['A1BG', 'A2M', 'A4GALT', 'A4GNT', 'AAAS', 'AACS', 'AADACL4', 'AAGAB', 'AAK1', 'AAMDC']\n", "Percentage of null values in gene data: 0.00%\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Gene expression data saved to ../../output/preprocess/Breast_Cancer/gene_data/GSE234017.csv\n" ] } ], "source": [ "# 1. Examine the gene annotation and gene expression data to determine the mapping\n", "# Based on the previous output and preview, we can see that:\n", "# - In gene_annotation: 'ID' contains probe IDs (e.g., 'RTS0020877') and 'ORF' contains gene symbols (e.g., 'A2M')\n", "# - In gene_data: The index has the same format as the 'ID' column from gene_annotation\n", "\n", "# 2. Extract the two relevant columns from the gene annotation dataframe to create a mapping\n", "mapping_df = get_gene_mapping(gene_annotation, 'ID', 'ORF')\n", "print(f\"Gene mapping dataframe shape: {mapping_df.shape}\")\n", "print(\"First 5 rows of mapping data:\")\n", "print(preview_df(mapping_df, n=5))\n", "\n", "# 3. Apply the gene mapping to convert probe-level measurements to gene expression\n", "gene_data = apply_gene_mapping(gene_data, mapping_df)\n", "print(f\"Gene expression data shape after mapping: {gene_data.shape}\")\n", "print(\"First 10 gene symbols in the processed gene data:\")\n", "print(gene_data.index[:10].tolist())\n", "\n", "# 4. Check for common issues in gene expression data\n", "null_percentage = gene_data.isnull().mean().mean() * 100\n", "print(f\"Percentage of null values in gene data: {null_percentage:.2f}%\")\n", "\n", "# 5. Save the gene expression data to a CSV file\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": "bd48ee3f", "metadata": {}, "source": [ "### Step 7: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 8, "id": "a35beacf", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T07:02:00.464929Z", "iopub.status.busy": "2025-03-25T07:02:00.464806Z", "iopub.status.idle": "2025-03-25T07:02:07.804487Z", "shell.execute_reply": "2025-03-25T07:02:07.803834Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape before normalization: (11792, 142)\n", "Gene data shape after normalization: (11787, 142)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Normalized gene data saved to ../../output/preprocess/Breast_Cancer/gene_data/GSE234017.csv\n", "Extracted clinical data shape: (1, 142)\n", "Preview of clinical data (first 5 samples):\n", " GSM7441040 GSM7441041 GSM7441042 GSM7441043 GSM7441044\n", "Breast_Cancer 0.0 0.0 0.0 0.0 0.0\n", "Clinical data saved to ../../output/preprocess/Breast_Cancer/clinical_data/GSE234017.csv\n", "Gene data columns (first 5): ['GSM7441040', 'GSM7441041', 'GSM7441042', 'GSM7441043', 'GSM7441044']\n", "Clinical data columns (first 5): ['GSM7441040', 'GSM7441041', 'GSM7441042', 'GSM7441043', 'GSM7441044']\n", "Found 142 common samples between gene and clinical data\n", "Initial linked data shape: (142, 11788)\n", "Preview of linked data (first 5 rows, first 5 columns):\n", " Breast_Cancer A1BG A2M A4GALT A4GNT\n", "GSM7441040 0.0 5.544706 6.085275 5.407203 4.670237\n", "GSM7441041 0.0 5.167737 6.691299 4.975092 3.167737\n", "GSM7441042 0.0 6.415664 8.396556 5.337662 4.975092\n", "GSM7441043 0.0 5.255200 6.489665 4.167737 4.337662\n", "GSM7441044 0.0 5.971407 7.971407 5.447845 4.447845\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data shape after handling missing values: (142, 11788)\n", "For the feature 'Breast_Cancer', the least common label is '0.0' with 47 occurrences. This represents 33.10% of the dataset.\n", "The distribution of the feature 'Breast_Cancer' in this dataset is fine.\n", "\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Linked data saved to ../../output/preprocess/Breast_Cancer/GSE234017.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the gene expression data\n", "try:\n", " # Make sure the directory exists\n", " os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)\n", " \n", " # Use the gene_data variable from the previous step (don't try to load it from file)\n", " print(f\"Gene data shape before normalization: {gene_data.shape}\")\n", " \n", " # Apply normalization to gene symbols\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " \n", " # Save the normalized gene data\n", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", " \n", " # Use the normalized data for further processing\n", " gene_data = normalized_gene_data\n", " is_gene_available = True\n", "except Exception as e:\n", " print(f\"Error normalizing gene data: {e}\")\n", " is_gene_available = False\n", "\n", "# 2. Load clinical data - respecting the analysis from Step 2\n", "# From Step 2, we determined:\n", "# trait_row = None # No Breast Cancer subtype data available\n", "# age_row = 2\n", "# gender_row = None\n", "is_trait_available = trait_row is not None\n", "\n", "# Skip clinical feature extraction when trait_row is None\n", "if is_trait_available:\n", " try:\n", " # Load the clinical data from file\n", " soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)\n", " background_info, clinical_data = get_background_and_clinical_data(matrix_file)\n", " \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", " gender_row=gender_row,\n", " convert_gender=convert_gender,\n", " age_row=age_row,\n", " convert_age=convert_age\n", " )\n", " \n", " print(f\"Extracted clinical data shape: {clinical_features.shape}\")\n", " print(\"Preview of clinical data (first 5 samples):\")\n", " print(clinical_features.iloc[:, :5])\n", " \n", " # Save the properly extracted clinical data\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " clinical_features.to_csv(out_clinical_data_file)\n", " print(f\"Clinical data saved to {out_clinical_data_file}\")\n", " except Exception as e:\n", " print(f\"Error extracting clinical data: {e}\")\n", " is_trait_available = False\n", "else:\n", " print(f\"No trait data ({trait}) available in this dataset based on previous analysis.\")\n", "\n", "# 3. Link clinical and genetic data if both are available\n", "if is_trait_available and is_gene_available:\n", " try:\n", " # Debug the column names to ensure they match\n", " print(f\"Gene data columns (first 5): {gene_data.columns[:5].tolist()}\")\n", " print(f\"Clinical data columns (first 5): {clinical_features.columns[:5].tolist()}\")\n", " \n", " # Check for common sample IDs\n", " common_samples = set(gene_data.columns).intersection(clinical_features.columns)\n", " print(f\"Found {len(common_samples)} common samples between gene and clinical data\")\n", " \n", " if len(common_samples) > 0:\n", " # Link the clinical and genetic data\n", " linked_data = geo_link_clinical_genetic_data(clinical_features, gene_data)\n", " print(f\"Initial linked data shape: {linked_data.shape}\")\n", " \n", " # Debug the trait values before handling missing values\n", " print(\"Preview of linked data (first 5 rows, first 5 columns):\")\n", " print(linked_data.iloc[:5, :5])\n", " \n", " # Handle missing values\n", " linked_data = handle_missing_values(linked_data, trait)\n", " print(f\"Linked data shape after handling missing values: {linked_data.shape}\")\n", " \n", " if linked_data.shape[0] > 0:\n", " # Check for bias in trait and demographic features\n", " is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " \n", " # Validate the data quality and save cohort info\n", " note = \"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\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=is_biased,\n", " df=linked_data,\n", " note=note\n", " )\n", " \n", " # 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", " linked_data.to_csv(out_data_file)\n", " print(f\"Linked data saved to {out_data_file}\")\n", " else:\n", " print(\"Data not usable for the trait study - not saving final linked data.\")\n", " else:\n", " print(\"After handling missing values, no samples remain.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No valid samples after handling missing values.\"\n", " )\n", " else:\n", " print(\"No common samples found between gene expression and clinical data.\")\n", " 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=True,\n", " df=pd.DataFrame(),\n", " note=\"No common samples between gene expression and clinical data.\"\n", " )\n", " except Exception as e:\n", " print(f\"Error linking or processing data: {e}\")\n", " 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=True, # Assume biased if there's an error\n", " df=pd.DataFrame(), # Empty dataframe for metadata\n", " note=f\"Error in data processing: {str(e)}\"\n", " )\n", "else:\n", " # Create an empty DataFrame for metadata purposes\n", " empty_df = pd.DataFrame()\n", " \n", " # We can't proceed with linking if either trait or gene data is missing\n", " print(\"Cannot proceed with data linking due to missing trait or gene data.\")\n", " 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=True, # Data is unusable if we're missing components\n", " df=empty_df, # Empty dataframe for metadata\n", " note=\"Dataset contains gene expression data from triple negative breast cancer vs. luminal tumors, but no explicit breast cancer subtype labels in the sample characteristics.\"\n", " )" ] } ], "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 }