Liu-Hy's picture
Add files using upload-large-folder tool
b5650f0 verified
raw
history blame
9.57 kB
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Crohns_Disease"
cohort = "GSE123088"
# Input paths
in_trait_dir = "../DATA/GEO/Crohns_Disease"
in_cohort_dir = "../DATA/GEO/Crohns_Disease/GSE123088"
# Output paths
out_data_file = "./output/preprocess/1/Crohns_Disease/GSE123088.csv"
out_gene_data_file = "./output/preprocess/1/Crohns_Disease/gene_data/GSE123088.csv"
out_clinical_data_file = "./output/preprocess/1/Crohns_Disease/clinical_data/GSE123088.csv"
json_path = "./output/preprocess/1/Crohns_Disease/cohort_info.json"
# STEP1
from tools.preprocess import *
# 1. Identify the paths to the SOFT file and the matrix file
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# 2. Read the matrix file to obtain background information and sample characteristics data
background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
background_info, clinical_data = get_background_and_clinical_data(matrix_file, background_prefixes, clinical_prefixes)
# 3. Obtain the sample characteristics dictionary from the clinical dataframe
sample_characteristics_dict = get_unique_values_by_row(clinical_data)
# 4. Explicitly print out all the background information and the sample characteristics dictionary
print("Background Information:")
print(background_info)
print("Sample Characteristics Dictionary:")
print(sample_characteristics_dict)
# STEP 2: Dataset Analysis and Clinical Feature Extraction
# 1. Determine if gene expression data is available
# From the background info (single-cell-based strategy) and sample descriptions,
# we assume it contains gene expression data rather than pure miRNA or methylation data.
is_gene_available = True
# 2. Variable Availability and Data Type Conversion
# Based on the sample characteristics dictionary:
# Row 1 contains many different diagnoses, including CROHN_DISEASE, so set trait_row=1.
# Rows 3 and 4 include "age: number" entries, but row 3 has more comprehensive listings, so set age_row=3.
# Row 2 contains "Sex: Male" and "Sex: Female", so set gender_row=2.
trait_row = 1
age_row = 3
gender_row = 2
# 2.2 Data Type and Conversion Functions
def convert_trait(x: str):
"""
Convert the diagnosis to a binary indicator:
1 if it is 'CROHN_DISEASE', else 0.
Return None for any unrecognized or empty value.
"""
# Split on the colon to isolate the actual value.
parts = x.split(":")
if len(parts) < 2:
return None
val = parts[1].strip().upper()
if val == "CROHN_DISEASE":
return 1
else:
return 0
def convert_age(x: str):
"""
Parse 'age: number' from the string.
Return the number as a float if valid. Otherwise return None.
"""
parts = x.split(":")
if len(parts) < 2:
return None
val = parts[1].strip()
# Check if val is numeric
try:
return float(val)
except ValueError:
return None
def convert_gender(x: str):
"""
Convert 'Sex: Female' -> 0, 'Sex: Male' -> 1.
Return None for unrecognized or empty values.
"""
parts = x.split(":")
if len(parts) < 2:
return None
val = parts[1].strip().upper()
if val == "MALE":
return 1
elif val == "FEMALE":
return 0
else:
return None
# 3. Save Metadata (initial filtering)
# Trait data is available if trait_row is not None. Here, trait_row=1 => available.
is_trait_available = (trait_row is not None)
# Perform initial filtering and save metadata
_ = validate_and_save_cohort_info(
is_final=False,
cohort=cohort,
info_path=json_path,
is_gene_available=is_gene_available,
is_trait_available=is_trait_available
)
# 4. Clinical Feature Extraction
# If trait_row is not None, we extract clinical features from the previously obtained DataFrame "clinical_data"
if trait_row is not None:
selected_clinical_df = geo_select_clinical_features(
clinical_df=clinical_data,
trait=trait,
trait_row=trait_row,
convert_trait=convert_trait,
age_row=age_row,
convert_age=convert_age,
gender_row=gender_row,
convert_gender=convert_gender
)
# Preview
preview_info = preview_df(selected_clinical_df)
print("Clinical feature preview:", preview_info)
# Save to CSV
selected_clinical_df.to_csv(out_clinical_data_file, index=False)
# STEP3
# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
gene_data = get_genetic_data(matrix_file)
# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
print(gene_data.index[:20])
# After observing the given identifiers (which appear to be numeric IDs),
# they do not match standard human gene symbols. Therefore:
print("requires_gene_mapping = True")
# STEP5
# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
gene_annotation = get_gene_annotation(soft_file)
# 2. Use the 'preview_df' function from the library to preview the data and print out the results.
print("Gene annotation preview:")
print(preview_df(gene_annotation))
# STEP 6: Gene Identifier Mapping (Corrected)
import re
def apply_gene_mapping_entrez(expression_df: pd.DataFrame, mapping_df: pd.DataFrame) -> pd.DataFrame:
"""
Convert probe-level expression measurements to gene-level measurements using numeric (Entrez) IDs.
For any probe that maps to multiple Entrez IDs, the expression is divided equally among them.
Then we sum up contributions for each gene across all probes.
"""
# Keep only those mappings whose 'ID' matches the expression probes
mapping_df = mapping_df[mapping_df['ID'].isin(expression_df.index)].copy()
# Each row has columns: ['ID', 'Gene'] from get_gene_mapping(...)
# 'Gene' here stores the Entrez ID. Convert to string in case they're numeric.
mapping_df['Gene'] = mapping_df['Gene'].astype(str).fillna('')
# If multiple Entrez IDs are stored in one cell (separated by commas or semicolons), split them
def split_gene_ids(x: str):
return [val.strip() for val in re.split(r'[;,]', x) if val.strip()]
mapping_df['Gene'] = mapping_df['Gene'].apply(split_gene_ids)
# Count how many Entrez IDs each probe maps to
mapping_df['num_genes'] = mapping_df['Gene'].apply(len)
# Expand rows so each probe maps to one Entrez ID per row
mapping_df = mapping_df.explode('Gene').dropna(subset=['Gene'])
# Set 'ID' as the index so we can join on the probe-level expression data
mapping_df.set_index('ID', inplace=True)
# Join annotation (Entrez gene IDs) to expression values
merged_df = mapping_df.join(expression_df, how='inner')
# Identify the expression columns (all columns in expression_df)
expr_cols = expression_df.columns
# If a probe maps to multiple genes, divide its expression equally
merged_df[expr_cols] = merged_df[expr_cols].div(
merged_df['num_genes'].replace(0, 1), axis=0
)
# Sum the distributed values across all probes that map to the same Entrez ID
gene_expression_df = merged_df.groupby('Gene')[expr_cols].sum()
return gene_expression_df
# 1) Identify columns for probes and symbols
probe_col = 'ID'
symbol_col = 'ENTREZ_GENE_ID'
# 2) Create a mapping DataFrame
mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=symbol_col)
# 3) Convert probe-level measurements to gene expression data using our revised function
gene_data = apply_gene_mapping_entrez(gene_data, mapping_df)
# Print a brief check of the result
print("Mapped gene_data shape:", gene_data.shape)
print("First 5 gene identifiers after mapping:", gene_data.index[:5])
import os
import pandas as pd
# STEP 7 (Revised)
# 1) Normalize gene symbols in the obtained gene expression data
normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
normalized_gene_data.to_csv(out_gene_data_file)
# 2) Read the clinical data back in the same shape as it was saved (3 rows = [trait, Age, Gender], columns = samples).
# Then reorient it so rows = [trait, Age, Gender] and columns = sample IDs exactly.
tmp = pd.read_csv(out_clinical_data_file, header=0)
# Extract row labels (trait, Age, Gender) from the first column, strip any accidental whitespace
row_names = tmp.iloc[:, 0].astype(str).str.strip().values
# Extract sample IDs from the remaining column headers
samples = [col.strip() for col in tmp.columns[1:].tolist()]
# Build a DataFrame of shape (3, #samples)
selected_clinical_df = tmp.iloc[:, 1:].copy()
selected_clinical_df.index = row_names
selected_clinical_df.columns = samples
# 3) Link the clinical and genetic data
linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
# 4) Handle missing values in the linked data
linked_data = handle_missing_values(linked_data, trait)
# 5) Check for biased features (including the trait)
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 6) Final validation and saving metadata
is_usable = validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=True,
is_trait_available=True,
is_biased=trait_biased,
df=linked_data,
note="Data from GSE123088, trait is Crohn's disease."
)
# 7) If the dataset is usable, save the linked data
if is_usable:
linked_data.to_csv(out_data_file)