Liu-Hy's picture
Add files using upload-large-folder tool
a0b62f5 verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Arrhythmia"
cohort = "GSE53622"
# Input paths
in_trait_dir = "../DATA/GEO/Arrhythmia"
in_cohort_dir = "../DATA/GEO/Arrhythmia/GSE53622"
# Output paths
out_data_file = "./output/preprocess/3/Arrhythmia/GSE53622.csv"
out_gene_data_file = "./output/preprocess/3/Arrhythmia/gene_data/GSE53622.csv"
out_clinical_data_file = "./output/preprocess/3/Arrhythmia/clinical_data/GSE53622.csv"
json_path = "./output/preprocess/3/Arrhythmia/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")
# Step 1: Gene expression data availability
# Based on the series title and summary, this is a lncRNA microarray study
# lncRNA is a type of gene expression data, so it is suitable
is_gene_available = True
# Step 2.1: Identify data rows
trait_row = 10 # Arrhythmia data in row 10
age_row = 1 # Age data in row 1
gender_row = 2 # Gender data in row 2
# Step 2.2: Define conversion functions
def convert_trait(x):
# Convert arrhythmia values to binary (no:0, yes:1)
if not isinstance(x, str):
return None
value = x.split(': ')[-1].lower()
if value == 'no':
return 0
elif value == 'yes':
return 1
return None
def convert_age(x):
# Convert age to float
if not isinstance(x, str):
return None
try:
return float(x.split(': ')[-1])
except:
return None
def convert_gender(x):
# Convert gender to binary (female:0, male:1)
if not isinstance(x, str):
return None
value = x.split(': ')[-1].lower()
if value == 'female':
return 0
elif value == 'male':
return 1
return None
# Step 3: Save metadata for initial filtering
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)
# Step 4: Extract clinical features since trait data is available
if trait_row is not None:
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 extracted features
print("Preview of extracted clinical features:")
print(preview_df(selected_clinical))
# Save to file
selected_clinical.to_csv(out_clinical_data_file)
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# 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)
# Based on the gene identifiers showing simple numeric values (1,2,24,25,26 etc)
# and the very high number of rows (71584), these appear to be probe IDs from a
# microarray platform rather than direct gene symbols. They will need to be mapped
# to standard gene symbols.
requires_gene_mapping = True
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Extract gene annotation from SOFT file by filtering out lines with prefixes
gene_annotation = get_gene_annotation(soft_file)
# Print platform information and key columns
print("Platform Information:")
with gzip.open(soft_file, 'rt') as f:
for line in f:
if '!Platform_title' in line or '!Platform_geo_accession' in line:
print(line.strip())
# Download and read platform annotation file from GEO
import urllib.request
import io
# Download GPL18109 platform annotation
platform_url = "https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?mode=raw&is_datatable=true&acc=GPL18109&id=18415&db=GeoDb_blob118"
response = urllib.request.urlopen(platform_url)
platform_data = response.read().decode('utf-8')
# Read into dataframe
platform_df = pd.read_csv(io.StringIO(platform_data), sep='\t', comment='#')
print("\nPlatform Annotation Preview:")
print("Column names:", platform_df.columns.tolist())
print("\nFirst few rows as dictionary:")
print(preview_df(platform_df))
# Store platform dataframe as our gene annotation
gene_annotation = platform_df
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Read SOFT file content
with gzip.open(soft_file, 'rt') as f:
platform_content = f.read()
# Extract the platform table section
table_start = platform_content.find("!platform_table_begin")
table_end = platform_content.find("!platform_table_end")
platform_table = platform_content[table_start:table_end]
# Read platform annotation into dataframe
gene_annotation = pd.read_csv(io.StringIO(platform_table), sep='\t', skiprows=1)
# Print column names to identify mapping columns
print("Available columns:", gene_annotation.columns.tolist())
print("\nSample rows:")
print(gene_annotation.head())
# Get mapping between probe IDs and gene symbols
mapping_df = get_gene_mapping(gene_annotation, prob_col='ID_REF', gene_col='GENE')
# Apply mapping to convert probe data to gene expression data
gene_data = apply_gene_mapping(expression_df=gene_data, mapping_df=mapping_df)
# Print shape and preview to verify conversion worked
print("\nShape of mapped gene expression data:", gene_data.shape)
print("\nFirst few rows after mapping:")
print(gene_data.head())
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Extract gene annotation from SOFT file
gene_annotation = get_gene_annotation(soft_file)
# Print annotation info
print("Looking for gene annotation in file:", soft_file)
print("\nGene Annotation Preview:")
print("Number of rows:", len(gene_annotation))
print("Column names:", gene_annotation.columns.tolist())
# The platform appears to lack complete annotation in the SOFT file
# This is GPL18109 platform which requires special handling
print("\nNOTE: This dataset uses GPL18109 platform (Agilent-038314 CBC Homo sapiens lncRNA + mRNA microarray)")
print("The complete gene mapping information is not available in the SOFT file.")
print("Manual annotation retrieval from GEO is required for this platform.")
# Since automated annotation retrieval failed, we should stop here and inform about manual annotation need
raise ValueError("Gene mapping information not found in SOFT file. Manual annotation retrieval required for GPL18109.")