Liu-Hy's picture
Add files using upload-large-folder tool
f426016 verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Anxiety_disorder"
cohort = "GSE68526"
# Input paths
in_trait_dir = "../DATA/GEO/Anxiety_disorder"
in_cohort_dir = "../DATA/GEO/Anxiety_disorder/GSE68526"
# Output paths
out_data_file = "./output/preprocess/1/Anxiety_disorder/GSE68526.csv"
out_gene_data_file = "./output/preprocess/1/Anxiety_disorder/gene_data/GSE68526.csv"
out_clinical_data_file = "./output/preprocess/1/Anxiety_disorder/clinical_data/GSE68526.csv"
json_path = "./output/preprocess/1/Anxiety_disorder/cohort_info.json"
# STEP 1
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("\nSample Characteristics Dictionary:")
print(sample_characteristics_dict)
# 1. Determine if gene expression data is available
is_gene_available = True # Based on the background info: "Gene expression profiling was carried out ..."
# 2. Determine availability of trait, age, gender, and define conversion functions
# From the dictionary, anxiety is at row 13 and has multiple distinct values.
trait_row = 13
# Age is at row 0, with multiple distinct values.
age_row = 0
# Gender is at row 1, with two distinct values (female: 0 or 1).
gender_row = 1
# Data type conversions:
def convert_trait(value: str):
"""
Convert the anxiety string value after colon to a float (continuous measure).
Returns None if 'missing' or conversion fails.
"""
# Example: "anxiety: 1.4"
try:
val_str = value.split(':', 1)[1].strip()
if val_str.lower() == "missing":
return None
return float(val_str)
except:
return None
def convert_age(value: str):
"""
Convert the age string value after colon to a float (continuous measure).
Returns None if conversion fails.
"""
# Example: "age (yrs): 76"
try:
val_str = value.split(':', 1)[1].strip()
return float(val_str)
except:
return None
def convert_gender(value: str):
"""
Convert the gender string value after colon to binary (female=0, male=1).
The data is stored as 'female: 0' or 'female: 1'.
'female: 1' means the subject is female -> 0
'female: 0' means the subject is male -> 1
Returns None if conversion fails.
"""
try:
val_str = value.split(':', 1)[1].strip()
if val_str == "1":
return 0 # female
elif val_str == "0":
return 1 # male
return None
except:
return None
# 3. Save metadata with 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 if trait_row is not None
if trait_row is not None:
# Assume "clinical_data" is the DataFrame containing sample characteristics
# from a previous step in the pipeline
selected_clinical = 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_df(selected_clinical, n=5, max_items=200)
# Optionally observe the preview (not printing to avoid extra text, but you could if needed)
selected_clinical.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])
# Based on the observed identifiers, some (like "A2BP1", "7A5") appear to be old or non-standard.
# Hence, they likely need to be mapped to official 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))
# STEP: Gene Identifier Mapping
# 1) Identify columns in `gene_annotation` corresponding to probe IDs and gene symbols.
# From the previous preview, "ID" in the gene annotation matches the expression data's IDs,
# and "ORF" appears to hold the same text which we'll treat as the gene symbol column.
# 2) Get the gene mapping dataframe.
mapping_df = get_gene_mapping(annotation=gene_annotation, prob_col='ID', gene_col='ORF')
# 3) Apply mapping to convert probe-level measurements to gene-level expression.
gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
# (Optional) Print basic info to confirm successful mapping.
print("Mapped gene data shape:", gene_data.shape)
print("First 20 mapped gene symbols:", list(gene_data.index[:20]))
# STEP 7: Data Normalization and Linking
import pandas as pd
# 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)
print(f"Saved normalized gene data to {out_gene_data_file}")
# Ensure "selected_clinical" is defined by reading from our previously saved CSV.
temp_df = pd.read_csv(out_clinical_data_file)
# Step 2 extracts trait, age, gender => we expect exactly 3 rows
if temp_df.shape[0] == 3:
temp_df.index = [trait, "Age", "Gender"]
selected_clinical = temp_df
# 2. Link the clinical and genetic data on sample IDs
linked_data = geo_link_clinical_genetic_data(selected_clinical, normalized_gene_data)
# 3. Handle missing values, removing or imputing as instructed
linked_data = handle_missing_values(linked_data, trait)
# 4. Determine whether the trait (and potentially other features) is severely biased.
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Conduct final quality 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=trait_biased,
df=linked_data,
note="Cohort data successfully processed with trait-based analysis."
)
# 6. If the dataset is usable, save the final linked data
if is_usable:
linked_data.to_csv(out_data_file, index=True)
print(f"Saved final linked data to {out_data_file}")
else:
print("The dataset is not usable for trait-based association. Skipping final output.")