# Path Configuration from tools.preprocess import * # Processing context trait = "Obesity" cohort = "GSE158237" # Input paths in_trait_dir = "../DATA/GEO/Obesity" in_cohort_dir = "../DATA/GEO/Obesity/GSE158237" # Output paths out_data_file = "./output/preprocess/3/Obesity/GSE158237.csv" out_gene_data_file = "./output/preprocess/3/Obesity/gene_data/GSE158237.csv" out_clinical_data_file = "./output/preprocess/3/Obesity/clinical_data/GSE158237.csv" json_path = "./output/preprocess/3/Obesity/cohort_info.json" # Get file paths soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir) # Extract background info and clinical data background_info, clinical_data = get_background_and_clinical_data(matrix_file) # Get unique values per clinical feature sample_characteristics = get_unique_values_by_row(clinical_data) # Print background info print("Dataset Background Information:") print(f"{background_info}\n") # Print sample characteristics print("Sample Characteristics:") for feature, values in sample_characteristics.items(): print(f"Feature: {feature}") print(f"Values: {values}\n") # 1. Gene Expression Data Availability # Based on series title and summary mentioning RNA extraction and transcriptomics, # this dataset likely contains gene expression data is_gene_available = True # 2. Variable Availability and Data Type Conversion # 2.1 Data Availability trait_row = 10 # BMI data in Feature 10 age_row = 1 # Age data in Feature 1 gender_row = 2 # Sex data in Feature 2 # 2.2 Data Type Conversion Functions def convert_trait(value): # Convert BMI value to binary (0 for non-obese, 1 for obese) if pd.isna(value): return None try: bmi = float(value.split(': ')[1]) return 1 if bmi >= 30 else 0 # Standard obesity threshold except: return None def convert_age(value): # Convert age to continuous value if pd.isna(value): return None try: age = float(value.split(': ')[1]) return age except: return None def convert_gender(value): # Convert sex to binary (0 for female, 1 for male) if pd.isna(value): return None try: sex = int(value.split(': ')[1]) return 1 if sex == 1 else 0 # Assuming Sex:1 is male and Sex:2 is female except: return None # 3. Save Metadata # Conduct initial filtering validate_and_save_cohort_info(is_final=False, cohort=cohort, info_path=json_path, is_gene_available=is_gene_available, is_trait_available=(trait_row is not None)) # 4. Clinical Feature Extraction # Since trait_row is not None, extract clinical features if trait_row is not None: clinical_features = 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 the extracted features preview = preview_df(clinical_features) print("Preview of clinical features:", preview) # Save to CSV clinical_features.to_csv(out_clinical_data_file) # Extract gene expression data from matrix file gene_data = get_genetic_data(matrix_file) # Print first 20 row IDs and shape of data to help debug print("Shape of gene expression data:", gene_data.shape) print("\nFirst few rows of data:") print(gene_data.head()) print("\nFirst 20 gene/probe identifiers:") print(gene_data.index[:20]) # Inspect a snippet of raw file to verify identifier format import gzip with gzip.open(matrix_file, 'rt', encoding='utf-8') as f: lines = [] for i, line in enumerate(f): if "!series_matrix_table_begin" in line: # Get the next 5 lines after the marker for _ in range(5): lines.append(next(f).strip()) break print("\nFirst few lines after matrix marker in raw file:") for line in lines: print(line) # From the output, we can see the identifiers appear to be numeric probe IDs (e.g. 16657436) # rather than human gene symbols (which would look like BRCA1, TP53 etc) # These need to be mapped to gene symbols for biological interpretation requires_gene_mapping = True # Get file paths using library function soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir) # Extract gene annotation from SOFT file # Use different prefix filters to capture platform annotation with gene symbols gene_annotation = filter_content_by_prefix(soft_file, prefixes_a=['!Platform_table_begin'], unselect=False, source_type='file', return_df_a=True)[0] # Preview gene annotation data print("Gene annotation shape:", gene_annotation.shape) print("\nGene annotation columns:", list(gene_annotation.columns)) print("\nGene annotation preview:") print(preview_df(gene_annotation)) # Print non-null values for each column to help identify useful columns print("\nNumber of non-null values in each column:") print(gene_annotation.count()) # Print example rows showing ID and gene symbol columns print("\nExample rows with ID and gene symbol information:") print(gene_annotation[['ID', 'Symbol']].head(10).to_string()) # Get file paths using library function soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir) # First examine the raw SOFT file content to locate platform annotation section import gzip platform_start = False header_line = None first_data_line = None with gzip.open(soft_file, 'rt') as f: for line in f: if '!Platform_table_begin' in line: platform_start = True # Get the next two lines (header and first data) header_line = next(f).strip() first_data_line = next(f).strip() break print("Header line found:") print(header_line) print("\nFirst data line example:") print(first_data_line) # Extract platform annotation data from io import StringIO platform_data = [] platform_start = False with gzip.open(soft_file, 'rt') as f: for line in f: if '!Platform_table_begin' in line: platform_start = True continue elif '!Platform_table_end' in line: break elif platform_start: platform_data.append(line.strip()) # Convert to dataframe gene_annotation = pd.read_csv(StringIO('\n'.join(platform_data)), sep='\t') # Preview gene annotation data print("\nGene annotation shape:", gene_annotation.shape) print("\nGene annotation columns:", gene_annotation.columns.tolist()) print("\nFirst few rows preview:") print(gene_annotation.head().to_string()) # Look for columns that might contain gene symbols symbol_candidates = [col for col in gene_annotation.columns if any(term in col.lower() for term in ['gene', 'symbol', 'entrez', 'refseq'])] print("\nPotential gene symbol columns:", symbol_candidates) from io import StringIO # First inspect the SOFT file content to understand structure import gzip print("Examining SOFT file content...") with gzip.open(soft_file, 'rt') as f: for line in f: # Look for platform annotation sections that might contain gene info if "!Platform_table_begin" in line: header = next(f).strip() print("\nFound platform table with header:") print(header) print("\nFirst few data lines:") for _ in range(5): print(next(f).strip()) break # Try extracting gene annotation using different prefix patterns gene_metadata_str = filter_content_by_prefix(soft_file, prefixes_a=['^', '#'], unselect=True, source_type='file', return_df_a=False)[0] # Process the metadata string to find the section with gene annotations annotation_lines = [] capture = False for line in gene_metadata_str.split('\n'): if 'Reporter Database Entry [gene symbol]' in line: # Found the start of gene symbol annotations capture = True continue if capture and line.strip(): if line.startswith('!'): # End of section break annotation_lines.append(line) if annotation_lines: # Convert captured lines to DataFrame gene_metadata = pd.read_csv(StringIO('\n'.join(annotation_lines)), sep='\t') print("\nAvailable columns in gene annotation data:") print(gene_metadata.columns.tolist()) # Create mapping dataframe using ID and gene symbol columns mapping_df = get_gene_mapping(gene_metadata, prob_col='ID', gene_col='GENE_SYMBOL') # Apply gene mapping to convert probe-level data to gene-level data gene_data = apply_gene_mapping(gene_data, mapping_df) # Print shape information to confirm successful mapping print(f"\nShape of mapped gene expression data: {gene_data.shape}") print("\nFirst few gene symbols:") print(gene_data.index[:10]) else: print("\nNo gene symbol annotation section found in the SOFT file.") # Load the clinical data that was successfully saved earlier selected_clinical = pd.read_csv(out_clinical_data_file, index_col=0) # Create minimal df with just clinical features for validation minimal_df = selected_clinical.copy() # Check for biased features with just clinical data is_biased, minimal_df = judge_and_remove_biased_features(minimal_df, trait) # Save validation info with minimal df is_usable = validate_and_save_cohort_info( is_final=True, cohort=cohort, info_path=json_path, is_gene_available=False, # Gene mapping failed is_trait_available=True, is_biased=is_biased, df=minimal_df, note="Failed to extract gene symbol annotations from SOFT file" ) # Do not save linked data since processing was unsuccessful