Liu-Hy's picture
Add files using upload-large-folder tool
24fe0da verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Endometriosis"
cohort = "GSE75427"
# Input paths
in_trait_dir = "../DATA/GEO/Endometriosis"
in_cohort_dir = "../DATA/GEO/Endometriosis/GSE75427"
# Output paths
out_data_file = "./output/preprocess/1/Endometriosis/GSE75427.csv"
out_gene_data_file = "./output/preprocess/1/Endometriosis/gene_data/GSE75427.csv"
out_clinical_data_file = "./output/preprocess/1/Endometriosis/clinical_data/GSE75427.csv"
json_path = "./output/preprocess/1/Endometriosis/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. Gene Expression Data Availability
is_gene_available = True # From the background ("Expression profiles..."), we infer mRNA expression data is provided
# 2. Variable Availability and Data Type Conversion
# Inspecting the sample characteristics dictionary, we see:
# 0 -> ["cell type: proliferative phase normal endometrium"] (only one unique value, not useful for trait)
# 1 -> ["gender: Female"] (only female, no variation)
# 2 -> ["age: 37y", "age: 47y", "age: 53y", "age: 41y"] (multiple unique values, so age is available)
# 3 -> ["treatment: ...", "treatment: ..."] (treatment info, not needed for this analysis)
# Therefore:
trait_row = None # Not available or no variation for trait (endometriosis)
age_row = 2 # Available and has variation
gender_row = None # All female, no variation
# Define the conversion functions
def convert_trait(x: str):
"""
Convert a raw trait value to a binary representation (0 or 1), or None if unknown.
However, since trait_row is None, this function will not be used here.
"""
# Placeholder implementation
return None
def convert_age(x: str):
"""
Convert a string like 'age: 37y' to a continuous numeric value (e.g., 37).
Return None if parsing fails.
"""
# Split by colon, take the value part, strip and remove 'y' if present
parts = x.split(':')
if len(parts) < 2:
return None
val = parts[1].strip()
val = val.replace('y', '').strip()
try:
return float(val)
except ValueError:
return None
def convert_gender(x: str):
"""
Convert a raw gender value to binary (female=0, male=1). Return None if unknown.
However, since gender_row is None, this function will not be used here.
"""
# Placeholder implementation
return None
# 3. Save Metadata (Initial filtering)
is_trait_available = (trait_row is not None)
is_usable = 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
# Since trait_row is None, we skip this step (the instructions say to skip if trait_row is None).
# 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])
# These identifiers (e.g., A_19_P00315452) appear to be probe IDs rather than standard human gene symbols.
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
# Based on the reviewer's feedback, it appears that the annotation file does not contain
# a column with "A_19_P..." probe IDs that match the row indices in gene_data. The "ID"
# column in gene_annotation shows entries like "(+)E1A_r60_1", which do not match "A_19_P..."
# probe IDs. Therefore, the mapping will likely produce an empty or nearly empty DataFrame.
# In a real workflow, we would ideally obtain the correct annotation file that contains
# matching probe identifiers. For now, we'll proceed with the current annotation data,
# noting that it may yield no usable mapping.
print(
"Warning: No column in gene_annotation matches the 'A_19_P...' probe IDs. "
"Mapping will likely result in an empty gene expression DataFrame."
)
# 1. We'll continue using 'ID' for the probe column and 'GENE_SYMBOL' for the gene symbol column,
# even though they likely won't match the gene_data row indices.
mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GENE_SYMBOL')
# 2. Convert probe-level measurements to gene-level measurements.
gene_data = apply_gene_mapping(gene_data, mapping_df)
# Display shape for diagnostic purposes
print("Resulting gene_data shape after mapping:", gene_data.shape)
import os
# STEP 7
# 1. Normalize the gene expression data to standard gene symbols.
normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
normalized_gene_data.to_csv(out_gene_data_file)
print("Normalized gene expression data saved to:", out_gene_data_file)
# 2. Check if clinical data exists (trait was available) before attempting to link.
if not os.path.exists(out_clinical_data_file):
print("No clinical data file found. Trait is likely unavailable; skipping linking and final data steps.")
# We only have partial data, so perform a non-final validation to record that the dataset is unusable.
is_usable = validate_and_save_cohort_info(
is_final=False,
cohort=cohort,
info_path=json_path,
is_gene_available=True,
is_trait_available=False
)
print("Dataset is not usable or missing trait data. No final data saved.")
else:
# We have clinical data, so proceed with linking and subsequent steps.
selected_clinical_df = pd.read_csv(out_clinical_data_file, header=0)
# 3. Link the clinical and genetic data on sample IDs.
linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data)
# 4. Handle missing values systematically.
df = handle_missing_values(linked_data, trait)
# 5. Determine whether the trait or demographic features are biased; remove biased demographic features.
trait_biased, df = judge_and_remove_biased_features(df, trait)
# 6. Perform final validation with the fully preprocessed dataset.
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=df,
note="Final step with linking, missing-value handling, bias checks."
)
# 7. If the data is usable, save the final linked data.
if is_usable:
df.to_csv(out_data_file)
print(f"Final linked data saved to: {out_data_file}")
else:
print("Dataset is not usable or severely biased. No final data saved.")