# Path Configuration from tools.preprocess import * # Processing context trait = "Eczema" cohort = "GSE123088" # Input paths in_trait_dir = "../DATA/GEO/Eczema" in_cohort_dir = "../DATA/GEO/Eczema/GSE123088" # Output paths out_data_file = "./output/preprocess/1/Eczema/GSE123088.csv" out_gene_data_file = "./output/preprocess/1/Eczema/gene_data/GSE123088.csv" out_clinical_data_file = "./output/preprocess/1/Eczema/clinical_data/GSE123088.csv" json_path = "./output/preprocess/1/Eczema/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. Decide if the dataset contains gene expression data is_gene_available = True # Based on the description, it appears to be gene expression (not miRNA or methylation). # 2. Determine availability (row indices) and define data type conversions for trait, age, and gender trait_row = 1 # The row with "primary diagnosis: ATOPIC_ECZEMA" among multiple diagnoses age_row = 3 # The row containing multiple entries of "age: XX" gender_row = 2 # The row that includes "Sex: Male" or "Sex: Female" def convert_trait(x: str) -> Optional[int]: """ Convert trait-related string to binary (0 or 1). We consider 'ATOPIC_ECZEMA' (case-insensitive) as 1, all other entries as 0. """ # Split by colon to isolate the actual value parts = x.split(':', 1) if len(parts) < 2: return None val = parts[1].strip().lower() if 'eczema' in val: return 1 return 0 def convert_age(x: str) -> Optional[float]: """ Convert age-related string to a floating/continuous value. """ parts = x.split(':', 1) if len(parts) < 2: return None val = parts[1].strip() try: return float(val) except ValueError: return None def convert_gender(x: str) -> Optional[int]: """ Convert gender string to binary (Female=0, Male=1). """ parts = x.split(':', 1) if len(parts) < 2: return None val = parts[1].strip().lower() if val == 'male': return 1 elif val == 'female': return 0 return None # 3. Initial filtering and saving metadata 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 if trait data is available if trait_row is not None: # Assume 'clinical_data' DataFrame is loaded from a previous step selected_clinical = 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 selected clinical features preview_output = preview_df(selected_clinical, n=5, max_items=200) print("Preview of extracted clinical features:", preview_output) # Save clinical features to CSV selected_clinical.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 provided gene identifiers, they appear to be numeric rather than standard human gene symbols. # Therefore, gene symbol mapping is required. 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 6: Gene Identifier Mapping # We'll use Entrez IDs as our gene identifiers without discarding numeric IDs. # The key fix is to carefully join the expression DataFrame with the mapping DataFrame on their shared ID index. prob_col = 'ID' gene_col = 'ENTREZ_GENE_ID' # 1. Obtain a mapping DataFrame (probe -> Entrez ID). mapping_df = get_gene_mapping(gene_annotation, prob_col=prob_col, gene_col=gene_col).copy() def apply_entrez_id_mapping(expression_df: pd.DataFrame, map_df: pd.DataFrame) -> pd.DataFrame: # Keep only probes present in expression_df map_df = map_df[map_df['ID'].isin(expression_df.index)].copy() map_df.rename(columns={gene_col: 'Gene'}, inplace=True) # Each probe maps to exactly one Entrez ID in this dataset map_df['num_genes'] = 1 map_df.set_index('ID', inplace=True) # Join on the expression_df index (probe IDs) merged_df = expression_df.join(map_df, how='inner') # Expression columns are the sample columns expr_cols = expression_df.columns # Divide each probe's expression by the number of mapped genes merged_df[expr_cols] = merged_df[expr_cols].div(merged_df['num_genes'].replace(0, 1), axis=0) # Sum contributions for each gene gene_expression_df = merged_df.groupby('Gene')[expr_cols].sum() return gene_expression_df # 2. Apply our custom mapping function to get gene-level expression data gene_data = apply_entrez_id_mapping(gene_data, mapping_df) # 3. Inspect the final shape and a sample of the gene index print("Mapped gene_data shape:", gene_data.shape) print("Sample of mapped gene_data index:", list(gene_data.index[:10])) 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) Reconstruct the clinical DataFrame so that it has row indices for "Eczema", "Age", "Gender", # and sample IDs as columns, matching the library's expected format. # Since in Step 2 we used 'index=False' when saving the CSV, we must parse the file accordingly. tmp_clin = pd.read_csv(out_clinical_data_file, header=None) # The first row in tmp_clin should contain the sample IDs. Make them column headers. tmp_clin.columns = tmp_clin.iloc[0] # Remove that row from the DataFrame tmp_clin = tmp_clin.iloc[1:].copy() # Now tmp_clin has shape (3, number_of_samples), # so assign the index to [trait, "Age", "Gender"]: tmp_clin.index = [trait, "Age", "Gender"] selected_clinical_df = tmp_clin # 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 any trait_biased, final_data = judge_and_remove_biased_features(final_data, trait) # 6) 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="Trait data successfully extracted and reformatted." ) # 7) If usable, save final linked data if is_usable: final_data.to_csv(out_data_file)