Liu-Hy's picture
Add files using upload-large-folder tool
a0747da verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Longevity"
cohort = "GSE16717"
# Input paths
in_trait_dir = "../DATA/GEO/Longevity"
in_cohort_dir = "../DATA/GEO/Longevity/GSE16717"
# Output paths
out_data_file = "./output/preprocess/3/Longevity/GSE16717.csv"
out_gene_data_file = "./output/preprocess/3/Longevity/gene_data/GSE16717.csv"
out_clinical_data_file = "./output/preprocess/3/Longevity/clinical_data/GSE16717.csv"
json_path = "./output/preprocess/3/Longevity/cohort_info.json"
# Step 1: Get file paths
soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)
# Step 2: Extract background info and clinical data from matrix file
background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)
# Step 3: Get dictionary of unique values for each clinical feature
unique_values_dict = get_unique_values_by_row(clinical_data)
# Step 4: Print background info and sample characteristics
print("Dataset Background Information:")
print("-" * 80)
print(background_info)
print("\nSample Characteristics:")
print("-" * 80)
print(json.dumps(unique_values_dict, indent=2))
# 1. Gene Expression Data Availability
# Yes, this is a gene expression study based on the background information
is_gene_available = True
# 2.1 Data Availability
# Key 0 contains "group" info that can determine longevity status
trait_row = 0
# Key 2 contains age information
age_row = 2
# Key 1 contains gender information
gender_row = 1
# 2.2 Data Type Conversion Functions
def convert_trait(value: str) -> Optional[int]:
"""Convert long-lived status to binary."""
if not isinstance(value, str):
return None
value = value.split(": ")[-1].lower().strip()
if "long-lived" in value:
return 1
elif "control" in value:
return 0
elif "offspring" in value:
return 0
return None
def convert_age(value: str) -> Optional[float]:
"""Convert age string to float."""
if not isinstance(value, str):
return None
try:
# Extract numeric value before "years"
age = float(value.split(": ")[-1].split(" ")[0])
return age
except:
return None
def convert_gender(value: str) -> Optional[int]:
"""Convert gender to binary (0=female, 1=male)."""
if not isinstance(value, str):
return None
value = value.split(": ")[-1].lower().strip()
if value == "female":
return 0
elif value == "male":
return 1
return None
# 3. 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=trait_row is not None)
# 4. Clinical Feature Extraction
clinical_df = geo_select_clinical_features(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 clinical data
preview = preview_df(clinical_df)
# Save clinical data
clinical_df.to_csv(out_clinical_data_file)
# 1. Extract gene expression data from matrix file
genetic_data = get_genetic_data(matrix_file_path)
# 2. Print first 20 row IDs
print("First 20 gene/probe identifiers:")
print(genetic_data.index[:20])
# The identifiers appear to be Affymetrix probe IDs rather than human gene symbols
# They are numerical values that need to be mapped to gene symbols
requires_gene_mapping = True
# 1. Extract gene annotation data from SOFT file
gene_annotation = get_gene_annotation(soft_file_path)
# 2. Preview annotation data
print("Column names and first few values in gene annotation data:")
print(preview_df(gene_annotation))
# First check all available columns in the annotation data
print("Available columns in the gene annotation data:")
print(gene_annotation.columns.tolist())
# Check if there are more sections in the SOFT file
print("\nChecking for additional annotation sections in SOFT file...")
with gzip.open(soft_file_path, 'rt') as f:
first_1000_lines = ''.join([next(f) for _ in range(1000)])
print(first_1000_lines)
# Based on the SOFT file review, we need to modify gene annotation extraction
# Let's extract annotation with a different set of prefixes to get more comprehensive data
gene_annotation = get_gene_annotation(soft_file_path, prefixes=['#', '!'])
# Check columns in new annotation data
print("\nColumns in expanded annotation data:")
print(gene_annotation.columns.tolist())
print("\nSample records:")
print(gene_annotation.head().to_dict('records'))
# For now, we'll save the intermediate probe-level data
# This indicates the dataset needs additional processing to map to human gene symbols
genetic_data.to_csv(out_gene_data_file)
print("\nINFO: The gene identifiers in this dataset require additional processing steps to map to human gene symbols.")
print("The probe-level data has been saved for further processing.")
# 1. Normalize gene symbols and save gene data
normalized_gene_data = normalize_gene_symbols_in_index(genetic_data)
os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
normalized_gene_data.to_csv(out_gene_data_file)
# 2. Link clinical and genetic data
linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data)
# 3. Handle missing values
linked_data = handle_missing_values(linked_data, trait)
# 4. Check for biased features and remove biased demographic ones
is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Final validation and save 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=is_biased,
df=linked_data,
note="Longevity status based on group classification (long-lived sibs vs controls)"
)
# 6. Save linked data if usable
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
linked_data.to_csv(out_data_file)