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 = "GSE60190"
# Input paths
in_trait_dir = "../DATA/GEO/Anxiety_disorder"
in_cohort_dir = "../DATA/GEO/Anxiety_disorder/GSE60190"
# Output paths
out_data_file = "./output/preprocess/1/Anxiety_disorder/GSE60190.csv"
out_gene_data_file = "./output/preprocess/1/Anxiety_disorder/gene_data/GSE60190.csv"
out_clinical_data_file = "./output/preprocess/1/Anxiety_disorder/clinical_data/GSE60190.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)
# Step 1: Determine if this dataset likely contains gene expression data
# From the background info, it's clear that this is a microarray-based gene expression dataset.
is_gene_available = True
# Step 2: Identify data availability for trait, age, and gender
# and define the corresponding row indices and conversion functions.
# ---------------------------------------------------------------
# 2.1 Data Availability
# We do not see any explicit or strongly inferable row key for "Anxiety_disorder" in the sample characteristics,
# so we consider the trait unavailable.
trait_row = None
# We see age data in key=5 with multiple unique numeric values, so it's available.
age_row = 5
# We see gender data in key=7 ("Sex: F" or "Sex: M"), so it's available.
gender_row = 7
# 2.2 Data Type Conversion
def convert_trait(x: str):
"""
Since trait_row is None (trait not available), this function is not actually used.
We provide a placeholder that returns None.
"""
return None
def convert_age(x: str):
"""
Convert age from a string like 'age: 30.5' to a float.
Unknown or invalid values become None.
"""
try:
# Split at colon, take right side, strip spaces
val_str = x.split(':', 1)[1].strip()
return float(val_str)
except:
return None
def convert_gender(x: str):
"""
Convert gender from a string like 'Sex: F' or 'Sex: M' to 0 or 1.
Unknown values become None.
"""
try:
val_str = x.split(':', 1)[1].strip().upper()
if val_str in ['F', 'FEMALE']:
return 0
elif val_str in ['M', 'MALE']:
return 1
else:
return None
except:
return None
# Step 3: Conduct initial filtering on dataset usability
# Trait data availability depends on whether trait_row is None.
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
)
# Step 4: Clinical Feature Extraction
# Only do this step if trait_row is not None. In this case, trait_row is None, so we skip it.
# 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 examining the provided gene identifiers, they are Illumina probe IDs (e.g., ILMN_1343291),
# which are not standard human gene symbols. Therefore, they require mapping to the correct 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))
# STEP: Gene Identifier Mapping
# 1. Decide which column in the gene annotation stores the probe IDs matching those in the gene expression data ("ID"),
# and which column stores the gene symbols ("Symbol").
probe_id_col = "ID"
gene_symbol_col = "Symbol"
# 2. Get a gene mapping dataframe by extracting these two columns.
gene_mapping_df = get_gene_mapping(
annotation=gene_annotation,
prob_col=probe_id_col,
gene_col=gene_symbol_col
)
# 3. Convert probe-level measurements to gene-level measurements by applying the mapping.
gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=gene_mapping_df)
# 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}")
# Since trait_row was None, we have no trait data; skip linking clinical data or trait-based steps.
# 5. Conduct final quality validation
# The library mandates that when is_final=True, we must provide both df and is_biased as non-None.
# Here, we have no trait data, so we pass an empty DataFrame and set is_biased=False (arbitrary boolean),
# which will mark the dataset as not usable for trait-based analysis.
empty_df = pd.DataFrame()
is_trait_available = False
is_usable = validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=True, # We did confirm gene expression is available
is_trait_available=is_trait_available,
is_biased=False, # Arbitrary boolean to satisfy the function requirement
df=empty_df,
note="Trait data is unavailable for this cohort."
)
# 6. If the dataset were usable, we would save final linked data, but here it will not be usable.
if is_usable:
print("Dataset unexpectedly marked as usable; no trait present.")
else:
print("No trait data, so the dataset is not usable for trait-based analysis. Skipping final output.")