Liu-Hy's picture
Add files using upload-large-folder tool
f426016 verified
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Anxiety_disorder"
cohort = "GSE61672"
# Input paths
in_trait_dir = "../DATA/GEO/Anxiety_disorder"
in_cohort_dir = "../DATA/GEO/Anxiety_disorder/GSE61672"
# Output paths
out_data_file = "./output/preprocess/1/Anxiety_disorder/GSE61672.csv"
out_gene_data_file = "./output/preprocess/1/Anxiety_disorder/gene_data/GSE61672.csv"
out_clinical_data_file = "./output/preprocess/1/Anxiety_disorder/clinical_data/GSE61672.csv"
json_path = "./output/preprocess/1/Anxiety_disorder/cohort_info.json"
# STEP 1
from tools.preprocess import *
# 1. Identify the paths to the SOFT file and the matrix file
soft_file, matrix_file = geo_get_relevant_filepaths(in_cohort_dir)
# 2. Read the matrix file to obtain background information and sample characteristics data
background_prefixes = ['!Series_title', '!Series_summary', '!Series_overall_design']
clinical_prefixes = ['!Sample_geo_accession', '!Sample_characteristics_ch1']
background_info, clinical_data = get_background_and_clinical_data(
matrix_file,
background_prefixes,
clinical_prefixes
)
# 3. Obtain the sample characteristics dictionary from the clinical dataframe
sample_characteristics_dict = get_unique_values_by_row(clinical_data)
# 4. Explicitly print out all the background information and the sample characteristics dictionary
print("Background Information:")
print(background_info)
print("\nSample Characteristics Dictionary:")
print(sample_characteristics_dict)
import pandas as pd
import os
import json
from typing import Optional, Callable
# The sample characteristics dictionary from the previous step:
sample_dict = {
0: ['age: 44', 'age: 59', 'age: 39', 'age: 64', 'age: 58', 'age: 45', 'age: 37', 'age: 40',
'age: 57', 'age: 52', 'age: 62', 'age: 55', 'age: 53', 'age: 47', 'age: 48', 'age: 49',
'age: 35', 'age: 46', 'age: 54', 'age: 67', 'age: 51', 'age: 34', 'age: 60', 'age: 41',
'age: 38', 'age: 73', 'age: 28', 'age: 56', 'age: 71', 'age: 50'],
1: ['Sex: F', 'Sex: M', 'body mass index: 25.1', 'body mass index: 31.1', 'body mass index: 29.4',
'body mass index: 27.6', 'body mass index: 24.6', 'body mass index: 28', 'body mass index: 33.9',
'body mass index: 35', 'body mass index: 18.1', 'body mass index: 19.2', 'body mass index: 39.2',
'body mass index: 26.8', 'body mass index: 21.3', 'body mass index: 36.5', 'body mass index: 19.5',
'body mass index: 24.4', 'body mass index: 26.4', 'body mass index: 26.2', 'body mass index: 23.8',
'body mass index: 19.7', 'body mass index: 30.6', 'body mass index: 22.8', 'body mass index: 22.1',
'body mass index: 33.4', 'body mass index: 26.6', 'body mass index: 21.8', 'body mass index: 24.3',
'body mass index: 27'],
2: ['body mass index: 22.2', 'body mass index: 33.1', 'body mass index: 22.4', 'body mass index: 20.6',
'body mass index: 27.5', 'body mass index: 21.9', 'body mass index: 26.1', 'body mass index: 34.8',
'body mass index: 20.8', 'body mass index: 23.3', 'body mass index: 22.7', 'body mass index: 26.4',
'body mass index: 32.5', 'body mass index: 21.6', 'body mass index: 27.6', 'body mass index: 25.7',
'body mass index: 33.3', 'body mass index: 31.6', 'body mass index: 28', 'body mass index: 41.1',
'body mass index: 19.7', 'body mass index: 22.1', 'body mass index: 20.7', 'body mass index: 30.9',
'body mass index: 17.8', 'body mass index: 22.5', 'body mass index: 40.6', 'body mass index: 28.9',
'body mass index: 26', 'body mass index: 22'],
3: ['ethnicity: CAU', 'ethnicity: AFR', 'ethnicity: ASN', 'ethnicity: AMI', 'ethnicity: CAH',
'gad7 score: 6', 'gad7 score: 1', 'gad7 score: 0', 'gad7 score: 2', 'gad7 score: 3', 'gad7 score: 5',
'gad7 score: 4', 'gad7 score: 9', 'gad7 score: 7', 'gad7 score: 8', 'hybridization batch: C',
'gad7 score: .', 'gad7 score: 16', 'gad7 score: 12', 'gad7 score: 11', 'gad7 score: 21',
'gad7 score: 18', 'gad7 score: 14'],
4: ['gad7 score: 2', 'gad7 score: 0', 'gad7 score: 3', 'gad7 score: 7', 'gad7 score: 4',
'gad7 score: 9', 'gad7 score: 1', 'gad7 score: 10', 'gad7 score: 5', 'gad7 score: 17', 'gad7 score: 6',
'gad7 score: 8', 'gad7 score: 12', 'gad7 score: 11', 'gad7 score: 14', 'gad7 score: .',
'hybridization batch: Z', 'gad7 score: 18', 'hybridization batch: O', 'gad7 score: 13',
'gad7 score: 15', 'gad7 score: 20', 'gad7 score: 21', 'gad7 score: 19', 'anxiety case/control: case',
'anxiety case/control: control', 'hybridization batch: B', None, 'hybridization batch: C',
'hybridization batch: D'],
5: ['hybridization batch: Z', 'anxiety case/control: control', 'anxiety case/control: case',
'rin: 8.4', 'hybridization batch: A', 'hybridization batch: O', 'rin: 6', None,
'hybridization batch: B', 'rin: 9.5', 'rin: 9.1', 'rin: 9.3', 'rin: 9.7', 'rin: 9.6',
'rin: 8.7', 'hybridization batch: C', 'rin: 8.6', 'rin: 7.9', 'rin: 7.3', 'rin: 7.1',
'rin: 8.9', 'rin: 9.8', 'rin: 9.4', 'rin: 9.2', 'rin: 8.8', 'rin: 10', 'rin: 9', 'rin: 9.9',
'hybridization batch: D'],
6: ['rin: 8.1', 'hybridization batch: Z', 'rin: 7.9', 'rin: 6.6', 'rin: 7.3', 'rin: 6.9',
'rin: 6.8', 'rin: 7.5', 'rin: 6.7', 'rin: 6.5', 'rin: 7.8', 'rin: 7.6', 'rin: 8', 'rin: 7.4',
'rin: 8.4', 'rin: 8.7', 'rin: 8.8', 'rin: 7.7', 'rin: 8.3', 'rin: 7', 'rin: 9', 'rin: 9.3',
'rin: 8.9', None, 'rin: 8.2', 'rin: 9.2', 'rin: 7.2', 'rin: 7.1', 'hybridization batch: A',
'rin: 9.8'],
7: [None, 'rin: 7.8', 'rin: 8.1', 'rin: 6.6', 'rin: 6.5', 'rin: 6.7', 'rin: 7.2', 'rin: 7.7',
'rin: 7.1', 'rin: 7', 'rin: 7.3', 'rin: 7.5', 'rin: 7.9', 'rin: 8.2', 'rin: 7.4', 'rin: 7.6',
'rin: 6.8', 'rin: 9.4', 'rin: 8.6', 'rin: 8.3', 'rin: 8.8', 'rin: 8', 'rin: 8.4', 'rin: 8.7',
'rin: 9', 'rin: 9.1', 'rin: 9.2', 'rin: 9.3', 'rin: 8.5', 'rin: 6.9']
}
# Construct the DataFrame where each row in sample_dict is a row in the DataFrame.
clinical_data = pd.DataFrame.from_dict(sample_dict, orient='index')
# 1. Gene Expression Data Availability
# The background info specifies "genome-wide differential gene expression",
# so we set is_gene_available to True.
is_gene_available = True
# 2. Variable Availability and Data Type Conversion
# Identify row keys for the variables (trait, age, gender) if they exist and are not constant.
# - Age is row 0, multiple distinct values => available.
age_row = 0
# - Trait (anxiety case/control) is found in row 4: "anxiety case/control: case"/"control"
trait_row = 4
# - Gender is in row 1: "Sex: F"/"Sex: M" along with BMI. Let's parse those "Sex" entries.
gender_row = 1
def convert_trait(value: str) -> Optional[int]:
"""
Convert values referring to 'anxiety case/control':
'case' -> 1
'control' -> 0
Everything else -> None
"""
parts = value.split(":", 1)
if len(parts) == 2:
header = parts[0].strip().lower()
val = parts[1].strip().lower()
if header == "anxiety case/control":
if val == "case":
return 1
elif val == "control":
return 0
return None
def convert_age(value: str) -> Optional[float]:
"""
Convert values of the form 'age: 44' -> 44.0
Otherwise -> None
"""
parts = value.split(":", 1)
if len(parts) == 2:
header = parts[0].strip().lower()
val = parts[1].strip()
if header == "age":
try:
return float(val)
except ValueError:
return None
return None
def convert_gender(value: str) -> Optional[int]:
"""
For gender, convert:
'Sex: F' -> 0
'Sex: M' -> 1
Otherwise -> None
"""
parts = value.split(":", 1)
if len(parts) == 2:
header = parts[0].strip().lower()
val = parts[1].strip().lower()
if header == "sex":
if val == "f":
return 0
elif val == "m":
return 1
return None
# 2.1 Check trait availability:
is_trait_available = (trait_row is not None)
# 3. Save Metadata (initial filtering)
from tools.preprocess import validate_and_save_cohort_info, geo_select_clinical_features, preview_df
is_usable = 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 if trait_row is not None
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 = preview_df(selected_clinical_df)
print("Clinical dataframe preview:", preview)
# Save the extracted clinical features
selected_clinical_df.to_csv(out_clinical_data_file, index=False)
import re
# 1. Gene Expression Data Availability
is_gene_available = True
# 2. Variable Availability and Data Type Conversion
# (We do not see any evidence of actual row keys for trait, age, or gender, so set them to None.)
trait_row = None
age_row = None
gender_row = None
# Define conversion functions even if rows are None, for consistency and future use.
def convert_trait(val_str: str):
"""Convert trait value to binary (0 for control, 1 for anxiety), None if unknown."""
if val_str is None:
return None
# If there's a colon, separate out the last segment.
parts = val_str.split(":")
val_str = parts[-1].strip() if len(parts) > 1 else val_str.strip()
val_lower = val_str.lower()
if "anxiety" in val_lower:
return 1
elif "control" in val_lower:
return 0
return None
def convert_age(val_str: str):
"""Convert age to a continuous number, None if parsing fails."""
if val_str is None:
return None
# If there's a colon, separate out the last segment.
parts = val_str.split(":")
val_str = parts[-1].strip() if len(parts) > 1 else val_str.strip()
# Extract numeric part from the string
match = re.search(r"(\d+(\.\d+)?)", val_str)
if match:
try:
return float(match.group(1))
except ValueError:
return None
return None
def convert_gender(val_str: str):
"""Convert gender to binary (0 for female, 1 for male), None if unknown."""
if val_str is None:
return None
# If there's a colon, separate out the last segment.
parts = val_str.split(":")
val_str = parts[-1].strip() if len(parts) > 1 else val_str.strip()
val_lower = val_str.lower()
if "female" in val_lower:
return 0
elif "male" in val_lower:
return 1
return None
# Determine availability of trait data
is_trait_available = (trait_row is not None)
# 3. Save Metadata - initial filtering
is_usable = 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
# Since trait_row is None, we skip the clinical feature extraction step.
# STEP3
# 1. Use the get_genetic_data function from the library to get the gene_data from the matrix_file previously defined.
gene_data = get_genetic_data(matrix_file)
# 2. Print the first 20 row IDs (gene or probe identifiers) for future observation.
print(gene_data.index[:20])
# These gene identifiers are from the Illumina platform (e.g., "ILMN_1343291"), not standard human gene symbols.
# Therefore, gene mapping to standard symbols is likely required.
print("requires_gene_mapping = True")
# STEP5
# 1. Use the 'get_gene_annotation' function from the library to get gene annotation data from the SOFT file.
gene_annotation = get_gene_annotation(soft_file)
# 2. Use the 'preview_df' function from the library to preview the data and print out the results.
print("Gene annotation preview:")
print(preview_df(gene_annotation))
# STEP: Gene Identifier Mapping
# 1. We observed that in the gene annotation dataframe, the column "ID" stores the same probe identifiers
# (e.g., ILMN_1343291) as in the gene expression data index, and the column "Symbol" stores the potential gene symbols.
# 2. Get a gene mapping from 'ID' to 'Symbol'.
mapping_df = get_gene_mapping(gene_annotation, prob_col='ID', gene_col='Symbol')
# 3. Convert probe-level measurements to gene expression data using our mapping.
gene_data = apply_gene_mapping(gene_data, mapping_df)
# STEP 8: Data Normalization and (Potential) Linking
# Because, in earlier steps, we determined trait_row = None, the trait data is unavailable,
# so there's no clinical CSV file to read back in. By the instructions, we still finalize
# the process but skip linking and trait-based analysis.
# 1. Normalize gene symbols in the obtained gene expression data
normalized_gene_data = normalize_gene_symbols_in_index(gene_data)
normalized_gene_data.to_csv(out_gene_data_file)
print(f"Saved normalized gene data to {out_gene_data_file}")
# 2. Since trait data is not available, we cannot link or run trait-based analyses.
print("Trait is not available (trait_row = None). Skipping linking and missing-value handling steps.")
# 3. Perform final validation indicating that trait data is missing, causing the dataset to be unusable:
is_usable = validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=True, # Gene data exists
is_trait_available=False, # Trait data is not available
is_biased=None, # This must be None if is_trait_available=False
df=pd.DataFrame(), # Pass an empty DataFrame since we have no clinical+trait data
note="No trait data available, thus not usable for trait-based analysis."
)
# 4. If the dataset is somehow deemed usable (unlikely, because no trait), save the final data anyway;
# otherwise skip saving.
if is_usable:
# This scenario won't occur, but included for completeness
out_data_file_placeholder = out_data_file.replace(".csv", "_linked_placeholder.csv")
pd.DataFrame().to_csv(out_data_file_placeholder, index=False)
print(f"Saved a placeholder linked dataset to {out_data_file_placeholder}")
else:
print("The dataset is not usable for trait-based association. Skipping final output of linked data.")