Liu-Hy's picture
Add files using upload-large-folder tool
1f52ac2 verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Melanoma"
cohort = "GSE144296"
# Input paths
in_trait_dir = "../DATA/GEO/Melanoma"
in_cohort_dir = "../DATA/GEO/Melanoma/GSE144296"
# Output paths
out_data_file = "./output/preprocess/3/Melanoma/GSE144296.csv"
out_gene_data_file = "./output/preprocess/3/Melanoma/gene_data/GSE144296.csv"
out_clinical_data_file = "./output/preprocess/3/Melanoma/clinical_data/GSE144296.csv"
json_path = "./output/preprocess/3/Melanoma/cohort_info.json"
# Get file paths for SOFT and matrix files
soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)
# Get background info and clinical data from the matrix file
background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)
# Create dictionary of unique values for each feature
unique_values_dict = get_unique_values_by_row(clinical_data)
# Print the information
print("Dataset Background Information:")
print(background_info)
print("\nSample Characteristics:")
for feature, values in unique_values_dict.items():
print(f"\n{feature}:")
print(values)
# 1. Gene Expression Data Availability
# Based on background info mentioning mRNA sequencing and gene expression analysis
is_gene_available = True
# 2.1 Data Availability
# Trait (melanoma vs non-melanoma) can be inferred from cell type field (row 1)
trait_row = 1
# Age not available in data
age_row = None
# Gender not available in data
gender_row = None
# 2.2 Data Type Conversion Functions
def convert_trait(x):
"""Convert cell type to binary melanoma indicator"""
if not isinstance(x, str):
return None
x = x.lower().split(': ')[-1]
if 'melanoma' in x:
return 1
elif 'colorectal' in x:
return 0
return None
def convert_age(x):
"""Placeholder for age conversion"""
return None
def convert_gender(x):
"""Placeholder for gender conversion"""
return None
# 3. 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
)
# 4. Clinical Feature Extraction
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 processed clinical data
preview_df(selected_clinical)
# Save clinical features
selected_clinical.to_csv(out_clinical_data_file)
# Extract genetic data matrix with case-insensitive marker
genetic_data = get_genetic_data(matrix_file_path, marker="!series_matrix_table_begin".lower())
# Verify data was loaded
if len(genetic_data.index) == 0:
# Try alternative marker format
genetic_data = get_genetic_data(matrix_file_path, marker="!Series_Matrix_Table_Begin")
if len(genetic_data.index) == 0:
print("Warning: No data was extracted from the matrix file. Please check the matrix file formatting.")
is_gene_available = False
else:
print("First 20 row IDs:")
print(list(genetic_data.index)[:20])
is_gene_available = True
# Save updated metadata
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)
)
if is_gene_available:
genetic_data.to_csv(out_gene_data_file)
# Examine file content before filtering
with gzip.open(soft_file_path, 'rt') as f:
print("\nSample of unfiltered SOFT file content (first 20 lines):")
for i, line in enumerate(f):
if i < 20: # Print more lines to better understand the structure
print(line.strip())
elif i == 20:
print("...")
break
# Try reading the matrix file for gene annotations since the SOFT file seems to lack them
with gzip.open(matrix_file_path, 'rt') as f:
print("\nSample of matrix file content (first 20 lines):")
for i, line in enumerate(f):
if i < 20:
print(line.strip())
elif i == 20:
print("...")
break
# Since we can see the file content now, update the gene metadata extraction
probe_info_found = False
with gzip.open(matrix_file_path, 'rt') as f:
lines = []
for line in f:
if line.startswith('!Platform_organism'):
probe_info_found = True
lines.append(line)
elif probe_info_found and line.startswith('!'):
lines.append(line)
elif probe_info_found and not any(line.startswith(p) for p in ['!', '#', '^']):
break
gene_metadata_text = '\n'.join(lines)
print("\nExtracted probe/gene information:")
print(gene_metadata_text)
# Try reading gene expression data using the library function
genetic_data = get_genetic_data(matrix_file_path)
# Convert index to string type
genetic_data.index = genetic_data.index.astype(str)
# Print sample identifiers for verification
print("\nSample identifiers from genetic data:")
print(list(genetic_data.index)[:5])
# Extract gene mapping info
try:
with gzip.open(matrix_file_path, 'rt') as f:
for line in f:
if '!series_matrix_table_begin' in line.lower():
# Found start of expression data
break
if line.startswith('!Sample_platform_id'):
# Save the platform ID if we find it
platform_line = line.strip()
# For RNA-seq data, create a 1:1 mapping using the original gene identifiers
ids = genetic_data.index.tolist()
annotation_df = pd.DataFrame({
'ID': ids,
'Gene': ids # Use same IDs as gene symbols for now
})
print("\nSample rows from annotation mapping:")
print(annotation_df.head())
# Apply gene mapping using library function
gene_data = apply_gene_mapping(genetic_data, annotation_df)
# Convert gene indices to string before normalization
gene_data.index = gene_data.index.astype(str)
# Normalize gene symbols
gene_data = normalize_gene_symbols_in_index(gene_data)
print("\nFinal gene data shape:", gene_data.shape)
print("Sample gene names after normalization:")
print(list(gene_data.index)[:5])
# Save the processed gene data
gene_data.to_csv(out_gene_data_file)
except Exception as e:
print(f"Error during gene mapping: {str(e)}")
# Save genetic data without mapping if error occurs
genetic_data.to_csv(out_gene_data_file)
# Read the entire file first to find the exact line numbers of begin/end markers
with gzip.open(matrix_file_path, 'rt') as f:
lines = f.readlines()
start_idx = None
end_idx = None
for i, line in enumerate(lines):
if '!series_matrix_table_begin' in line.lower():
start_idx = i + 1 # Skip the marker line
elif '!series_matrix_table_end' in line.lower():
end_idx = i
break
genetic_data = None
if start_idx and end_idx:
# Read only the data section
genetic_data = pd.read_csv(io.StringIO(''.join(lines[start_idx:end_idx])),
sep='\t', index_col=0)
# Print results
if genetic_data is not None and len(genetic_data) > 0:
print("\nFirst 20 row IDs:")
print(list(genetic_data.index)[:20])
is_gene_available = True
else:
print("\nWarning: No gene expression data could be extracted")
is_gene_available = False
# Save updated metadata
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)
)
if is_gene_available:
genetic_data.to_csv(out_gene_data_file)