Liu-Hy's picture
Add files using upload-large-folder tool
54d4d57 verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Huntingtons_Disease"
cohort = "GSE71220"
# Input paths
in_trait_dir = "../DATA/GEO/Huntingtons_Disease"
in_cohort_dir = "../DATA/GEO/Huntingtons_Disease/GSE71220"
# Output paths
out_data_file = "./output/preprocess/3/Huntingtons_Disease/GSE71220.csv"
out_gene_data_file = "./output/preprocess/3/Huntingtons_Disease/gene_data/GSE71220.csv"
out_clinical_data_file = "./output/preprocess/3/Huntingtons_Disease/clinical_data/GSE71220.csv"
json_path = "./output/preprocess/3/Huntingtons_Disease/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(soft_file_path) # Changed to use soft_file_path
# Get unique values for each clinical feature
unique_values_dict = get_unique_values_by_row(clinical_data)
# Print background information
print("Background Information:")
print(background_info)
print("\nSample Characteristics:")
print(json.dumps(unique_values_dict, indent=2))
# Gene expression data availability
is_gene_available = True # Yes, uses Affymetrix Human Gene 1.1 ST microarray
# Variable row indices and conversion functions
trait_row = 1 # disease field contains trait info
age_row = 2 # age field contains numeric age
gender_row = 3 # Sex field contains gender info
def convert_trait(value: str) -> int:
"""Convert disease status to binary."""
if ':' in value:
value = value.split(':')[1].strip()
if value == 'COPD':
return 1 # Case
elif value == 'Control':
return 0 # Control
return None
def convert_age(value: str) -> float:
"""Convert age to float."""
if ':' in value:
value = value.split(':')[1].strip()
try:
return float(value)
except:
return None
def convert_gender(value: str) -> int:
"""Convert gender to binary."""
if ':' in value:
value = value.split(':')[1].strip()
if value.upper() == 'F':
return 0
elif value.upper() == 'M':
return 1
return None
# Save metadata about dataset usability
validate_and_save_cohort_info(is_final=False,
cohort=cohort,
info_path=json_path,
is_gene_available=is_gene_available,
is_trait_available=True)
# Extract clinical features if trait data available
if trait_row is not None:
selected_clinical_df = 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 extracted data
preview = preview_df(selected_clinical_df)
# Save clinical data
selected_clinical_df.to_csv(out_clinical_data_file)
# Extract gene expression data from the matrix file
genetic_data = get_genetic_data(matrix_file_path)
# Print first 20 row IDs
print("First 20 row IDs:")
print(genetic_data.index[:20].tolist())
# The identifiers appear to be microarray probe IDs
# They are numeric IDs that don't match standard human gene symbol format
# Gene mapping will be required to convert these to proper gene symbols
requires_gene_mapping = True
# Extract gene annotation data from SOFT file
gene_metadata = get_gene_annotation(soft_file_path)
# Display information about the annotation data
print("Column names:")
print(gene_metadata.columns.tolist())
print("\nPreview of first few rows:")
print(json.dumps(preview_df(gene_metadata), indent=2))
# Extract gene mapping from annotation data
# 'ID' column matches probe IDs in expression data
# 'gene_assignment' column contains gene symbols in format "... // SYMBOL // ..."
mapping_data = get_gene_mapping(gene_metadata, 'ID', 'gene_assignment')
# Extract gene symbols from gene_assignment strings using regular expressions
def extract_gene_symbols(text: str) -> List[str]:
if pd.isna(text) or text == '---':
return []
# Find gene symbols between double slashes, excluding common annotations
genes = []
segments = text.split('//')
for i in range(1, len(segments)-1, 3): # Symbol is every 3rd segment starting at index 1
symbol = segments[i].strip()
if symbol not in ['---', 'ENSEMBL', 'RefSeq', 'GenBank']:
genes.append(symbol)
return list(set(genes)) # Remove duplicates
# Apply extraction and explode to get one row per probe-gene pair
mapping_data['Gene'] = mapping_data['gene_assignment'].apply(extract_gene_symbols)
# Map probes to genes and get gene expression data
gene_data = apply_gene_mapping(genetic_data, mapping_data)
# Normalize gene symbols to handle aliases/variants
gene_data = normalize_gene_symbols_in_index(gene_data)
# Preview results
print("Preview of gene expression data:")
print("Number of genes:", len(gene_data.index))
print("First 5 gene symbols:", gene_data.index[:5].tolist())