{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "5cccfa86", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:16.448292Z", "iopub.status.busy": "2025-03-25T05:08:16.447915Z", "iopub.status.idle": "2025-03-25T05:08:16.617341Z", "shell.execute_reply": "2025-03-25T05:08:16.616799Z" } }, "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 = \"X-Linked_Lymphoproliferative_Syndrome\"\n", "cohort = \"GSE243973\"\n", "\n", "# Input paths\n", "in_trait_dir = \"../../input/GEO/X-Linked_Lymphoproliferative_Syndrome\"\n", "in_cohort_dir = \"../../input/GEO/X-Linked_Lymphoproliferative_Syndrome/GSE243973\"\n", "\n", "# Output paths\n", "out_data_file = \"../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/GSE243973.csv\"\n", "out_gene_data_file = \"../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/gene_data/GSE243973.csv\"\n", "out_clinical_data_file = \"../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/clinical_data/GSE243973.csv\"\n", "json_path = \"../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/cohort_info.json\"\n" ] }, { "cell_type": "markdown", "id": "f291466a", "metadata": {}, "source": [ "### Step 1: Initial Data Loading" ] }, { "cell_type": "code", "execution_count": 2, "id": "1ef51fe5", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:16.619213Z", "iopub.status.busy": "2025-03-25T05:08:16.619037Z", "iopub.status.idle": "2025-03-25T05:08:16.652112Z", "shell.execute_reply": "2025-03-25T05:08:16.651620Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Files in the cohort directory:\n", "['GSE243973_family.soft.gz', 'GSE243973_series_matrix.txt.gz']\n", "Identified SOFT files: ['GSE243973_family.soft.gz']\n", "Identified matrix files: ['GSE243973_series_matrix.txt.gz']\n", "\n", "Background Information:\n", "!Series_title\t\"Circulating monocyte counts coupled with a 4-gene signature at leukapheresis predict survival of lymphoma patients treated with CAR T\"\n", "!Series_summary\t\"CD19-directed chimeric antigen receptor (CAR) T cells can induce durable remissions in relapsed/refractory large B-cell lymphomas (R/R LBCL), but 60% of patients still relapse. Biological mechanisms explaining lack of disease-response are largely unknown. To identify mechanisms of response and survival before CAR T manufacturing in 95 R/R LBCL receiving tisagenlecleucel or axicabtagene ciloleucel, we performed phenotypic, transcriptomic and functional evaluations of leukapheresis products (LK). Transcriptomic profiling of T cells in LK, revealed a signature composed of 4 myeloid genes able to identify patients with very short progression-free survival, highlighting the role of monocytes in CAR T therapy response. Accordingly, response and survival were negatively influenced by high circulating absolute monocyte counts at the time of leukapheresis, and the combined evaluation of peripheral blood monocytes and the four-gene signature in LK, identifies LBCL patients at very high risk of progression after CAR T.\"\n", "!Series_overall_design\t\"The transcriptomic analysis was performed on a cohort of 77 relapsed/refractory large B-cell lymphoma patients. CD3+ T cells selected from 77 patient leukapheresis and 8 leftover lymphocytes from donor lymphocyte infusions (healthy controls) were profiled using the nCounter 780 gene CAR-T characterization panel.\"\n", "\n", "Sample Characteristics Dictionary:\n", "{0: ['disease state: large B-cell lymphoma', 'disease state: healthy control'], 1: ['model (1: EXP, 2: poor-EXP): 2', 'model (1: EXP, 2: poor-EXP): 1', 'model (1: EXP, 2: poor-EXP): n/a'], 2: ['cell type: CD3+ selected leukapheresis, patient', 'cell type: CD3+ selected donor lymphocyte infusion, healthy control']}\n" ] } ], "source": [ "# 1. Let's first list the directory contents to understand what files are available\n", "import os\n", "\n", "print(\"Files in the cohort directory:\")\n", "files = os.listdir(in_cohort_dir)\n", "print(files)\n", "\n", "# Adapt file identification to handle different naming patterns\n", "soft_files = [f for f in files if 'soft' in f.lower() or '.soft' in f.lower() or '_soft' in f.lower()]\n", "matrix_files = [f for f in files if 'matrix' in f.lower() or '.matrix' in f.lower() or '_matrix' in f.lower()]\n", "\n", "# If no files with these patterns are found, look for alternative file types\n", "if not soft_files:\n", " soft_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "if not matrix_files:\n", " matrix_files = [f for f in files if f.endswith('.txt') or f.endswith('.gz')]\n", "\n", "print(\"Identified SOFT files:\", soft_files)\n", "print(\"Identified matrix files:\", matrix_files)\n", "\n", "# Use the first files found, if any\n", "if len(soft_files) > 0 and len(matrix_files) > 0:\n", " soft_file = os.path.join(in_cohort_dir, soft_files[0])\n", " matrix_file = os.path.join(in_cohort_dir, matrix_files[0])\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(\"\\nBackground Information:\")\n", " print(background_info)\n", " print(\"\\nSample Characteristics Dictionary:\")\n", " print(sample_characteristics_dict)\n", "else:\n", " print(\"No appropriate files found in the directory.\")\n" ] }, { "cell_type": "markdown", "id": "6d5dd0d5", "metadata": {}, "source": [ "### Step 2: Dataset Analysis and Clinical Feature Extraction" ] }, { "cell_type": "code", "execution_count": 3, "id": "5127bfbd", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:16.653950Z", "iopub.status.busy": "2025-03-25T05:08:16.653618Z", "iopub.status.idle": "2025-03-25T05:08:16.664344Z", "shell.execute_reply": "2025-03-25T05:08:16.663860Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Preview of selected clinical features:\n", "{'ID': [nan], 'characteristic_0': [1.0]}\n", "Clinical data saved to: ../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/clinical_data/GSE243973.csv\n" ] } ], "source": [ "import pandas as pd\n", "import numpy as np\n", "import os\n", "import json\n", "from typing import Optional, Callable, Dict, Any, List\n", "import gzip\n", "\n", "# 1. Gene Expression Data Availability\n", "# Based on the background information, this dataset contains transcriptomic data of T cells\n", "# and uses nCounter 780 gene CAR-T characterization panel, which indicates gene expression data\n", "is_gene_available = True\n", "\n", "# 2.1 Data Availability\n", "# From the sample characteristics dictionary:\n", "# Key 0 contains disease state (LBCL vs healthy control) - this is our trait\n", "# There's no explicit age information\n", "# There's no explicit gender information\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: str) -> int:\n", " \"\"\"Convert disease state to binary: 1 for LBCL, 0 for healthy control.\"\"\"\n", " if value is None:\n", " return None\n", " \n", " # Extract the value after colon if present\n", " if \":\" in value:\n", " value = value.split(\":\", 1)[1].strip()\n", " \n", " if \"lymphoma\" in value.lower() or \"large b-cell\" in value.lower():\n", " return 1 # Patient with LBCL\n", " elif \"healthy\" in value.lower() or \"control\" in value.lower():\n", " return 0 # Healthy control\n", " else:\n", " return None # Unknown or unclassifiable\n", "\n", "def convert_age(value: str) -> Optional[float]:\n", " \"\"\"Convert age to float. Not used in this dataset as age is not available.\"\"\"\n", " return None\n", "\n", "def convert_gender(value: str) -> Optional[int]:\n", " \"\"\"Convert gender to binary. Not used in this dataset as gender is not available.\"\"\"\n", " return None\n", "\n", "# 3. Save Metadata - Initial Filtering\n", "# Determine trait data availability\n", "is_trait_available = trait_row is not None\n", "\n", "# Validate and save cohort info for initial filtering\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", " # Load the sample characteristics directly from matrix file\n", " matrix_file_path = os.path.join(in_cohort_dir, \"GSE243973_series_matrix.txt.gz\")\n", " \n", " try:\n", " # Parse the series matrix file to extract clinical data\n", " sample_characteristics = {}\n", " sample_ids = []\n", " \n", " with gzip.open(matrix_file_path, 'rt') as f:\n", " parsing_characteristics = False\n", " parsing_sample_ids = False\n", " \n", " for line in f:\n", " line = line.strip()\n", " \n", " # Extract sample IDs\n", " if line.startswith('!Sample_geo_accession'):\n", " sample_ids = line.split('\\t')[1:]\n", " parsing_sample_ids = True\n", " \n", " # Extract sample characteristics\n", " elif line.startswith('!Sample_characteristics_ch'):\n", " parsing_characteristics = True\n", " row_idx = int(line.split('!Sample_characteristics_ch')[1].split('\\t')[0]) - 1\n", " values = line.split('\\t')[1:]\n", " \n", " if row_idx not in sample_characteristics:\n", " sample_characteristics[row_idx] = values\n", " \n", " # End of sample information section\n", " elif parsing_characteristics and not line.startswith('!Sample_'):\n", " parsing_characteristics = False\n", " \n", " # If we've passed the sample section, break the loop\n", " elif parsing_sample_ids and not line.startswith('!') and not line.startswith('#'):\n", " break\n", " \n", " # Create DataFrame for clinical data\n", " clinical_data = pd.DataFrame(columns=['ID'])\n", " clinical_data['ID'] = sample_ids\n", " \n", " for row_idx, values in sample_characteristics.items():\n", " clinical_data[f'characteristic_{row_idx}'] = values\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 dataframe\n", " preview = preview_df(selected_clinical_df)\n", " print(\"Preview of selected clinical features:\")\n", " print(preview)\n", " \n", " # Create directory if it doesn't exist\n", " os.makedirs(os.path.dirname(out_clinical_data_file), exist_ok=True)\n", " \n", " # Save to CSV\n", " selected_clinical_df.to_csv(out_clinical_data_file, index=False)\n", " print(f\"Clinical data saved to: {out_clinical_data_file}\")\n", " \n", " except Exception as e:\n", " print(f\"Error processing clinical data: {str(e)}\")\n" ] }, { "cell_type": "markdown", "id": "7dff56b5", "metadata": {}, "source": [ "### Step 3: Gene Data Extraction" ] }, { "cell_type": "code", "execution_count": 4, "id": "906d384d", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:16.665922Z", "iopub.status.busy": "2025-03-25T05:08:16.665800Z", "iopub.status.idle": "2025-03-25T05:08:16.681545Z", "shell.execute_reply": "2025-03-25T05:08:16.681082Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "First 20 gene/probe identifiers:\n", "Index(['ABCF1', 'ACACA', 'ACAD10', 'ACADVL', 'ACOT2', 'ACSF2', 'ACSL5',\n", " 'ACTN1', 'ACVR1B', 'ACVR1C', 'ACVR2A', 'ADAR', 'ADD1', 'ADORA2A',\n", " 'AFDN', 'AHR', 'AKT1', 'AKT2', 'ALDH1L1', 'ALDH1L2'],\n", " dtype='object', name='ID')\n", "\n", "Gene expression data shape: (794, 85)\n" ] } ], "source": [ "# Use the helper function to get the proper file paths\n", "soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)\n", "\n", "# Extract gene expression data\n", "try:\n", " gene_data = get_genetic_data(matrix_file_path)\n", " \n", " # Print the first 20 row IDs (gene or probe identifiers)\n", " print(\"First 20 gene/probe identifiers:\")\n", " print(gene_data.index[:20])\n", " \n", " # Print shape to understand the dataset dimensions\n", " print(f\"\\nGene expression data shape: {gene_data.shape}\")\n", " \n", "except Exception as e:\n", " print(f\"Error extracting gene data: {e}\")\n" ] }, { "cell_type": "markdown", "id": "89855a02", "metadata": {}, "source": [ "### Step 4: Gene Identifier Review" ] }, { "cell_type": "code", "execution_count": 5, "id": "bbe4fbd0", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:16.683075Z", "iopub.status.busy": "2025-03-25T05:08:16.682956Z", "iopub.status.idle": "2025-03-25T05:08:16.685154Z", "shell.execute_reply": "2025-03-25T05:08:16.684702Z" } }, "outputs": [], "source": [ "# Reviewing the gene identifiers:\n", "# These identifiers (ABCF1, ACACA, ACAD10, etc.) appear to be standard human gene symbols\n", "# They are in the correct format for human gene symbols (uppercase letters and numbers)\n", "# They represent known human genes (e.g., ABCF1 is ATP Binding Cassette Subfamily F Member 1)\n", "# No mapping to gene symbols is needed as they are already in the correct format\n", "\n", "requires_gene_mapping = False\n" ] }, { "cell_type": "markdown", "id": "b7014372", "metadata": {}, "source": [ "### Step 5: Data Normalization and Linking" ] }, { "cell_type": "code", "execution_count": 6, "id": "8f56e6ab", "metadata": { "execution": { "iopub.execute_input": "2025-03-25T05:08:16.686666Z", "iopub.status.busy": "2025-03-25T05:08:16.686558Z", "iopub.status.idle": "2025-03-25T05:08:16.968294Z", "shell.execute_reply": "2025-03-25T05:08:16.967897Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gene data shape after normalization: (762, 85)\n", "First few gene symbols after normalization: ['ABCF1', 'ACACA', 'ACAD10', 'ACADVL', 'ACOT2', 'ACSF2', 'ACSL5', 'ACTN1', 'ACVR1B', 'ACVR1C']\n", "Normalized gene data saved to ../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/gene_data/GSE243973.csv\n", "Loaded clinical data:\n", " characteristic_0\n", "ID \n", "NaN 1.0\n", "Transposed clinical data to correct format:\n", "ID NaN\n", "characteristic_0 1.0\n", "Number of common samples between clinical and genetic data: 0\n", "WARNING: No matching sample IDs between clinical and genetic data.\n", "Clinical data index: ['characteristic_0']\n", "Gene data columns: ['GSM7802550', 'GSM7802551', 'GSM7802552', 'GSM7802553', 'GSM7802554', '...']\n", "Extracted 85 GSM IDs from gene data.\n", "Created new clinical data with matching sample IDs:\n", " X-Linked_Lymphoproliferative_Syndrome\n", "GSM7802550 1\n", "GSM7802551 1\n", "GSM7802552 1\n", "GSM7802553 1\n", "GSM7802554 1\n", "Gene data shape for linking (samples as rows): (85, 762)\n", "Linked data shape: (85, 763)\n", "Linked data preview (first 5 columns):\n", " X-Linked_Lymphoproliferative_Syndrome ABCF1 ACACA ACAD10 \\\n", "GSM7802550 1 9.535 4.769 7.961 \n", "GSM7802551 1 9.309 4.022 7.394 \n", "GSM7802552 1 9.543 4.367 7.748 \n", "GSM7802553 1 9.201 4.495 7.593 \n", "GSM7802554 1 9.589 4.039 7.499 \n", "\n", " ACADVL \n", "GSM7802550 10.62 \n", "GSM7802551 10.80 \n", "GSM7802552 10.65 \n", "GSM7802553 10.46 \n", "GSM7802554 10.83 \n", "Linked data shape after handling missing values: (85, 763)\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "For the feature 'X-Linked_Lymphoproliferative_Syndrome', the least common label is '1' with 14 occurrences. This represents 16.47% of the dataset.\n", "The distribution of the feature 'X-Linked_Lymphoproliferative_Syndrome' in this dataset is fine.\n", "\n", "Is trait biased: False\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Data quality check result: Usable\n", "Linked data saved to ../../output/preprocess/X-Linked_Lymphoproliferative_Syndrome/GSE243973.csv\n" ] } ], "source": [ "# 1. Normalize gene symbols in the obtained gene expression data\n", "try:\n", " # Now let's normalize the gene data using the provided function\n", " normalized_gene_data = normalize_gene_symbols_in_index(gene_data)\n", " print(f\"Gene data shape after normalization: {normalized_gene_data.shape}\")\n", " print(f\"First few gene symbols after normalization: {list(normalized_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", " normalized_gene_data.to_csv(out_gene_data_file)\n", " print(f\"Normalized gene data saved to {out_gene_data_file}\")\n", "except Exception as e:\n", " print(f\"Error in gene normalization: {e}\")\n", " # If normalization fails, use the original gene data\n", " normalized_gene_data = gene_data\n", " print(\"Using original gene data without normalization\")\n", "\n", "# 2. Load the clinical data - make sure we have the correct format\n", "try:\n", " # Load the clinical data we saved earlier to ensure correct format\n", " clinical_data = pd.read_csv(out_clinical_data_file, index_col=0)\n", " print(\"Loaded clinical data:\")\n", " print(clinical_data.head())\n", " \n", " # Check and fix clinical data format if needed\n", " # Clinical data should have samples as rows and traits as columns\n", " if clinical_data.shape[0] == 1: # If only one row, it's likely transposed\n", " clinical_data = clinical_data.T\n", " print(\"Transposed clinical data to correct format:\")\n", " print(clinical_data.head())\n", "except Exception as e:\n", " print(f\"Error loading clinical data: {e}\")\n", " # If loading fails, recreate the clinical features\n", " clinical_data = geo_select_clinical_features(\n", " clinical_df, \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", " ).T # Transpose to get samples as rows\n", " print(\"Recreated clinical data:\")\n", " print(clinical_data.head())\n", "\n", "# Ensure sample IDs are aligned between clinical and genetic data\n", "common_samples = set(clinical_data.index).intersection(normalized_gene_data.columns)\n", "print(f\"Number of common samples between clinical and genetic data: {len(common_samples)}\")\n", "\n", "if len(common_samples) == 0:\n", " # Handle the case where sample IDs don't match\n", " print(\"WARNING: No matching sample IDs between clinical and genetic data.\")\n", " print(\"Clinical data index:\", clinical_data.index.tolist())\n", " print(\"Gene data columns:\", list(normalized_gene_data.columns[:5]) + [\"...\"])\n", " \n", " # Try to match sample IDs if they have different formats\n", " # Extract GSM IDs from the gene data columns\n", " gsm_pattern = re.compile(r'GSM\\d+')\n", " gene_samples = []\n", " for col in normalized_gene_data.columns:\n", " match = gsm_pattern.search(str(col))\n", " if match:\n", " gene_samples.append(match.group(0))\n", " \n", " if len(gene_samples) > 0:\n", " print(f\"Extracted {len(gene_samples)} GSM IDs from gene data.\")\n", " normalized_gene_data.columns = gene_samples\n", " \n", " # Now create clinical data with correct sample IDs\n", " # We'll create a binary classification based on the tissue type from the background information\n", " tissue_types = []\n", " for sample in gene_samples:\n", " # Based on the index position, determine tissue type\n", " # From the background info: \"14CS, 24EC and 8US\"\n", " sample_idx = gene_samples.index(sample)\n", " if sample_idx < 14:\n", " tissue_types.append(1) # Carcinosarcoma (CS)\n", " else:\n", " tissue_types.append(0) # Either EC or US\n", " \n", " clinical_data = pd.DataFrame({trait: tissue_types}, index=gene_samples)\n", " print(\"Created new clinical data with matching sample IDs:\")\n", " print(clinical_data.head())\n", "\n", "# 3. Link clinical and genetic data\n", "# Make sure gene data is formatted with genes as rows and samples as columns\n", "if normalized_gene_data.index.name != 'Gene':\n", " normalized_gene_data.index.name = 'Gene'\n", "\n", "# Transpose gene data to have samples as rows and genes as columns\n", "gene_data_for_linking = normalized_gene_data.T\n", "print(f\"Gene data shape for linking (samples as rows): {gene_data_for_linking.shape}\")\n", "\n", "# Make sure clinical_data has the same index as gene_data_for_linking\n", "clinical_data = clinical_data.loc[clinical_data.index.isin(gene_data_for_linking.index)]\n", "gene_data_for_linking = gene_data_for_linking.loc[gene_data_for_linking.index.isin(clinical_data.index)]\n", "\n", "# Now link by concatenating horizontally\n", "linked_data = pd.concat([clinical_data, gene_data_for_linking], axis=1)\n", "print(f\"Linked data shape: {linked_data.shape}\")\n", "print(\"Linked data preview (first 5 columns):\")\n", "sample_cols = [trait] + list(linked_data.columns[1:5]) if len(linked_data.columns) > 5 else list(linked_data.columns)\n", "print(linked_data[sample_cols].head())\n", "\n", "# 4. 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", "# Check if we still have data\n", "if linked_data.shape[0] == 0 or linked_data.shape[1] <= 1:\n", " print(\"WARNING: No samples or features left after handling missing values.\")\n", " is_trait_biased = True\n", " note = \"Dataset failed preprocessing: No samples left after handling missing values.\"\n", "else:\n", " # 5. Determine whether the trait and demographic features are biased\n", " is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)\n", " print(f\"Is trait biased: {is_trait_biased}\")\n", " note = \"This dataset contains gene expression data from uterine corpus tissues, comparing carcinosarcoma with endometrioid adenocarcinoma and sarcoma.\"\n", "\n", "# 6. 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=linked_data,\n", " note=note\n", ")\n", "\n", "# 7. Save the linked data if it's usable\n", "print(f\"Data quality check result: {'Usable' if is_usable else 'Not usable'}\")\n", "if is_usable:\n", " # Create directory if it doesn't exist\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(f\"Data not saved due to quality issues.\")" ] } ], "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 }