Liu-Hy's picture
Add files using upload-large-folder tool
f2fc1fc verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Retinoblastoma"
cohort = "GSE110811"
# Input paths
in_trait_dir = "../DATA/GEO/Retinoblastoma"
in_cohort_dir = "../DATA/GEO/Retinoblastoma/GSE110811"
# Output paths
out_data_file = "./output/preprocess/3/Retinoblastoma/GSE110811.csv"
out_gene_data_file = "./output/preprocess/3/Retinoblastoma/gene_data/GSE110811.csv"
out_clinical_data_file = "./output/preprocess/3/Retinoblastoma/clinical_data/GSE110811.csv"
json_path = "./output/preprocess/3/Retinoblastoma/cohort_info.json"
# Get file paths
soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)
# Get background info and clinical data
background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)
print("Background Information:")
print(background_info)
print("\nSample Characteristics:")
# Get dictionary of unique values per row
unique_values_dict = get_unique_values_by_row(clinical_data)
for row, values in unique_values_dict.items():
print(f"\n{row}:")
print(values)
# 1. Gene Expression Data Availability
# Yes, this is microarray gene expression data analyzing retinoblastoma tumors
is_gene_available = True
# 2.1 Data Availability
# trait_row=1: anaplasia severity is available in row 1
# age_row=None: age information not available
# gender_row=None: gender information not available
trait_row = 1
age_row = None
gender_row = None
# 2.2 Data Type Conversion Functions
def convert_trait(value):
"""Convert anaplasia severity to binary: 1 for severe, 0 for mild/moderate"""
if pd.isna(value):
return None
value = value.split(': ')[1].strip().lower()
if value == 'severe':
return 1
elif value in ['mild', 'moderate']:
return 0
return None
# No age/gender conversion functions needed since data not available
convert_age = None
convert_gender = None
# 3. Save Metadata
is_trait_available = trait_row is not None
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
# Extract clinical features since trait data is available
clinical_df = geo_select_clinical_features(clinical_data,
trait='Anaplasia',
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 extracted features
preview_df(clinical_df)
# Save clinical data
clinical_df.to_csv(out_clinical_data_file)
# Get gene expression data from matrix file
genetic_data = get_genetic_data(matrix_file_path)
# Examine data structure
print("Data structure and head:")
print(genetic_data.head())
print("\nShape:", genetic_data.shape)
print("\nFirst 20 row IDs (gene/probe identifiers):")
print(list(genetic_data.index)[:20])
# Get a few column names to verify sample IDs
print("\nFirst 5 column names:")
print(list(genetic_data.columns)[:5])
# Check gene identifiers
# The row IDs are numeric codes (16657445, etc.) which appear to be probe IDs
# They are not standard human gene symbols (which are typically alphanumeric like BRCA1)
# Therefore mapping to gene symbols is required
requires_gene_mapping = True
# Extract gene annotation data, trying to find the gene symbol section
# More lines start with # in the SOFT file contain the metadata we need
prefixes = ['^', '!'] # Remove '#' from prefix filter to keep those lines
gene_annotation = get_gene_annotation(soft_file_path)
# Check if there are any columns containing gene symbols or names in the SOFT file
def check_string_columns(df):
"""Helper function to check string columns that might contain gene information"""
for col in df.columns:
sample_values = df[col].astype(str).str.contains('[A-Za-z]').sum()
if sample_values > 0:
print(f"\nSample values from {col}:")
print(df[col].dropna().astype(str).unique()[:10])
print("Gene annotation structure:")
print(gene_annotation.head())
print("\nChecking columns for potential gene information:")
check_string_columns(gene_annotation)
# Let's read the raw SOFT file content to examine its structure
import gzip
print("\nExamining SOFT file structure:")
with gzip.open(soft_file_path, 'rt') as f:
# Print first 20 lines that aren't empty
lines = [line.strip() for line in f if line.strip()][:20]
for line in lines:
print(line)
# 1. Use GB_ACC column for gene mapping since it contains RefSeq/GenBank accessions that can be mapped to gene symbols
mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='GB_ACC')
# 2. Convert probe-level data to gene-level data using the mapping
# The apply_gene_mapping function will extract gene symbols from accessions
gene_data = apply_gene_mapping(genetic_data, mapping_df)
# 3. Preview data structure and save
print("\nGene expression data after mapping:")
print(gene_data.head())
print("\nShape:", gene_data.shape)
print("\nFirst few gene symbols:", list(gene_data.index)[:5])
# Save gene data
gene_data.to_csv(out_gene_data_file)
# Since gene mapping failed in previous step, we will retry using gene annotation data
# Filter gene annotation to include only entries with NM_ or NR_ accessions
# These are protein-coding and non-coding RNA transcripts that should map to genes
filtered_annotation = gene_annotation[gene_annotation['GB_ACC'].str.contains('NM_|NR_', na=False)]
# Create mapping with probe IDs and accessions
mapping_df = get_gene_mapping(filtered_annotation, prob_col='ID', gene_col='GB_ACC')
# Convert probe-level data to gene-level data using the filtered mapping
gene_data = apply_gene_mapping(genetic_data, mapping_df)
# Normalize gene symbols to standardize format
gene_data = normalize_gene_symbols_in_index(gene_data)
gene_data.to_csv(out_gene_data_file)
# Reload clinical data that was processed earlier
selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
# Link clinical and genetic data
linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)
# Handle missing values systematically
linked_data = handle_missing_values(linked_data, "Anaplasia")
# Check for bias in trait and demographic features
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, "Anaplasia")
# Final validation and information saving
note = "Dataset contains gene expression data from primary human retinoblastoma samples profiled with Affymetrix microarray."
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=note
)
# Save linked data only if usable
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
linked_data.to_csv(out_data_file)