# Path Configuration from tools.preprocess import * # Processing context trait = "Amyotrophic_Lateral_Sclerosis" cohort = "GSE26927" # Input paths in_trait_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis" in_cohort_dir = "../DATA/GEO/Amyotrophic_Lateral_Sclerosis/GSE26927" # Output paths out_data_file = "./output/preprocess/1/Amyotrophic_Lateral_Sclerosis/GSE26927.csv" out_gene_data_file = "./output/preprocess/1/Amyotrophic_Lateral_Sclerosis/gene_data/GSE26927.csv" out_clinical_data_file = "./output/preprocess/1/Amyotrophic_Lateral_Sclerosis/clinical_data/GSE26927.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) # 1. Gene Expression Data Availability is_gene_available = True # Based on the series summary, this dataset uses Illumina whole genome array. # 2. Variable Availability # Checking the sample characteristics dictionary, we found: # - trait_row = 0, because row 0 has "disease: ..." entries including "Amyotrophic lateral sclerosis". # - age_row = 2, because row 2 has "age at death (in years): ..." entries. # - gender_row = 1, because row 1 has "gender: M" or "gender: F". trait_row = 0 age_row = 2 gender_row = 1 # 2.2 Data Type Conversions def convert_trait(value: str) -> int: """ Convert disease field to binary indicating ALS (1) vs non-ALS (0). Unknown values are converted to None. Example input: "disease: Amyotrophic lateral sclerosis" """ parts = value.split(":") if len(parts) < 2: return None disease_str = parts[1].strip().lower() if "amyotrophic lateral sclerosis" in disease_str: return 1 else: return 0 def convert_age(value: str) -> Optional[float]: """ Convert age field to continuous (float). Unknown values are converted to None. Example input: "age at death (in years): 70" """ parts = value.split(":") if len(parts) < 2: return None age_str = parts[1].strip() try: return float(age_str) except ValueError: return None def convert_gender(value: str) -> Optional[int]: """ Convert gender field to binary: female -> 0, male -> 1. Unknown values are converted to None. Example input: "gender: M" """ parts = value.split(":") if len(parts) < 2: return None gender_str = parts[1].strip().lower() if gender_str == 'f': return 0 elif gender_str == 'm': return 1 else: return None # 3. Save Metadata (initial filtering) is_trait_available = (trait_row is not None) is_final = False # initial filtering validate_and_save_cohort_info( is_final=is_final, cohort=cohort, info_path=json_path, is_gene_available=is_gene_available, is_trait_available=is_trait_available ) # 4. Clinical Feature Extraction (only if trait_row is not None) if trait_row is not None: # Assume 'clinical_data' is the DataFrame with sample characteristics loaded from a previous step. 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 and save print("Preview of Selected Clinical Features:", preview_df(selected_clinical_df)) 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, such as 'ILMN_10000', are Illumina microarray probe IDs rather than standard gene symbols. # Hence, they require mapping to 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. Identify the corresponding columns for probe ID and gene symbol in 'gene_annotation'. # From the previews, 'ID' matches the probe identifiers used in the gene expression data (e.g., 'ILMN_10000'), # and 'SYMBOL' stores the gene symbols. probe_col = 'ID' symbol_col = 'SYMBOL' # 2. Get a mapping dataframe from 'gene_annotation'. mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=symbol_col) # 3. Convert probe-level measurements to gene-level expression data using 'apply_gene_mapping'. # This handles the many-to-many relationships by dividing expression across genes and summing contributions per gene. gene_data = apply_gene_mapping(gene_data, mapping_df) # For verification, let's output a small preview of the resulting gene_data: shape and first few gene indices. print("Mapped gene_data shape:", gene_data.shape) print("First 10 genes after mapping:", gene_data.index[:10].to_list()) # 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}") # 2. Read the previously saved clinical data and correctly restore the row/column structure # After step 2, the CSV has 3 rows (trait, Age, Gender) and columns = sample IDs (header=0). # We can directly set the new index labels because we know row 0 = trait, row 1 = Age, row 2 = Gender. selected_clinical_df = pd.read_csv(out_clinical_data_file, header=0) if selected_clinical_df.shape[0] == 3: selected_clinical_df.index = [trait, 'Age', 'Gender'] else: print("Warning: The clinical data does not have 3 rows as expected. Check the saved CSV format.") # 3. Link clinical and gene expression data on sample IDs linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data) # 4. Handle missing values (drop samples missing trait, drop high-missing genes/samples, impute remaining) linked_data = handle_missing_values(linked_data, trait_col=trait) # 5. Check for biased features (trait, age, gender) and remove biased demographic features trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait) # 6. Final quality validation and metadata saving 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="Final data pipeline completed." ) # 7. Save final linked data if usable if is_usable: linked_data.to_csv(out_data_file) print(f"Saved final linked data to {out_data_file}") else: print("Dataset is not usable for trait-based association. Skipping final output.")