Liu-Hy's picture
Add files using upload-large-folder tool
0db4514 verified
raw
history blame
8.01 kB
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Chronic_kidney_disease"
cohort = "GSE180393"
# Input paths
in_trait_dir = "../DATA/GEO/Chronic_kidney_disease"
in_cohort_dir = "../DATA/GEO/Chronic_kidney_disease/GSE180393"
# Output paths
out_data_file = "./output/preprocess/1/Chronic_kidney_disease/GSE180393.csv"
out_gene_data_file = "./output/preprocess/1/Chronic_kidney_disease/gene_data/GSE180393.csv"
out_clinical_data_file = "./output/preprocess/1/Chronic_kidney_disease/clinical_data/GSE180393.csv"
json_path = "./output/preprocess/1/Chronic_kidney_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)
# 1. Evaluate whether gene expression data is available
is_gene_available = True # Based on microarray transcriptome data from the summary
# 2. Determine availability of trait, age, and gender data
# and define corresponding conversion functions
# From the sample characteristics dictionary, row 0 provides multi-category info
# about disease status. We will code "Living donor" or "unaffected" as 0 (control)
# and all others as 1 (CKD). Rows for age/gender do not appear available.
trait_row = 0
age_row = None
gender_row = None
def convert_trait(value: str):
# Extract the part after the colon
parts = value.split(":", 1)
if len(parts) < 2:
return None # Unknown format
label = parts[1].strip().lower()
# Living donor or unaffected
if "living donor" in label or "unaffected" in label:
return 0
else:
return 1
def convert_age(value: str):
# No age data available
return None
def convert_gender(value: str):
# No gender data available
return None
# 3. Conduct initial filtering and save metadata
is_trait_available = (trait_row is not None)
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. If trait data is available, extract and preview clinical features
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 and save the resulting clinical dataframe
preview = preview_df(selected_clinical_df, n=5)
print("Preview of selected clinical features:", preview)
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])
# The listed identifiers (e.g., "100009613_at", "10000_at", etc.) are typical Affymetrix probe set IDs,
# not standard human gene symbols. Therefore, they require mapping to gene symbols.
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))
# STEP6: Gene Identifier Mapping
# Observing the preview from step 5, the annotation DataFrame has columns 'ID' and 'ENTREZ_GENE_ID',
# but 'ENTREZ_GENE_ID' is purely numeric, which leads to an empty mapping when the library's
# apply_gene_mapping() tries to parse it as a “human gene symbol.” We will therefore implement
# a custom mapping function that distributes expression values to numeric Entrez IDs without
# filtering them out.
def apply_entrez_id_mapping(expression_df: pd.DataFrame, annotation_df: pd.DataFrame) -> pd.DataFrame:
"""
Convert probe-level data to gene-level data using numeric Entrez IDs.
If a probe maps to multiple Entrez IDs (split by '///'), each gene gets an equal split.
Then we sum contributions from multiple probes associated with the same gene ID.
"""
# Keep only the columns we need, renaming ENTREZ_GENE_ID to 'Gene'
mapping_df = annotation_df[['ID', 'ENTREZ_GENE_ID']].copy()
mapping_df.columns = ['ID', 'Gene']
mapping_df.dropna(subset=['Gene'], inplace=True)
# Filter to probes that exist in expression_df
mapping_df = mapping_df[mapping_df['ID'].isin(expression_df.index)].copy()
# A single probe might have multiple Entrez IDs separated by '///'
def split_entrez_ids(gene_str):
if '///' in gene_str:
return [x.strip() for x in gene_str.split('///') if x.strip()]
else:
return [gene_str.strip()]
mapping_df['Gene'] = mapping_df['Gene'].apply(split_entrez_ids)
# Remove rows with no valid gene IDs
mapping_df = mapping_df[mapping_df['Gene'].map(len) > 0]
# Count how many genes per probe
mapping_df['num_genes'] = mapping_df['Gene'].map(len)
# Explode so each gene occupies its own row
mapping_df.set_index('ID', inplace=True)
mapping_df = mapping_df.explode('Gene')
# Join expression data
merged_df = mapping_df.join(expression_df, how='inner')
expr_cols = [c for c in merged_df.columns if c not in ['Gene', 'num_genes']]
# Divide the probe expression among mapped genes
merged_df[expr_cols] = merged_df[expr_cols].div(merged_df['num_genes'], axis=0)
# Sum expressions for each gene
gene_df = merged_df.groupby('Gene')[expr_cols].sum()
return gene_df
# 1 & 2. Identify columns for probe ID and gene ID, then map
gene_data = apply_entrez_id_mapping(gene_data, gene_annotation)
# 3. Print shape after mapping to confirm we have gene-level data
print("Gene expression data shape after mapping:", gene_data.shape)
# STEP7
# 1. Normalize the obtained gene data with the 'normalize_gene_symbols_in_index' function from the library.
normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
normalized_gene_data.to_csv(out_gene_data_file)
# 2. Link the clinical and genetic data with the 'geo_link_clinical_genetic_data' function from the library.
linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
# 3. Handle missing values in the linked data
linked_data = handle_missing_values(linked_data, trait)
# 4. Determine whether the trait and some demographic features are severely biased, and remove biased features.
is_trait_biased, unbiased_linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Conduct quality check and save the cohort information.
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=is_trait_biased,
df=linked_data
)
# 6. If the linked data is usable, save it as a CSV file to 'out_data_file'.
if is_usable:
unbiased_linked_data.to_csv(out_data_file)