Liu-Hy's picture
Add files using upload-large-folder tool
3ee376c verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Breast_Cancer"
cohort = "GSE249377"
# Input paths
in_trait_dir = "../DATA/GEO/Breast_Cancer"
in_cohort_dir = "../DATA/GEO/Breast_Cancer/GSE249377"
# Output paths
out_data_file = "./output/preprocess/3/Breast_Cancer/GSE249377.csv"
out_gene_data_file = "./output/preprocess/3/Breast_Cancer/gene_data/GSE249377.csv"
out_clinical_data_file = "./output/preprocess/3/Breast_Cancer/clinical_data/GSE249377.csv"
json_path = "./output/preprocess/3/Breast_Cancer/cohort_info.json"
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Extract background info and clinical data using specified prefixes
background_info, clinical_data = get_background_and_clinical_data(
matrix_file,
prefixes_a=['!Series_title', '!Series_summary', '!Series_overall_design'],
prefixes_b=['!Sample_geo_accession', '!Sample_characteristics_ch1']
)
# 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
# This is a transcriptomics dataset using MCF7 breast cancer cell line
is_gene_available = True
# 2.1 Variable availability - look at unique values under each feature ID
trait_row = 2 # Treatment status available in Feature 2
age_row = None # No age information
gender_row = None # No gender information - cell line data only
# 2.2 Data type conversion functions
def convert_trait(value: str) -> Optional[int]:
"""Convert treatment data to binary: treated (1) vs untreated (0)"""
if value is None or 'NA' in value:
return None
if 'untreated' in value:
return 0
if 'exposure' in value:
return 1
return None
def convert_age(value: str) -> Optional[float]:
"""Not used since age data unavailable"""
return None
def convert_gender(value: str) -> Optional[int]:
"""Not used since gender data unavailable"""
return None
# 3. Save metadata about data availability
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 and save
if trait_row is not None:
selected_clinical_df = 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
preview = preview_df(selected_clinical_df)
print("Preview of extracted clinical features:")
print(preview)
# Save clinical data
selected_clinical_df.to_csv(out_clinical_data_file)
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Debug: Print section around matrix begin marker
print("Examining data format:")
with gzip.open(matrix_file, 'rt') as f:
found = False
for i, line in enumerate(f):
if "!series_matrix_table_begin" in line:
found = True
print("Found marker at line:", i)
print("\nHeader line:")
header = next(f).strip()
print(header)
print("\nFirst few data lines:")
for _ in range(4): # Print 4 data lines
print(next(f).strip())
break
if not found:
print("Matrix begin marker not found")
# Now extract gene expression data with better error handling
def get_gene_data_debug(file_path: str, marker: str = "!series_matrix_table_begin") -> pd.DataFrame:
skip_rows = 0
with gzip.open(file_path, 'rt') as file:
for i, line in enumerate(file):
if marker in line:
skip_rows = i
break
# Read the data starting right after the marker line
genetic_data = pd.read_csv(file_path, compression='gzip', skiprows=skip_rows+1,
sep='\t', index_col=0)
return genetic_data
gene_data = get_gene_data_debug(matrix_file)
# Print information about loaded data
print("\nShape 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].tolist())
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Extract gene data using library function
gene_data = get_genetic_data(matrix_file)
# Print debug info
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].tolist())
# Get file paths
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Try direct read with error handling and verification
try:
# Use the library function but verify output
gene_data = get_genetic_data(matrix_file)
# Verify we got data
if gene_data.empty:
print("WARNING: No gene expression data loaded!")
else:
print(f"\nSuccessfully loaded gene expression data with shape: {gene_data.shape}")
print("\nFirst 5 rows:")
print(gene_data.head())
print("\nFirst 20 gene/probe identifiers:")
print(gene_data.index[:20].tolist())
# Save gene data
gene_data.to_csv(out_gene_data_file)
except Exception as e:
print(f"Error reading gene data: {e}")
print("\nAttempting to examine file content:")
with gzip.open(matrix_file, 'rt') as f:
# Read a bit more after the header
header = False
for i, line in enumerate(f):
if "!series_matrix_table_begin" in line:
header = True
print("\nFound data start marker")
continue
if header:
print(f"Line after marker {i}: {line[:100]}...")
if i > 85: # Print a few lines after marker
break
# First examine if file contains platform/probe information
with gzip.open(soft_file, 'rt', encoding='utf-8') as f:
has_platform = False
gene_annotation_lines = []
for i, line in enumerate(f):
line = line.strip()
if 'platform' in line.lower():
print(f"Platform line: {line}")
has_platform = True
# Collect lines between !platform_table_begin and !platform_table_end
if has_platform and "!platform_table_begin" in line:
next(f) # Skip header line
for data_line in f:
if "!platform_table_end" in data_line:
break
gene_annotation_lines.append(data_line)
break
# Convert collected lines to dataframe if any found
if gene_annotation_lines:
# Join lines and create dataframe
annotation_text = ''.join(gene_annotation_lines)
gene_metadata = pd.read_csv(io.StringIO(annotation_text), delimiter='\t')
print("\nGene annotation dataframe shape:", gene_metadata.shape)
print("\nColumn names:", gene_metadata.columns.tolist())
print("\nFirst few rows:")
print(gene_metadata.head())
else:
print("\nNo gene annotation data found in platform section")
# Create empty dataframe as placeholder
gene_metadata = pd.DataFrame()