Liu-Hy's picture
Add files using upload-large-folder tool
187fbda verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Atrial_Fibrillation"
cohort = "GSE41177"
# Input paths
in_trait_dir = "../DATA/GEO/Atrial_Fibrillation"
in_cohort_dir = "../DATA/GEO/Atrial_Fibrillation/GSE41177"
# Output paths
out_data_file = "./output/preprocess/1/Atrial_Fibrillation/GSE41177.csv"
out_gene_data_file = "./output/preprocess/1/Atrial_Fibrillation/gene_data/GSE41177.csv"
out_clinical_data_file = "./output/preprocess/1/Atrial_Fibrillation/clinical_data/GSE41177.csv"
json_path = "./output/preprocess/1/Atrial_Fibrillation/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 stating "microarray analysis revealed ...", indicating gene expression data.
# 2. Variable Availability and Data Type Conversion
# 2.1 Data Availability
# Trait (Atrial_Fibrillation): All patients have AF (persistent AF), so there's no variation (constant). Hence, not available.
trait_row = None
# Age: Multiple unique age values are found in row 2.
age_row = 2
# Gender: Multiple unique gender values are found in row 1.
gender_row = 1
# 2.2 Data Type Conversion
def convert_trait(x: str) -> Optional[int]:
"""
Convert any given value of the trait 'Atrial_Fibrillation' to a binary value.
However, here it's not used because trait_row is None for this dataset (constant trait).
Example logic shown for completeness.
"""
if not x or ':' not in x:
return None
# If data indicated presence of AF, assign 1, otherwise 0.
# (In this dataset, it's constant, so this function is effectively unused.)
return 1
def convert_age(x: str) -> Optional[float]:
"""
Convert age string 'age: XXY' to a float.
If unknown, return None.
"""
if not x or ':' not in x:
return None
value = x.split(':', 1)[1].strip() # e.g. "62Y"
value = value.replace('Y', '').strip()
if not value.isdigit():
return None
return float(value)
def convert_gender(x: str) -> Optional[int]:
"""
Convert gender string 'gender: male/female' to a binary value:
female -> 0
male -> 1
If unknown, return None.
"""
if not x or ':' not in x:
return None
gender_str = x.split(':', 1)[1].strip().lower()
if 'female' in gender_str:
return 0
if 'male' in gender_str:
return 1
return None
# 3. Save Metadata (Initial filtering)
# Trait data is not available if 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
)
# 4. Clinical Feature Extraction
# Skip if trait_row is None.
if trait_row is not None:
selected_clinical_df = geo_select_clinical_features(
clinical_df=clinical_data,
trait="Atrial_Fibrillation",
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 = preview_df(selected_clinical_df, n=5)
print("Preview of Selected Clinical Features:", preview)
# Save
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])
# These identifiers (e.g., "1007_s_at", "1053_at") are Affymetrix probe IDs rather than standard human gene symbols.
# Hence, we conclude that the data requires gene symbol mapping.
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 the relevant columns in the annotation dataframe:
# - 'ID' holds the same identifiers as gene_data.index (e.g., "1007_s_at")
# - 'Gene Symbol' holds the gene symbols.
# 2. Extract mapping columns:
mapping_df = get_gene_mapping(gene_annotation, prob_col="ID", gene_col="Gene Symbol")
# 3. Convert probe-level measurements to gene-level expression data:
gene_data = apply_gene_mapping(gene_data, mapping_df)
# STEP7
import pandas as pd
# Since trait_row is None, we have no clinical data to link. According to the instructions, we skip linking
# and other steps requiring the trait. We only normalize and save gene data, then perform final validation
# to mark this dataset as not usable (due to missing trait data).
# 1. Normalize the obtained gene data using the NCBI Gene synonym database
normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
normalized_gene_data.to_csv(out_gene_data_file)
# 2. Final quality validation and metadata saving (trait not available).
# Since is_final=True, we must provide dummy values for 'df' and 'is_biased'.
empty_df = pd.DataFrame() # Placeholder DataFrame
is_usable = validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=True, # Gene data is available
is_trait_available=False, # Trait data is not available
is_biased=True, # Mark as biased/unusable since we're missing core trait data
df=empty_df, # Passing an empty df to satisfy function signature
note="No trait data available, skipping clinical linkage. Gene data extracted only."
)
# 3. Since the dataset is not usable, we do not proceed with saving any final linked data.