File size: 10,042 Bytes
4144951 |
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 |
# Path Configuration
from tools.preprocess import *
# Processing context
trait = "Underweight"
cohort = "GSE130563"
# Input paths
in_trait_dir = "../DATA/GEO/Underweight"
in_cohort_dir = "../DATA/GEO/Underweight/GSE130563"
# Output paths
out_data_file = "./output/preprocess/3/Underweight/GSE130563.csv"
out_gene_data_file = "./output/preprocess/3/Underweight/gene_data/GSE130563.csv"
out_clinical_data_file = "./output/preprocess/3/Underweight/clinical_data/GSE130563.csv"
json_path = "./output/preprocess/3/Underweight/cohort_info.json"
# Get file paths
soft_file_path, matrix_file_path = geo_get_relevant_filepaths(in_cohort_dir)
# Get background info and clinical data
background_info, clinical_data = get_background_and_clinical_data(matrix_file_path)
# Print shape and first few rows to verify data
print("Background Information:")
print(background_info)
print("\nClinical Data Shape:", clinical_data.shape)
print("\nFirst few rows of Clinical Data:")
print(clinical_data.head())
print("\nSample Characteristics:")
# Get dictionary of unique values per row
unique_values_dict = get_unique_values_by_row(clinical_data)
for row, values in unique_values_dict.items():
print(f"\n{row}:")
print(values)
# 1. Gene Expression Data Availability
is_gene_available = True # Based on background info, this is gene expression data from muscle biopsies
# 2.1 Data Availability
trait_row = 3 # bw loss data available in row 3
age_row = 4 # age data available in row 4
gender_row = 1 # gender data available in row 1 as "Sex"
# 2.2 Data Type Conversion Functions
def convert_trait(val):
# Extract value after colon
if ':' in val:
val = val.split(':')[1].strip()
# Convert to binary based on >= 5% weight loss criteria mentioned in background
try:
if val == '0':
return 0
elif val == 'n.d. (not determined)':
return None
else:
weight_loss = float(val)
return 1 if weight_loss >= 5 else 0
except:
return None
def convert_age(val):
# Extract age value after colon
if ':' in val:
val = val.split(':')[1].strip()
try:
return float(val)
except:
return None
def convert_gender(val):
# Extract gender value after colon and convert F->0, M->1
if ':' in val:
val = val.split(':')[1].strip()
if val == 'F':
return 0
elif val == 'M':
return 1
return None
# 3. Save Initial 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. Clinical Feature Extraction
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(preview_df(clinical_features))
# Save clinical data
clinical_features.to_csv(out_clinical_data_file)
# Extract gene expression data from matrix file
genetic_data = get_genetic_data(matrix_file_path)
# Print first 20 row IDs
print("First 20 gene/probe IDs:")
print(list(genetic_data.index[:20]))
# These identifiers appear to be microarray probe IDs (suffix '_at' is characteristic of Affymetrix arrays)
# rather than standard human gene symbols. They will need to be mapped to gene symbols.
requires_gene_mapping = True
# Extract gene annotation from SOFT file with broader prefix filtering
gene_annotation = get_gene_annotation(soft_file_path, prefixes=['!', '#'])
# Display all column names
print("All annotation columns:")
print(list(gene_annotation.columns))
# Preview first few rows of annotation data
print("\nGene annotation preview (first few rows):")
print(gene_annotation.head())
# Extract platform annotation data by excluding series and sample sections
gene_annotation = get_gene_annotation(soft_file_path, prefixes=['!Series', '!Sample', '^'])
# Print details about annotation data for debugging
print("Gene annotation preview:")
print(gene_annotation.head())
print("\nAnnotation shape:", gene_annotation.shape)
print("\nAnnotation columns:", list(gene_annotation.columns))
# Based on column names, get mapping between probes and genes
mapping_data = get_gene_mapping(gene_annotation, prob_col='ID_REF', gene_col='Gene Symbol')
# Print mapping data preview
print("\nMapping data preview:")
print(mapping_data.head())
print("\nMapping data shape:", mapping_data.shape)
# Apply mapping to convert probe-level data to gene-level data
gene_data = apply_gene_mapping(genetic_data, mapping_data)
# Preview results
print("\nFirst 20 gene symbols:")
print(list(gene_data.index[:20]))
print("\nShape of gene expression data:")
print(gene_data.shape)
# Save gene expression data
gene_data.to_csv(out_gene_data_file)
# Look for platform annotation file
platform_files = [f for f in os.listdir(in_cohort_dir) if 'annot' in f.lower()]
platform_file_path = os.path.join(in_cohort_dir, platform_files[0])
# Read platform annotation file
platform_annotation = pd.read_csv(platform_file_path, sep='\t', skiprows=0, low_memory=False)
# Display column names to find relevant ones
print("Platform annotation columns:")
print(list(platform_annotation.columns))
# Preview platform annotation data
print("\nPlatform annotation preview:")
print(platform_annotation[['probeset_id', 'gene_assignment']].head())
# Create mapping dataframe between probe IDs and gene symbols
mapping_data = platform_annotation[['probeset_id', 'gene_assignment']].copy()
mapping_data = mapping_data.rename(columns={'probeset_id': 'ID', 'gene_assignment': 'Gene'})
# Print mapping data shape and preview
print("\nMapping data shape:", mapping_data.shape)
print("\nMapping data preview:")
print(mapping_data.head())
# Try different prefix combinations to find the platform annotation section
gene_annotation = get_gene_annotation(soft_file_path, prefixes=['!Platform'])
# Print annotation details for debugging
print("Gene annotation preview:")
print(gene_annotation.head())
print("\nAnnotation columns:", list(gene_annotation.columns))
# Since we can't directly access platform annotation, let's try to obtain probe ID and gene symbol mapping
# by examining the expression matrix header
probe_ids = genetic_data.index.tolist()
mapping_data = pd.DataFrame({'ID': probe_ids})
mapping_data['Gene'] = mapping_data['ID'].str.extract(r'([A-Za-z0-9]+)_at')
# Print mapping data preview
print("\nMapping data preview:")
print(mapping_data.head())
print("\nMapping data shape:", mapping_data.shape)
# Apply mapping to convert probe-level to gene-level data
gene_data = apply_gene_mapping(genetic_data, mapping_data)
print("\nGene data preview:")
print(gene_data.head())
print("\nGene data shape:", gene_data.shape)
# Save gene data
gene_data.to_csv(out_gene_data_file)
# Extract gene expression data from matrix file
genetic_data = get_genetic_data(matrix_file_path)
# Print first 20 row IDs
print("First 20 gene/probe IDs:")
print(list(genetic_data.index[:20]))
# Get platform annotation from SOFT file
prefixes_to_exclude = ['!Series', '!Sample', '^SERIES', '^SAMPLE']
gene_annotation = get_gene_annotation(soft_file_path, prefixes=prefixes_to_exclude)
# Extract probe-gene mapping section
probe_gene_lines = []
in_mapping = False
with gzip.open(soft_file_path, 'rt') as f:
for line in f:
if '!platform_table_begin' in line:
in_mapping = True
continue
elif '!platform_table_end' in line:
break
elif in_mapping:
probe_gene_lines.append(line)
# Create dataframe from probe-gene mapping
if probe_gene_lines:
mapping_df = pd.read_csv(io.StringIO(''.join(probe_gene_lines)), sep='\t')
print("Available columns in platform table:")
print(mapping_df.columns)
print("\nFirst few rows of platform table:")
print(mapping_df.head())
# Extract probe ID and gene columns using available column names
id_column = [col for col in mapping_df.columns if 'id' in col.lower()][0]
gene_column = [col for col in mapping_df.columns if 'gene' in col.lower()][0]
mapping_data = pd.DataFrame({
'ID': mapping_df[id_column],
'Gene': mapping_df[gene_column]
})
else:
# If no mapping found, use the probe IDs as gene names
probe_ids = genetic_data.index.tolist()
mapping_data = pd.DataFrame({'ID': probe_ids, 'Gene': [x.split('_')[0] for x in probe_ids]})
# Convert probe-level to gene-level measurements
gene_data = apply_gene_mapping(genetic_data, mapping_data)
# 1. Normalize gene symbols
gene_data = normalize_gene_symbols_in_index(gene_data)
os.makedirs(os.path.dirname(out_gene_data_file), exist_ok=True)
gene_data.to_csv(out_gene_data_file)
print("\nGene data shape (normalized gene-level):", gene_data.shape)
# 2. Link clinical and genetic data
selected_clinical_df = pd.read_csv(out_clinical_data_file, index_col=0)
linked_data = geo_link_clinical_genetic_data(selected_clinical_df, gene_data)
# 3. Handle missing values
linked_data = handle_missing_values(linked_data, trait)
# 4. Check for bias in features
is_trait_biased, linked_data = judge_and_remove_biased_features(linked_data, trait)
# 5. Validate and save dataset metadata
note = "Dataset contains gene expression data from rectus abdominis muscle biopsies, along with weight loss and clinical information from pancreatic cancer patients."
is_usable = validate_and_save_cohort_info(
is_final=True,
cohort=cohort,
info_path=json_path,
is_gene_available=True,
is_trait_available=True,
is_biased=is_trait_biased,
df=linked_data,
note=note
)
# 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) |