# Path Configuration from tools.preprocess import * # Processing context trait = "Eczema" cohort = "GSE120899" # Input paths in_trait_dir = "../DATA/GEO/Eczema" in_cohort_dir = "../DATA/GEO/Eczema/GSE120899" # Output paths out_data_file = "./output/preprocess/1/Eczema/GSE120899.csv" out_gene_data_file = "./output/preprocess/1/Eczema/gene_data/GSE120899.csv" out_clinical_data_file = "./output/preprocess/1/Eczema/clinical_data/GSE120899.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) # STEP 2: Dataset Analysis and Clinical Feature Extraction # 1. Decide whether gene expression data is available is_gene_available = True # Based on the presence of mRNA expression data in the background info # 2. Determine data availability and define row indices # From the sample characteristics dictionary, row 1 has "lesional skin", "non-lesional skin", "Normal" # We can interpret this as "Eczema vs. Normal" (case vs. control). Hence: trait_row = 1 age_row = None gender_row = None # 2.2 Define data-type conversion functions def convert_trait(value: str): # First, handle non-string or NaN cases if not isinstance(value, str): return None parts = value.split(':', 1) if len(parts) < 2: return None val = parts[1].strip().lower() if val == 'normal': return 0 elif val in ['lesional skin', 'non-lesional skin']: return 1 else: return None def convert_age(value: str): if not isinstance(value, str): return None return None # Not available in this dataset def convert_gender(value: str): if not isinstance(value, str): return None return None # Not available in this dataset # 3. Perform initial filtering and save 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 (only if trait data is available) if trait_row is not None: import pandas as pd temp_dict = { 0: ['batch_date: 2016-02-01', 'batch_date: 2016-01-12', 'batch_date: 2016-01-20', 'batch_date: 2016-01-25'], 1: ['tissue: lesional skin', 'tissue: non-lesional skin', 'tissue: Normal'], 2: ['week: 0', 'week: 12', 'week: NA'], 3: ['treatment: APRMST-30', 'treatment: Placebo', 'treatment: APRMST-40', 'treatment: NA'], 4: ['patient id: 31007', 'patient id: 61001', 'patient id: 61007', 'patient id: 61013'] } clinical_data = pd.DataFrame(dict([(k, pd.Series(v)) for k, v in temp_dict.items()])).T extracted_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 = preview_df(extracted_clinical, n=5, max_items=200) print("Preview of extracted clinical features:", preview) extracted_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 probe IDs (e.g., "1007_s_at"), they are Affymetrix probe set IDs, not human gene symbols. # Hence, they require mapping to gene symbols. print("\nrequires_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 match the probe identifiers in the expression data # (i.e., "ID") and the column for gene symbols (i.e., "Gene Symbol"). probe_col = "ID" symbol_col = "Gene Symbol" # 2. Extract the corresponding mapping between probe IDs and gene symbols. mapping_df = get_gene_mapping(gene_annotation, prob_col=probe_col, gene_col=symbol_col) # 3. Apply the mapping to convert probe-level measurements into gene-level expression data. gene_data = apply_gene_mapping(gene_data, mapping_df) # (Optional) Preview the resulting gene_data to verify the shape and a few rows. print("Mapped gene_data shape:", gene_data.shape) print("Preview of mapped gene_data:\n", gene_data.head()) 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 the clinical data with the default header, then re-align columns with gene_data. selected_clinical_df = pd.read_csv(out_clinical_data_file) # Expect shape (1, Ncolumns) # Ensure we only take the first row in case there are unexpected extra rows if selected_clinical_df.shape[0] > 1: selected_clinical_df = selected_clinical_df.iloc[:1, :] num_clin_cols = selected_clinical_df.shape[1] num_gene_cols = len(normalized_gene_data.columns) # Match columns up to the smaller dimension if num_clin_cols <= num_gene_cols: new_col_names = list(normalized_gene_data.columns[:num_clin_cols]) else: # If clinical has more columns, constrain to gene_data's column count selected_clinical_df = selected_clinical_df.iloc[:, :num_gene_cols] new_col_names = list(normalized_gene_data.columns) selected_clinical_df.columns = new_col_names # Assign the single row index to the trait selected_clinical_df.index = [trait] # 3) Link clinical and gene expression data linked_data = geo_link_clinical_genetic_data(selected_clinical_df, normalized_gene_data) # 4) Handle missing values in the linked data final_data = handle_missing_values(linked_data, trait_col=trait) # 5) Evaluate bias in the trait and remove any biased features (like Age or Gender) if needed trait_biased, final_data = judge_and_remove_biased_features(final_data, trait) # 6) 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=trait_biased, df=final_data, note="Adjusted clinical data column alignment to match gene expression sample IDs." ) # 7) If the dataset is usable, save it if is_usable: final_data.to_csv(out_data_file)