# Path Configuration from tools.preprocess import * # Processing context trait = "Endometrioid_Cancer" cohort = "GSE73637" # Input paths in_trait_dir = "../DATA/GEO/Endometrioid_Cancer" in_cohort_dir = "../DATA/GEO/Endometrioid_Cancer/GSE73637" # Output paths out_data_file = "./output/preprocess/1/Endometrioid_Cancer/GSE73637.csv" out_gene_data_file = "./output/preprocess/1/Endometrioid_Cancer/gene_data/GSE73637.csv" out_clinical_data_file = "./output/preprocess/1/Endometrioid_Cancer/clinical_data/GSE73637.csv" json_path = "./output/preprocess/1/Endometrioid_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) import pandas as pd # 1. Determine if gene expression data is available # Based on background info, this dataset uses gene expression for GECA analysis. is_gene_available = True # 2. Identify data availability and define row indices # From the sample characteristics dictionary, histopathology is stored in row 3, # which includes “Endometrioid” among other values (i.e., multiple categories). # There's no mention of age or gender, so age_row and gender_row are None. trait_row = 3 # row containing histopathology with "Endometrioid" age_row = None gender_row = None # 2.2 Define data type conversion functions def convert_trait(value: str): """ Convert histopathology values to binary, indicating whether 'Endometrioid' is present (1) or not (0). Unknown/unexpected values become None. """ parts = value.split(':', 1) if len(parts) == 2: val_str = parts[1].strip().lower() else: val_str = parts[0].strip().lower() # Heuristic: Any mention of 'endometrioid' or 'endometroid' is mapped to 1 # Otherwise, map known terms to 0, else None. if 'endometrioid' in val_str or 'endometroid' in val_str: return 1 elif any(keyword in val_str for keyword in ['serous', 'carcinoma', 'clear cell', 'adenocarcinoma']): return 0 else: return None def convert_age(value: str): # No age data available; return None return None def convert_gender(value: str): # No gender data available; return None return None # 3. Perform initial filtering and 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. If trait_row is available, extract clinical data and save if trait_row is not None: # Suppose 'clinical_data' is the DataFrame that holds the sample characteristics # in the same format as shown in the "Sample Characteristics Dictionary". data_dict = { 0: ['cell type: ovarian cells'], 1: [ 'cell line: COV504', 'cell line: COV362', 'cell line: UWB1.289+BRCA1', 'cell line: OV56', 'cell line: UWB1.289', 'cell line: COV318', 'cell line: NCI/ADR-RES', 'cell line: OVCAR3', 'cell line: OVCAR4', 'cell line: OVCAR8', 'cell line: IGR-OV1', 'cell line: SK-OV-3', 'cell line: OVCAR5', 'cell line: ES-2', 'cell line: TOV-21G', 'cell line: TOV-112D', 'cell line: PEO1', 'cell line: PEO4' ], 2: ['tumor site of origin: Ovarian'], 3: [ 'histopathology: Serous', 'histopathology: Endometrioid', 'histopathology: Poorly differentiated serous', 'histopathology: Undifferentiated carcinoma', 'histopathology: Poorly differentiated carcinoma', 'histopathology: Moderately differentiated carcinoma', 'histopathology: Endometroid with serous/clear cell', 'histopathology: Well-differentiated adenocarcinoma', 'histopathology: Poorly differentiated clear cell', 'histopathology: Clear Cell' ] } # Convert the dictionary to a DataFrame similar to how GEO data often appear clinical_data = pd.DataFrame.from_dict(data_dict, orient='index').fillna('') 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 DataFrame preview_result = preview_df(selected_clinical_df) print("Preview of selected clinical features:", preview_result) # 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 the output, the gene identifiers are numeric (e.g., '1', '2', '3', etc.), # which indicates they are not human gene symbols and likely require mapping. # Therefore: requires_gene_mapping = True # STEP5 import pandas as pd import io # 1. Extract the lines that do NOT start with '^', '!', or '#', but do NOT parse them into a DataFrame yet. annotation_text, _ = filter_content_by_prefix( source=soft_file, prefixes_a=['^', '!', '#'], unselect=True, source_type='file', return_df_a=False, return_df_b=False ) # 2. Manually parse the filtered text into a DataFrame, specifying engine="python" to avoid buffer overflow issues. gene_annotation = pd.read_csv( io.StringIO(annotation_text), delimiter='\t', on_bad_lines='skip', engine='python' ) print("Gene annotation preview:") print(preview_df(gene_annotation)) # STEP: Gene Identifier Mapping # 1. Decide which columns correspond to the gene expression ID and the gene symbol # From the previews, "ID" matches the numeric identifiers in gene_data, # and "GeneSymbol" stores the actual gene symbols. # 2. Get a gene mapping DataFrame mapping_df = get_gene_mapping(gene_annotation, prob_col="ID", gene_col="GeneSymbol") # 3. Convert probe-level measurements to gene-level expression data gene_data = apply_gene_mapping(gene_data, mapping_df) import pandas as pd # STEP7 # 1) Normalize gene symbols and save normalized_gene_data = normalize_gene_symbols_in_index(gene_data) normalized_gene_data.to_csv(out_gene_data_file) # 2) Read back the clinical DataFrame we saved in Step 2. # Since we saved a single row with no header or index, we read with header=None to keep that row as data. selected_clinical_df = pd.read_csv(out_clinical_data_file, header=None) # If the number of columns aligns with the gene expression DataFrame's columns (i.e., same samples), # rename the clinical DataFrame columns accordingly to achieve correct sample alignment. if selected_clinical_df.shape[1] == normalized_gene_data.shape[1]: selected_clinical_df.columns = normalized_gene_data.columns # Set the row index to the trait name (e.g., "Endometrioid_Cancer") selected_clinical_df.index = [trait] # 3) Link the clinical and gene expression data linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data) # 4) Handle missing values using the trait column final_data = handle_missing_values(linked_data, trait_col=trait) # 5) Evaluate bias in the trait (and remove biased demographic features if present) trait_biased, final_data = judge_and_remove_biased_features(final_data, trait) # 6) Final validation. We do have trait data, so set is_trait_available=True 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=final_data, note="Aligned columns in clinical DataFrame to match gene expression samples." ) # 7) If the dataset is deemed usable, save final linked data if is_usable: final_data.to_csv(out_data_file) import pandas as pd # STEP8 # 1) Normalize gene symbols and save normalized_gene_data = normalize_gene_symbols_in_index(gene_data) normalized_gene_data.to_csv(out_gene_data_file) # 2) Read back the clinical DataFrame saved in Step 2 (one or more rows × number_of_samples columns, no header). selected_clinical_df = pd.read_csv(out_clinical_data_file, header=None) # In case there are empty columns (e.g., trailing commas), drop them selected_clinical_df = selected_clinical_df.dropna(axis=1, how='all') # If the number of columns matches the number of samples (columns) in the gene data, rename to align sample IDs if selected_clinical_df.shape[1] == normalized_gene_data.shape[1]: selected_clinical_df.columns = normalized_gene_data.columns else: print(f"Warning: Mismatch in shape. Clinical data has {selected_clinical_df.shape[1]} columns, " f"while gene data has {normalized_gene_data.shape[1]} columns. Linking may fail.") # Set the row index to the trait, so we can keep track of it selected_clinical_df.index = [trait] # 2) Link the clinical and gene expression data linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data) # 3) Handle missing values using the trait column final_data = handle_missing_values(linked_data, trait_col=trait) # 4) Evaluate bias in the trait (and remove biased demographic features if present) trait_biased, final_data = judge_and_remove_biased_features(final_data, trait) # 5) Final validation 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=final_data, note="Ensured clinical and gene sample columns were aligned if possible." ) # 6) If the dataset is usable, save the final linked data if is_usable: final_data.to_csv(out_data_file)