Liu-Hy's picture
Add files using upload-large-folder tool
61e25af verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Obesity"
cohort = "GSE123086"
# Input paths
in_trait_dir = "../DATA/GEO/Obesity"
in_cohort_dir = "../DATA/GEO/Obesity/GSE123086"
# Output paths
out_data_file = "./output/preprocess/3/Obesity/GSE123086.csv"
out_gene_data_file = "./output/preprocess/3/Obesity/gene_data/GSE123086.csv"
out_clinical_data_file = "./output/preprocess/3/Obesity/clinical_data/GSE123086.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
# Yes, from series design we can see RNA microarray was used
is_gene_available = True
# 2.1 Data Availability
# Trait data is in Feature 1 under "primary diagnosis"
trait_row = 1
# Age data is spread across Features 3 and 4
age_row = 3
# Gender data is in Feature 2 under "Sex"
gender_row = 2
# 2.2 Data Type Conversion Functions
def convert_trait(x):
# Extract value after colon and convert to binary
if pd.isna(x):
return None
value = x.split(': ')[1]
if value == 'OBESITY':
return 1
elif value == 'HEALTHY_CONTROL':
return 0
return None
def convert_age(x):
# Extract age value as continuous
if pd.isna(x):
return None
if not x.startswith('age:'):
return None
try:
return float(x.split(': ')[1])
except:
return None
def convert_gender(x):
# Convert gender to binary (female=0, male=1)
if pd.isna(x):
return None
if not x.startswith('Sex:'):
return None
value = x.split(': ')[1]
if value == 'Female':
return 0
elif value == 'Male':
return 1
return None
# 3. 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. Clinical Feature Extraction
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
)
print("Preview of extracted clinical features:")
print(preview_df(clinical_features))
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)
# Looking at the identifiers - they are numeric values (1,2,3,9,10 etc)
# These appear to be probe/feature IDs rather than gene symbols
# Therefore mapping to gene symbols will be required
requires_gene_mapping = True
# Get file paths using library function
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# For SOFT files with platform annotations, we need to get rows not starting with '!'
# but also not containing just numeric IDs and entrez genes
gene_annotation = pd.read_csv(soft_file, compression='gzip', sep='\t', header=None,
comment='!', on_bad_lines='skip')
# Find rows with detailed platform annotations (containing gene symbols)
annotation_starts = False
annotation_lines = []
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
for line in f:
if "!platform_table_begin" in line:
annotation_starts = True
# Get the header line
header = next(f).strip()
annotation_lines.append(header)
continue
if annotation_starts:
if "!platform_table_end" in line:
break
annotation_lines.append(line.strip())
# Convert annotation lines to dataframe
annotation_content = '\n'.join(annotation_lines)
gene_annotation = pd.read_csv(io.StringIO(annotation_content), sep='\t')
# Preview annotation data
print("Gene annotation shape:", gene_annotation.shape)
print("\nAll column names:")
print(gene_annotation.columns.tolist())
print("\nFirst few rows:")
print(gene_annotation.head().to_string())
print("\nNumber of non-null values in each column:")
print(gene_annotation.count())
# Print example rows showing ID and gene symbol columns
print("\nSample rows showing the ID and gene symbol mapping:")
symbol_col = [col for col in gene_annotation.columns if 'symbol' in col.lower()][0]
print(gene_annotation[['ID', symbol_col]].head(10))
# Extract complete platform annotation table from SOFT file
platform_lines = []
annotation_starts = False
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
for line in f:
if line.startswith('^PLATFORM'):
platform_lines.append(line)
elif line.startswith('!Platform_data_row_count'):
platform_lines.append(line)
elif line.startswith('!Platform_table_begin'):
annotation_starts = True
header = next(f).strip()
platform_lines.append(header)
continue
elif annotation_starts:
if line.startswith('!Platform_table_end'):
break
platform_lines.append(line.strip())
# Parse platform annotation content
platform_content = '\n'.join(platform_lines)
gene_annotation = pd.read_csv(io.StringIO(platform_content), sep='\t', comment='!', skiprows=2)
# Create mapping DataFrame using ID and gene symbol
mapping_df = gene_annotation[['ID', 'GB_ACC']].copy()
mapping_df = mapping_df.rename(columns={'GB_ACC': 'Gene'})
# Clean gene symbols - split on spaces/semicolons and take first value
mapping_df['Gene'] = mapping_df['Gene'].astype(str).apply(lambda x: x.split(';')[0].split()[0])
mapping_df = mapping_df.dropna()
# Apply gene mapping to convert probe expression to gene expression
gene_data = apply_gene_mapping(gene_data, mapping_df)
# Normalize gene symbols using the provided function
gene_data = normalize_gene_symbols_in_index(gene_data)
# Save gene expression data
gene_data.to_csv(out_gene_data_file)
# Preview the mapped gene data
print("Shape of gene expression data after mapping:", gene_data.shape)
print("\nFirst few mapped genes and their expression values:")
print(gene_data.head())
# Get file paths using library function
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Try to peek at the SOFT file contents first
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
# Read first few lines to understand file structure
print("First 20 lines of SOFT file:")
for i, line in enumerate(f):
if i < 20:
print(line.strip())
else:
break
# Reset file pointer
f.seek(0)
# Look for the platform table section
print("\nPlatform table header:")
for line in f:
if "!Platform_table_begin" in line:
# Print the next line which should be the header
print(next(f).strip())
break
# Now extract annotation data using a simpler method - get lines between table markers
annotation_lines = []
table_started = False
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
for line in f:
if "!Platform_table_begin" in line:
header = next(f).strip()
annotation_lines.append(header)
table_started = True
continue
if table_started:
if "!Platform_table_end" in line:
break
annotation_lines.append(line.strip())
# Convert to dataframe
annotation_text = '\n'.join(annotation_lines)
gene_annotation = pd.read_csv(io.StringIO(annotation_text), sep='\t')
# Preview annotation data
print("\nAnnotation data shape:", gene_annotation.shape)
print("\nColumn names:")
print(gene_annotation.columns.tolist())
print("\nFirst few rows:")
print(gene_annotation.head())
# 1. Let's examine SOFT file content first to identify correct gene identifier columns
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
for line in f:
if '!Platform_table_begin' in line:
header = next(f).strip()
print("Platform table header:")
print(header)
print("\nFirst few data rows:")
for i in range(5):
print(next(f).strip())
break
# Extract gene metadata using library function
gene_metadata = get_gene_annotation(soft_file)
# Print available columns to identify gene symbol column
print("\nAvailable annotation columns:")
print(gene_metadata.columns.tolist())
print("\nPreview of gene metadata:")
print(gene_metadata.head())
# Get gene expression data
gene_data = get_genetic_data(matrix_file)
# Print shape and preview of expression data before mapping
print("\nShape of gene expression data before mapping:", gene_data.shape)
print("\nPreview of gene expression data before mapping:")
print(gene_data.head())
# Use library function to get gene annotation from SOFT file
gene_metadata = get_gene_annotation(soft_file)
# Create mapping DataFrame using ID and ENTREZ_GENE_ID
mapping_df = gene_metadata[['ID', 'ENTREZ_GENE_ID']].copy()
mapping_df = mapping_df.rename(columns={'ENTREZ_GENE_ID': 'Gene'})
# Clean and prepare mapping data
mapping_df['ID'] = mapping_df['ID'].astype(str)
mapping_df['Gene'] = mapping_df['Gene'].astype(str)
mapping_df = mapping_df.dropna()
# Apply gene mapping to convert probe expression to gene expression
gene_data = apply_gene_mapping(gene_data, mapping_df)
# Normalize gene symbols
gene_data = normalize_gene_symbols_in_index(gene_data)
# Save processed gene expression data
gene_data.to_csv(out_gene_data_file)
print("\nShape of gene expression data after mapping:", gene_data.shape)
print("\nFirst few mapped genes and their expression values:")
print(gene_data.head())
# Get file paths using library function
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Extract gene annotation from SOFT file and get meaningful data
gene_annotation = get_gene_annotation(soft_file)
# Preview gene annotation data
print("Gene annotation shape:", gene_annotation.shape)
print("\nGene annotation preview:")
print(preview_df(gene_annotation))
print("\nNumber of non-null values in each column:")
print(gene_annotation.count())
# Print example rows showing the mapping information columns
print("\nSample mapping columns ('ID' and 'GENE_SYMBOL'):")
print("\nFirst 5 rows:")
print(gene_annotation[['ID', 'GENE_SYMBOL']].head().to_string())
print("\nNote: Gene mapping will use:")
print("'ID' column: Probe identifiers")
print("'GENE_SYMBOL' column: Contains gene symbol information")