Liu-Hy's picture
Add files using upload-large-folder tool
3ee376c verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Cardiovascular_Disease"
cohort = "GSE283522"
# Input paths
in_trait_dir = "../DATA/GEO/Cardiovascular_Disease"
in_cohort_dir = "../DATA/GEO/Cardiovascular_Disease/GSE283522"
# Output paths
out_data_file = "./output/preprocess/3/Cardiovascular_Disease/GSE283522.csv"
out_gene_data_file = "./output/preprocess/3/Cardiovascular_Disease/gene_data/GSE283522.csv"
out_clinical_data_file = "./output/preprocess/3/Cardiovascular_Disease/clinical_data/GSE283522.csv"
json_path = "./output/preprocess/3/Cardiovascular_Disease/cohort_info.json"
# Get paths to the SOFT and matrix files
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# Get background info and clinical data from matrix file
background_info, clinical_data = get_background_and_clinical_data(matrix_file)
# Get unique values for each feature (row) in clinical data
unique_values_dict = get_unique_values_by_row(clinical_data)
# Print background info
print("=== Dataset Background Information ===")
print(background_info)
print("\n=== Sample Characteristics ===")
print(json.dumps(unique_values_dict, indent=2))
# Gene Expression Data Availability
is_gene_available = True # mRNA seq data available based on background info
# Clinical Data Availability and Type Conversion
trait_row = 6 # sample category indicates sample type
age_row = 2 # age data available
gender_row = 5 # sex data available
def convert_trait(value):
if pd.isna(value) or 'not applicable' in str(value).lower():
return None
value = value.split(': ')[1] if ': ' in value else value
if 'invasive breast cancer' in value.lower():
return 1
elif 'healthy' in value.lower() or 'no tumor' in value.lower():
return 0
return None
def convert_age(value):
if pd.isna(value) or 'not applicable' in str(value).lower():
return None
value = value.split(': ')[1] if ': ' in value else value
if '-' not in value:
return None
try:
start, end = map(int, value.split('-'))
return (start + end) / 2 # Take midpoint of range
except:
return None
def convert_gender(value):
if pd.isna(value) or 'missing' in str(value).lower() or 'not applicable' in str(value).lower():
return None
value = value.split(': ')[1] if ': ' in value else value
if value.lower() == 'female':
return 0
elif value.lower() == 'male':
return 1
return None
# Save metadata for 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))
# Extract clinical features if trait data available
if trait_row is not None:
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)
print("Preview of extracted clinical features:")
print(preview_df(clinical_features))
clinical_features.to_csv(out_clinical_data_file)
# First verify the file exists and print more lines to check structure
with gzip.open(matrix_file, 'rt') as f:
# Read more lines to look for data section
print("Searching for marker line and data section:")
marker_found = False
for i, line in enumerate(f):
if i < 50: # Check first 50 lines
if '!series_matrix_table_begin' in line.lower():
marker_found = True
print(f"\nFound marker at line {i}:")
print(line.strip())
print("\nNext few lines:")
elif marker_found and i < marker_found + 5:
print(line.strip())
else:
break
print("\nAttempting to extract gene expression data...\n")
# Try extracting with case-insensitive marker matching
def get_genetic_data_flexible(file_path: str) -> pd.DataFrame:
"""Modified version of get_genetic_data that does case-insensitive marker matching"""
marker_variations = ["!series_matrix_table_begin", "!Series_Matrix_Table_Begin"]
# Determine the number of rows to skip
with gzip.open(file_path, 'rt') as file:
for i, line in enumerate(file):
if any(marker in line for marker in marker_variations):
skip_rows = i + 1 # +1 to skip the marker row itself
break
else:
raise ValueError(f"Matrix data marker not found in the file.")
# Read the genetic data into a dataframe
genetic_data = pd.read_csv(file_path, compression='gzip', skiprows=skip_rows,
comment='!', delimiter='\t', on_bad_lines='skip')
if 'ID_REF' in genetic_data.columns:
genetic_data = genetic_data.rename(columns={'ID_REF': 'ID'})
genetic_data = genetic_data.astype({'ID': 'str'})
genetic_data.set_index('ID', inplace=True)
return genetic_data
# Try extracting data with modified function
genetic_df = get_genetic_data_flexible(matrix_file)
# Print first 20 row IDs and shape of dataframe
print("DataFrame shape:", genetic_df.shape)
print("\nFirst 20 gene/probe IDs:")
print(list(genetic_df.index)[:20])
# First check all files in the directory
print(f"Files in directory {in_cohort_dir}:")
files = os.listdir(in_cohort_dir)
for f in files:
print(f)
print("\nLooking for platform annotation file...")
# Try to find platform SOFT file(s)
platform_files = [f for f in files if 'platform' in f.lower() and 'soft' in f.lower()]
if platform_files:
# Use the first platform file found
platform_file = os.path.join(in_cohort_dir, platform_files[0])
print(f"\nFound platform file: {platform_file}")
# Check content
with gzip.open(platform_file, 'rt') as f:
print("\nFirst few lines of platform file:")
for i, line in enumerate(f):
if i < 10:
print(line.strip())
else:
break
# Extract gene annotation
try:
gene_metadata = get_gene_annotation(platform_file)
print("\nColumn names and preview of gene annotation data:")
print(preview_df(gene_metadata))
except Exception as e:
print(f"\nError extracting gene annotation: {e}")
else:
# If no platform file, try checking family SOFT file for platform info
print("\nNo separate platform file found. Checking family SOFT file for platform info...")
with gzip.open(soft_file, 'rt') as f:
print("\nSearching for platform information in family SOFT file:")
for i, line in enumerate(f):
if line.startswith('!Series_platform_id'):
print(line.strip())
elif i < 20 and ('platform' in line.lower() or 'GPL' in line):
print(line.strip())
# Load and preview gene identifiers from series matrix file
gene_expr_path = os.path.join(in_cohort_dir, "GSE283522_series_matrix.txt.gz")
# Read the file using pandas with adjusted parameters
# Skip initial metadata rows but read the gene IDs
gene_expr_df = pd.read_csv(gene_expr_path, sep='\t', compression='gzip',
skiprows=70, # Skip more rows to get past metadata
nrows=5) # Only read first 5 rows for preview
print("First few gene identifiers:")
print(gene_expr_df.iloc[:, 0].tolist())
# GPL24676 is Illumina HumanHT-12 WG-DASL V4.0 which uses Illumina probe IDs
# These need to be mapped to standard gene symbols
requires_gene_mapping = True