# Path Configuration from tools.preprocess import * # Processing context trait = "Bladder_Cancer" cohort = "GSE138118" # Input paths in_trait_dir = "../DATA/GEO/Bladder_Cancer" in_cohort_dir = "../DATA/GEO/Bladder_Cancer/GSE138118" # Output paths out_data_file = "./output/preprocess/1/Bladder_Cancer/GSE138118.csv" out_gene_data_file = "./output/preprocess/1/Bladder_Cancer/gene_data/GSE138118.csv" out_clinical_data_file = "./output/preprocess/1/Bladder_Cancer/clinical_data/GSE138118.csv" json_path = "./output/preprocess/1/Bladder_Cancer/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 # Based on the background "Expression profile...", it is likely gene-expression data # 2. Variable Availability and Data Type Conversion # Determine row indices trait_row = 0 # Maps to "stage at sample..." which indicates healthy vs various tumor stages age_row = 2 # This row consistently has age information (mostly "age: XX") gender_row = None # No gender info found # Define conversion functions def convert_trait(value: Any) -> Optional[int]: """ Convert the 'stage at sample' info into a binary variable: 0 => Healthy/Neg 1 => any 'G' stage None => unknown or missing """ if not isinstance(value, str): return None parts = value.split(':', maxsplit=1) if len(parts) == 2: val_str = parts[1].strip().lower() else: val_str = value.strip().lower() if 'healthy' in val_str or 'neg' in val_str: return 0 elif 'g' in val_str: return 1 else: return None def convert_age(value: Any) -> Optional[float]: """ Convert strings of the form 'age: XX' to float. If it doesn't match, returns None. """ if not isinstance(value, str): return None parts = value.split(':', maxsplit=1) if len(parts) == 2 and 'age' in parts[0].lower(): try: return float(parts[1].strip()) except ValueError: return None return None def convert_gender(value: Any) -> Optional[int]: """ No gender data available, so always return None. """ return None # 3. Save Metadata (Initial Filtering) 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 (only if trait_row is not None) 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 the extracted clinical features preview_data = preview_df(selected_clinical_df) print("Preview of clinical features:", preview_data) # Save clinical data as 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]) # Observing the gene identifiers, they appear to be numeric probe IDs rather than standard human gene symbols. # Hence, they require mapping to known 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 columns in 'gene_annotation' that correspond to probe IDs and gene symbols # From the preview, it appears 'ID' matches the probe IDs in the expression data (gene_data.index), # and 'gene_assignment' contains gene symbols in a messy string. # 2. Get the gene mapping dataframe by extracting these two columns mapping_df = get_gene_mapping(annotation=gene_annotation, prob_col='ID', gene_col='gene_assignment') # 3. Apply the gene mapping to convert from probe-level to gene-level data gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df) # STEP 7 import pandas as pd # 1) Normalize gene symbols with synonym information normalized_gene_data = normalize_gene_symbols_in_index(gene_data) normalized_gene_data.to_csv(out_gene_data_file) # 2) Link the clinical and genetic data # After saving the clinical DataFrame with index=False, the row names (e.g., "Bladder_Cancer") might contain # trailing spaces or mismatches upon re-loading. Strip them before merging. clinical_df = pd.read_csv(out_clinical_data_file, index_col=0) clinical_df.index = clinical_df.index.str.strip() linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data) # 3) Handle missing values (remove samples lacking trait, remove genes or samples with excess missingness, impute) linked_data = handle_missing_values(linked_data, trait_col=trait) # 4) Check if the trait (and optional covariates) is severely biased is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait=trait) # 5) Final 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=is_biased, df=linked_data, note="Data processed successfully." ) # 6) If the linked data is deemed usable, save it for downstream analysis if is_usable: linked_data.to_csv(out_data_file, index=False) # STEP 8 import pandas as pd # 1) Normalize the gene symbols with synonym information normalized_gene_data = normalize_gene_symbols_in_index(gene_data) normalized_gene_data.to_csv(out_gene_data_file) # 2) Link clinical and genetic data # Load the clinical data so that rows = ["Bladder_Cancer","Age","Gender",...], columns = sample IDs. clinical_df = pd.read_csv(out_clinical_data_file, header=0, index_col=0) clinical_df.index = clinical_df.index.map(str).str.strip() linked_data = geo_link_clinical_genetic_data(clinical_df, normalized_gene_data) # 3) Handle missing values linked_data = handle_missing_values(linked_data, trait_col=trait) # 4) Evaluate bias in the trait and remove any biased covariates is_biased, linked_data = judge_and_remove_biased_features(linked_data, trait=trait) # 5) Final 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=is_biased, df=linked_data, note="Data processed successfully." ) # 6) Save the final linked data if it is usable if is_usable: linked_data.to_csv(out_data_file, index=False)