Liu-Hy's picture
Add files using upload-large-folder tool
4144951 verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Underweight"
cohort = "GSE130563"
# Input paths
in_trait_dir = "../DATA/GEO/Underweight"
in_cohort_dir = "../DATA/GEO/Underweight/GSE130563"
# Output paths
out_data_file = "./output/preprocess/3/Underweight/GSE130563.csv"
out_gene_data_file = "./output/preprocess/3/Underweight/gene_data/GSE130563.csv"
out_clinical_data_file = "./output/preprocess/3/Underweight/clinical_data/GSE130563.csv"
json_path = "./output/preprocess/3/Underweight/cohort_info.json"
# Get file paths
soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)
# Get background info and clinical data
background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)
# Print shape and first few rows to verify data
print("Background Information:")
print(background_info)
print("\nClinical Data Shape:", clinical_data.shape)
print("\nFirst few rows of Clinical Data:")
print(clinical_data.head())
print("\nSample Characteristics:")
# Get dictionary of unique values per row
unique_values_dict = get_unique_values_by_row(clinical_data)
for row, values in unique_values_dict.items():
print(f"\n{row}:")
print(values)
# 1. Gene Expression Data Availability
is_gene_available = True # Based on background info, this is gene expression data from muscle biopsies
# 2.1 Data Availability
trait_row = 3 # bw loss data available in row 3
age_row = 4 # age data available in row 4
gender_row = 1 # gender data available in row 1 as "Sex"
# 2.2 Data Type Conversion Functions
def convert_trait(val):
# Extract value after colon
if ':' in val:
val = val.split(':')[1].strip()
# Convert to binary based on >= 5% weight loss criteria mentioned in background
try:
if val == '0':
return 0
elif val == 'n.d. (not determined)':
return None
else:
weight_loss = float(val)
return 1 if weight_loss >= 5 else 0
except:
return None
def convert_age(val):
# Extract age value after colon
if ':' in val:
val = val.split(':')[1].strip()
try:
return float(val)
except:
return None
def convert_gender(val):
# Extract gender value after colon and convert F->0, M->1
if ':' in val:
val = val.split(':')[1].strip()
if val == 'F':
return 0
elif val == 'M':
return 1
return None
# 3. Save Initial 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
clinical_features = 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 extracted features
print(preview_df(clinical_features))
# Save clinical data
clinical_features.to_csv(out_clinical_data_file)
# Extract gene expression data from matrix file
genetic_data = get_genetic_data(matrix_file_path)
# Print first 20 row IDs
print("First 20 gene/probe IDs:")
print(list(genetic_data.index[:20]))
# These identifiers appear to be microarray probe IDs (suffix '_at' is characteristic of Affymetrix arrays)
# rather than standard human gene symbols. They will need to be mapped to gene symbols.
requires_gene_mapping = True
# Extract gene annotation from SOFT file with broader prefix filtering
gene_annotation = get_gene_annotation(soft_file_path, prefixes=['!', '#'])
# Display all column names
print("All annotation columns:")
print(list(gene_annotation.columns))
# Preview first few rows of annotation data
print("\nGene annotation preview (first few rows):")
print(gene_annotation.head())
# Extract platform annotation data by excluding series and sample sections
gene_annotation = get_gene_annotation(soft_file_path, prefixes=['!Series', '!Sample', '^'])
# Print details about annotation data for debugging
print("Gene annotation preview:")
print(gene_annotation.head())
print("\nAnnotation shape:", gene_annotation.shape)
print("\nAnnotation columns:", list(gene_annotation.columns))
# Based on column names, get mapping between probes and genes
mapping_data = get_gene_mapping(gene_annotation, prob_col='ID_REF', gene_col='Gene Symbol')
# Print mapping data preview
print("\nMapping data preview:")
print(mapping_data.head())
print("\nMapping data shape:", mapping_data.shape)
# Apply mapping to convert probe-level data to gene-level data
gene_data = apply_gene_mapping(genetic_data, mapping_data)
# Preview results
print("\nFirst 20 gene symbols:")
print(list(gene_data.index[:20]))
print("\nShape of gene expression data:")
print(gene_data.shape)
# Save gene expression data
gene_data.to_csv(out_gene_data_file)
# Look for platform annotation file
platform_files = [f for f in os.listdir(in_cohort_dir) if 'annot' in f.lower()]
platform_file_path = os.path.join(in_cohort_dir, platform_files[0])
# Read platform annotation file
platform_annotation = pd.read_csv(platform_file_path, sep='\t', skiprows=0, low_memory=False)
# Display column names to find relevant ones
print("Platform annotation columns:")
print(list(platform_annotation.columns))
# Preview platform annotation data
print("\nPlatform annotation preview:")
print(platform_annotation[['probeset_id', 'gene_assignment']].head())
# Create mapping dataframe between probe IDs and gene symbols
mapping_data = platform_annotation[['probeset_id', 'gene_assignment']].copy()
mapping_data = mapping_data.rename(columns={'probeset_id': 'ID', 'gene_assignment': 'Gene'})
# Print mapping data shape and preview
print("\nMapping data shape:", mapping_data.shape)
print("\nMapping data preview:")
print(mapping_data.head())
# Try different prefix combinations to find the platform annotation section
gene_annotation = get_gene_annotation(soft_file_path, prefixes=['!Platform'])
# Print annotation details for debugging
print("Gene annotation preview:")
print(gene_annotation.head())
print("\nAnnotation columns:", list(gene_annotation.columns))
# Since we can't directly access platform annotation, let's try to obtain probe ID and gene symbol mapping
# by examining the expression matrix header
probe_ids = genetic_data.index.tolist()
mapping_data = pd.DataFrame({'ID': probe_ids})
mapping_data['Gene'] = mapping_data['ID'].str.extract(r'([A-Za-z0-9]+)_at')
# Print mapping data preview
print("\nMapping data preview:")
print(mapping_data.head())
print("\nMapping data shape:", mapping_data.shape)
# Apply mapping to convert probe-level to gene-level data
gene_data = apply_gene_mapping(genetic_data, mapping_data)
print("\nGene data preview:")
print(gene_data.head())
print("\nGene data shape:", gene_data.shape)
# Save gene data
gene_data.to_csv(out_gene_data_file)
# Extract gene expression data from matrix file
genetic_data = get_genetic_data(matrix_file_path)
# Print first 20 row IDs
print("First 20 gene/probe IDs:")
print(list(genetic_data.index[:20]))
# Get platform annotation from SOFT file
prefixes_to_exclude = ['!Series', '!Sample', '^SERIES', '^SAMPLE']
gene_annotation = get_gene_annotation(soft_file_path, prefixes=prefixes_to_exclude)
# Extract probe-gene mapping section
probe_gene_lines = []
in_mapping = False
with gzip.open(soft_file_path, 'rt') as f:
for line in f:
if '!platform_table_begin' in line:
in_mapping = True
continue
elif '!platform_table_end' in line:
break
elif in_mapping:
probe_gene_lines.append(line)
# Create dataframe from probe-gene mapping
if probe_gene_lines:
mapping_df = pd.read_csv(io.StringIO(''.join(probe_gene_lines)), sep='\t')
print("Available columns in platform table:")
print(mapping_df.columns)
print("\nFirst few rows of platform table:")
print(mapping_df.head())
# Extract probe ID and gene columns using available column names
id_column = [col for col in mapping_df.columns if 'id' in col.lower()][0]
gene_column = [col for col in mapping_df.columns if 'gene' in col.lower()][0]
mapping_data = pd.DataFrame({
'ID': mapping_df[id_column],
'Gene': mapping_df[gene_column]
})
else:
# If no mapping found, use the probe IDs as gene names
probe_ids = genetic_data.index.tolist()
mapping_data = pd.DataFrame({'ID': probe_ids, 'Gene': [x.split('_')[0] for x in probe_ids]})
# Convert probe-level to gene-level measurements
gene_data = apply_gene_mapping(genetic_data, mapping_data)
# 1. Normalize gene symbols
gene_data = normalize_gene_symbols_in_index(gene_data)
os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
gene_data.to_csv(out_gene_data_file)
print("\nGene data shape (normalized gene-level):", gene_data.shape)
# 2. Link clinical and genetic data
selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)
# 3. Handle missing values
linked_data = handle_missing_values(linked_data, trait)
# 4. Check for bias in features
is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Validate and save dataset metadata
note = "Dataset contains gene expression data from rectus abdominis muscle biopsies, along with weight loss and clinical information from pancreatic cancer patients."
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=is_trait_biased,
df=linked_data,
note=note
)
# 6. Save linked data if usable
if is_usable:
os.makedirs(os.path.dirname(out_data_file), exist_ok=True)
linked_data.to_csv(out_data_file)