# Path Configuration from tools.preprocess import * # Processing context trait = "Amyotrophic_Lateral_Sclerosis" cohort = "GSE118336" # Input paths in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis" in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE118336" # Output paths out_data_file = "./output/preprocess/1/Amyotrophic_Lateral_Sclerosis/GSE118336.csv" out_gene_data_file = "./output/preprocess/1/Amyotrophic_Lateral_Sclerosis/gene_data/GSE118336.csv" out_clinical_data_file = "./output/preprocess/1/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE118336.csv" json_path = "./output/preprocess/1/Amyotrophic_Lateral_Sclerosis/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 gene expression data is available # Based on the series description (HTA2.0 array - a gene expression microarray), we assume it contains gene expression data. is_gene_available = True # Step 2: Identify availability of trait, age, and gender, and set row indices accordingly # From the sample characteristics dictionary: # { # 0: ['cell type: iPSC-MN'], # 1: ['genotype: FUSWT/WT', 'genotype: FUSWT/H517D', 'genotype: FUSH517D/H517D'], # 2: ['time (differentiation from motor neuron precursor): 2 weeks', 'time (differentiation from motor neuron precursor): 4 weeks'] # } # We interpret row=1 as the ALS status (presence/absence of mutation) => trait trait_row = 1 # There's no clear row for age or gender age_row = None gender_row = None # Step 2.2: Define conversion functions for trait, age, and gender def convert_trait(value: str): # Typically "genotype: something" parts = value.split(':', 1) if len(parts) < 2: return None val = parts[1].strip() # Map genotype to binary: "FUSWT/WT" -> 0 (control), else -> 1 (ALS) if val == "FUSWT/WT": return 0 elif "H517D" in val: return 1 else: return None def convert_age(value: str): # Not applicable here, return None return None def convert_gender(value: str): # Not applicable here, return None return None # Step 3: Initial filtering for dataset usability 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 if trait data is available) if trait_row is not None: # Here we assume 'clinical_data' is already loaded as a pandas DataFrame selected_clinical_df = geo_select_clinical_features( 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 the extracted clinical data preview = preview_df(selected_clinical_df, n=5) print("Clinical Data Preview:", preview) # Save clinical data to CSV 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]) # Based on biomedical knowledge, these "xxx_st" identifiers appear to be probe set IDs (likely from an Affymetrix array), # not human gene symbols. Therefore, they require mapping to gene symbols. # Conclusion: 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 6: Gene Identifier Mapping (Revised) # We will attempt to map the probe identifiers in gene_data (e.g. "2824546_st") to those in the # gene_annotation DataFrame (e.g. "TC01000001.hg.1"). The original attempt concluded there # was no match and skipped the mapping entirely. Here, we'll demonstrate a more thorough check: # 1) Direct match # 2) Partial match by stripping "_st" # If no matches are found, we conclude that no mapping can be performed and retain the original data. # Copy the annotation so we can manipulate it safely annot_df = gene_annotation.copy() # Identify columns to use for probe ID and gene assignment (gene symbol or similar). probe_col = 'ID' gene_col = 'gene_assignment' # Create the mapping DataFrame mapping_df = get_gene_mapping( annotation=annot_df, prob_col=probe_col, gene_col=gene_col ) # 1) Direct match between expression index and annotation ID: expr_ids = set(gene_data.index) annot_ids = set(mapping_df['ID']) common_ids = expr_ids.intersection(annot_ids) if len(common_ids) > 0: # Some probes match directly; proceed with standard mapping print("Direct matches found. Proceeding with gene symbol mapping using apply_gene_mapping...") gene_data = apply_gene_mapping(gene_data, mapping_df) else: # 2) Attempt partial match: removing '_st' from expression IDs before checking print("No direct matches found. Attempting partial match by stripping '_st'...") # Create a dictionary to map stripped IDs -> original IDs stripped_to_orig = {} for idx in gene_data.index: stripped = idx.replace('_st', '').strip() stripped_to_orig[stripped] = idx # Re-check intersection new_expr_ids = set(stripped_to_orig.keys()) common_stripped = new_expr_ids.intersection(annot_ids) if len(common_stripped) > 0: print("Partial matches found. Proceeding with gene symbol mapping...") # Temporarily rename expression DataFrame index to the stripped version gene_data_tmp = gene_data.copy() gene_data_tmp.index = gene_data_tmp.index.map(lambda x: x.replace('_st', '').strip()) # Perform mapping with apply_gene_mapping gene_data_mapped = apply_gene_mapping(gene_data_tmp, mapping_df) # We revert the index to some user-friendly format (e.g., the gene symbols returned) # but "apply_gene_mapping" already sets the new DataFrame's index to gene symbols. gene_data = gene_data_mapped else: # 3) Confirm no mapping possible print("No direct or partial matches found. No reliable way to map these probe IDs.") print("Retaining the original gene_data DataFrame without mapping.") # Display final shape and top rows print("Final gene_data shape:", gene_data.shape) print(gene_data.head(5)) # STEP 7: Data Normalization and Linking # 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}") # 2. Link the clinical and genetic data on sample IDs linked_data = geo_link_clinical_genetic_data(selected_clinical_df, 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, # We do have a trait column 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.")