File size: 14,638 Bytes
13fd1a3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 |
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "COVID-19"
cohort = "GSE275334"
# Input paths
in_trait_dir = "../DATA/GEO/COVID-19"
in_cohort_dir = "../DATA/GEO/COVID-19/GSE275334"
# Output paths
out_data_file = "./output/preprocess/3/COVID-19/GSE275334.csv"
out_gene_data_file = "./output/preprocess/3/COVID-19/gene_data/GSE275334.csv"
out_clinical_data_file = "./output/preprocess/3/COVID-19/clinical_data/GSE275334.csv"
json_path = "./output/preprocess/3/COVID-19/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
# Yes, contains NanoString gene expression data from immune exhaustion panel
is_gene_available = True
# 2. Variable Availability and Keys
trait_row = 3 # 'disease' field contains trait data
age_row = 1 # 'age (years)' field contains age data
gender_row = 2 # 'Sex' field contains gender data
# 2.2 Data Type Conversion Functions
def convert_trait(value: str) -> int:
"""Convert COVID-19 status to binary. Long COVID=1, others=0"""
if pd.isna(value) or ':' not in value:
return None
value = value.split(':')[1].strip().lower()
if 'long covid' in value:
return 1
elif value in ['healthy control', 'me/cfs']:
return 0
return None
def convert_age(value: str) -> float:
"""Convert age to float"""
if pd.isna(value) or ':' not in value:
return None
try:
return float(value.split(':')[1].strip())
except:
return None
def convert_gender(value: str) -> int:
"""Convert gender to binary. Female=0, Male=1"""
if pd.isna(value) or ':' not in value:
return None
value = value.split(':')[1].strip().lower()
if value == 'female':
return 0
elif value == 'male':
return 1
return None
# 3. Save 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. Extract Clinical Features
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
)
# Preview the extracted features
print("Preview of clinical features:")
print(preview_df(clinical_features))
# Save to CSV
clinical_features.to_csv(out_clinical_data_file)
# Extract genetic data matrix
genetic_data = get_genetic_data(matrix_file_path)
# Print first few rows with column names to examine data structure
print("Data preview:")
print("\nColumn names:")
print(list(genetic_data.columns)[:5])
print("\nFirst 5 rows:")
print(genetic_data.head())
print("\nShape:", genetic_data.shape)
# Verify this is gene expression data and check identifiers
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)
)
# Save gene expression data
genetic_data.to_csv(out_gene_data_file)
requires_gene_mapping = False
# 1. Normalize gene symbols and save gene data
normalized_gene_data = normalize_gene_symbols_in_index(genetic_data)
os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
normalized_gene_data.to_csv(out_gene_data_file)
# 2. Link clinical and genetic data
clinical_features = pd.read_csv(out_clinical_data_file, index_col=0).T
linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)
# Verify data integrity
print("Linked data shape:", linked_data.shape)
print("\nAvailable columns:")
print(list(linked_data.columns)[:10])
print("\nSample preview:")
print(linked_data.head())
# 3. Handle missing values
linked_data = handle_missing_values(linked_data, trait)
# 4. Judge bias in features and remove biased ones
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Final validation and save metadata
is_usable = validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=is_gene_available,
is_trait_available=True,
is_biased=trait_biased,
df=linked_data,
note="NanoString gene expression data comparing long COVID cases with healthy controls and ME/CFS."
)
# 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)
# Since data already contains proper gene symbols, skip mapping and use original genetic data
gene_data = genetic_data
print("Gene mapping skipped - data already contains proper gene symbols")
print(f"Shape of gene expression data: {gene_data.shape}")
print("\nFirst few gene symbols:")
print(list(gene_data.index)[:10])
# Extract gene annotation data
gene_metadata = get_gene_annotation(soft_file_path)
# Preview column names and first few values
preview = preview_df(gene_metadata)
print("\nGene annotation columns and sample values:")
print(preview)
# Extract gene annotation data
gene_metadata = get_gene_annotation(soft_file_path)
# Print column names and first few rows for verification
print("Gene annotation data preview:")
print("Columns:", list(gene_metadata.columns))
print("\nFirst few rows:")
print(gene_metadata.head())
# Get mapping between gene IDs and gene symbols (ID maps to itself since already symbols)
mapping_df = get_gene_mapping(gene_metadata, "ID", "ID")
# Convert index to string type
gene_data = genetic_data.copy()
gene_data.index = gene_data.index.astype(str)
print("\nFirst 10 gene symbols in expression data:")
print(list(gene_data.index)[:10])
print("\nShape of gene expression data:")
print(gene_data.shape)
# 1. Normalize gene symbols and save gene data
normalized_gene_data = normalize_gene_symbols_in_index(genetic_data)
os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
normalized_gene_data.to_csv(out_gene_data_file)
# 2. Link clinical and genetic data
clinical_features = pd.read_csv(out_clinical_data_file, index_col=0).T
linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)
# 3. Handle missing values
linked_data = handle_missing_values(linked_data, trait)
# 4. Judge bias in features and remove biased ones
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Final validation and save metadata
is_usable = validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=is_gene_available,
is_trait_available=True,
is_biased=trait_biased,
df=linked_data,
note="NanoString gene expression data comparing long COVID cases with healthy controls and ME/CFS."
)
# 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)
print("Missing critical input. Please provide:")
print("1. Output of previous step containing sample characteristics dictionary")
print("2. Background information about the dataset")
# 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
# Yes, this dataset contains gene expression data according to the background info
is_gene_available = True
# 2.1 Data Availability
trait_row = 3 # 'disease' row contains trait info
age_row = 1 # age is available
gender_row = 2 # gender info is in 'Sex' field
# 2.2 Data Type Conversion Functions
def convert_trait(x):
"""Convert trait values to binary (0 for control, 1 for case)"""
if not x or ':' not in x:
return None
value = x.split(':')[1].strip()
if value == 'Healthy control':
return 0
elif value in ['Long COVID', 'ME/CFS']:
return 1
return None
def convert_age(x):
"""Convert age values to continuous numeric"""
if not x or ':' not in x:
return None
try:
return float(x.split(':')[1].strip())
except:
return None
def convert_gender(x):
"""Convert gender values to binary (0 for female, 1 for male)"""
if not x or ':' not in x:
return None
value = x.split(':')[1].strip()
if value == 'Female':
return 0
elif value == 'Male':
return 1
return None
# 3. Save 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)
# 4. Clinical Feature Extraction
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
preview_result = preview_df(selected_clinical)
print("Preview of extracted clinical features:")
print(preview_result)
# Save clinical data
selected_clinical.to_csv(out_clinical_data_file)
# Extract genetic data matrix
genetic_data = get_genetic_data(matrix_file_path)
# Print first few rows with column names to examine data structure
print("Data preview:")
print("\nColumn names:")
print(list(genetic_data.columns)[:5])
print("\nFirst 5 rows:")
print(genetic_data.head())
print("\nShape:", genetic_data.shape)
# Verify this is gene expression data and check identifiers
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)
)
# Save gene expression data
genetic_data.to_csv(out_gene_data_file)
# Based on gene identifiers like ACACA, ACADVL, ACAT2 - these appear to be standard human gene symbols
# No mapping required as they are already in the correct format
requires_gene_mapping = False
# 1. Normalize gene symbols and save gene data
normalized_gene_data = normalize_gene_symbols_in_index(genetic_data)
os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
normalized_gene_data.to_csv(out_gene_data_file)
# 2. Link clinical and genetic data
clinical_features = pd.read_csv(out_clinical_data_file, index_col=0).T
linked_data = geo_link_clinical_genetic_data(clinical_features, normalized_gene_data)
# Rename trait column to match the trait variable
linked_data = linked_data.rename(columns={'COVID-19': trait})
# 3. Handle missing values
linked_data = handle_missing_values(linked_data, trait)
# 4. Judge bias in features and remove biased ones
trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Final validation and save metadata
is_usable = validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=is_gene_available,
is_trait_available=True,
is_biased=trait_biased,
df=linked_data,
note="NanoString gene expression data comparing long COVID cases with healthy controls and ME/CFS patients."
)
# 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)
clinical_data = pd.read_csv("../DATA/GEO/COVID-19/GSE275334/sample_characteristics.csv", index_col=0) # Load data from previous step
sample_info = preview_df(clinical_data)
print(sample_info)
# Based on log2 expression data seen in previous step
is_gene_available = True
# Based on sample characteristics review
trait_row = 9 # critical status
age_row = 5 # age row
gender_row = 6 # gender row
def convert_trait(x):
if x is None:
return None
x = str(x).lower().split(':')[-1].strip()
if 'critical' in x:
return 1
elif 'non-critical' in x:
return 0
return None
def convert_age(x):
if x is None:
return None
try:
age = float(str(x).split(':')[-1].strip())
return age
except:
return None
def convert_gender(x):
if x is None:
return None
x = str(x).lower().split(':')[-1].strip()
if 'female' in x or 'f' in x:
return 0
elif 'male' in x or 'm' in x:
return 1
return None
# Save 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)
)
# Extract clinical features since trait data is available
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("\nExtracted clinical features:")
print(preview_df(clinical_features))
# Save clinical data
clinical_features.to_csv(out_clinical_data_file) |