Repository navigation
Expand file tree
/
Copy pathdata.py
More file actions
617 lines (526 loc) · 24 KB
/
Copy pathdata.py
File metadata and controls
617 lines (526 loc) · 24 KB
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
import torch
from torch.utils.data import DataLoader, TensorDataset
import pandas as pd
from pathlib import Path
from typing import Union, Dict, List, Tuple
import yaml
from torch.utils.data.distributed import DistributedSampler
from preprocessing import DataPreprocessor
import json
class LHCbMCModule:
def __init__(
self,
train_data_path: Union[str, Path],
test_data_path: Union[str, Path],
) -> None:
"""Initializes the LHCbMCModule with paths to training and testing data."""
self.train_path = train_data_path
self.test_path = test_data_path
self._preprocessor = None # Will be initialized in setup
@staticmethod
def _get_features_config_path(filename: str) -> Path:
"""Find configuration file across possible locations."""
possible_paths = [
Path(f"{filename}"), # Relative to working directory
Path(f"config/{filename}"), # Relative to working directory
Path(__file__).parent / f"../config/{filename}", # Relative to this file
Path(__file__).parent / f"../{filename}", # Relative to this file
Path(
f"/work/submit/blaised/TopoNNOps/config/{filename}"
), # Original absolute path
]
for path in possible_paths:
if path.exists():
return path
raise FileNotFoundError(f"Could not find {filename} in any expected location")
@staticmethod
def feature_config(
model: str = "TwoBody", feature_config_file: str = "features.yml"
) -> dict:
"""Read in the user-defined YAML pipeline configuration."""
assert model in ["TwoBody", "ThreeBody"], f"Model {model} not supported"
# read in the user-defined YAML pipeline configuration
with open(
LHCbMCModule._get_features_config_path(feature_config_file), "r"
) as f:
config = yaml.safe_load(f)
# return the feature dict
return config["features"][model]
@staticmethod
def spectator_config(
model: str = "TwoBody", feature_config_file: str = "features.yml"
) -> dict:
"""Read spectator variables configuration from YAML."""
assert model in ["TwoBody", "ThreeBody"], f"Model {model} not supported"
# read in the user-defined YAML pipeline configuration
with open(
LHCbMCModule._get_features_config_path(feature_config_file), "r"
) as f:
config = yaml.safe_load(f)
# Return empty dict if no spectators section
if "spectators" not in config:
return {}
# Return spectator dict for specified model
return config["spectators"].get(model, {})
@staticmethod
def remove_nan_rows(
df: pd.DataFrame, feature_cols: List[str], dataset_name: str = ""
):
"""
Remove rows with NaN values in feature columns and abort if NaN rows exceed 1%.
Args:
df: pandas DataFrame to process
feature_cols: list of feature column names to check for NaNs
dataset_name: name of the dataset for logging purposes
Returns:
Processed DataFrame with NaN rows removed
Raises:
ValueError: If more than 1% of rows contain NaN values
"""
# Check for NaN values in the feature columns
nan_rows = df[feature_cols].isna().any(axis=1)
nan_count = nan_rows.sum()
nan_percent = (nan_count / len(df)) * 100
print(
f"Found {nan_count} NaN rows in {dataset_name} data with total size {len(df)} ({nan_percent:.2f}%)"
)
# Verify NaN percentage is below threshold
if nan_percent > 20.0:
raise ValueError(
f"Detected NaN candidates above tolerance: {nan_percent:.2f}% (threshold: 1.0%)"
)
# Remove NaN rows & report
df_clean = df[~nan_rows]
print(
f"Removed NaN rows from {dataset_name} data. New size: {len(df_clean)} [{len(df_clean)/len(df)*100:.2f}% of original size]"
)
return df_clean
@staticmethod
def transforms_config(
model: str = "TwoBody", feature_config_file: str = "features.yml"
) -> dict:
"""Read in the transformation configuration for preprocessing."""
assert model in ["TwoBody", "ThreeBody"], f"Model {model} not supported"
# read in the user-defined YAML pipeline configuration
with open(
LHCbMCModule._get_features_config_path(feature_config_file), "r"
) as f:
config = yaml.safe_load(f)
# Check if transforms section exists
transforms = {}
if "transforms" in config:
key = (
"transforms" if "transforms" in config else "preprocessing"
) # for backwards compatibility
# Fix possible spelling differences (TwoBoody vs TwoBody)
model_key = model
if model == "TwoBody" and "TwoBoody" in config[key]:
model_key = "TwoBoody"
elif model == "ThreeBody" and "ThreeBoody" in config[key]:
model_key = "ThreeBoody"
if model_key in config[key]:
transforms = config[key][model_key]
return transforms
@staticmethod
def get_n_features(model: str = "TwoBody") -> int:
"""Returns the number of features for the specified model"""
return len(LHCbMCModule.feature_config(model=model).keys())
def _initialize_preprocessor(
self, feature_config_file: str = "features.yml", model: str = "TwoBody"
) -> None:
"""Initialize the DataPreprocessor with transformation configs"""
# Get transformation configs
transforms_dict = self.transforms_config(
model=model, feature_config_file=feature_config_file
)
# Get feature list to identify unchanged vars
feature_list = list(
self.feature_config(
model=model, feature_config_file=feature_config_file
).keys()
)
# Prepare lists for each transformation type
gev_vars = []
log_vars = []
tenx_vars = []
ps_vars = []
unchanged_vars = []
# Parse the transformations
for feature in feature_list:
transform_type = transforms_dict.get(feature, None)
if transform_type == "gev":
gev_vars.append(feature)
elif transform_type == "log":
log_vars.append(feature)
elif transform_type == "tenx":
tenx_vars.append(feature)
elif transform_type == "ps":
ps_vars.append(feature)
else:
# Any feature without an explicit transform goes to unchanged_vars
unchanged_vars.append(feature)
# sanity check: all features preserved + no erroenous inclusion of observables as features (which we woudl need for efficiency plots)
assert len(gev_vars) + len(log_vars) + len(unchanged_vars) + len(
tenx_vars
) + len(ps_vars) == len(
feature_list
), "Number of features in the preprocessor does not match the number of features in the config file"
assert (
len(unchanged_vars) == 0
), "Unchanged variables not implemented in the LHCb stack"
# Create preprocessor with proper configs
self._preprocessor = DataPreprocessor(
gev_vars=tuple(gev_vars),
log_vars=tuple(log_vars),
tenx_vars=tuple(tenx_vars),
ps_vars=tuple(ps_vars),
unchanged_vars=tuple(unchanged_vars),
background_channel="minbias",
clip_quantiles=(0.001, 0.999),
normalize=False, # NOTE: remove for clipping but no minmax scaling
)
# expose the processor to access it in visualize.py
@property
def preprocessor(self):
"""Expose the preprocessor for external use"""
return self._preprocessor if hasattr(self, "_preprocessor") else None
def _process_sb_data(
self,
train_data: pd.DataFrame,
scale_factor: float = 1.0,
ratio: float = 0.1,
balance: bool = True,
):
"""Setup with controlled background-to-signal ratio and scale factor"""
# Split background and signal
background = train_data[train_data["channel"] == "minbias"]
signal = train_data[train_data["channel"] != "minbias"]
# Calculate samples to take
n_background = int(len(background) * scale_factor)
if ratio:
n_signal = int(
n_background * ratio
) # Maintains minbias:<individual signal channel> ratio
else:
n_signal = len(signal)
# Sample the data
background_sample = background.sample(n=n_background)
signal_sample = signal.sample(n=n_signal)
# Combine and create final dataset
train_data = pd.concat([background_sample, signal_sample])
return train_data
def get_channel_information(self, dataset_type="test"):
"""
Get channel information for training or test dataset.
Args:
dataset_type: 'train' or 'test' to specify which dataset
Returns:
Array of channel labels
"""
if dataset_type == "train":
data = pd.read_pickle(self.train_path)
else: # test
data = pd.read_pickle(self.test_path)
return data["channel"].values
def setup(
self,
batch_size: int = 128,
scale_factor: float = 1.0,
ratio: float = 0.1,
feature_config_file: str = "features.yml",
apply_preprocessing: bool = True,
balance_train_sample: bool = False,
model: str = "TwoBody",
remove_nan_rows: bool = True,
include_spectators: bool = True,
):
"""Setup the DataLoaders for training and testing data with preprocessing."""
# Load and sample the data
train_data = self._process_sb_data(
pd.read_pickle(self.train_path),
scale_factor=scale_factor,
ratio=ratio,
)
# Load the test data with the same sampling
test_data = self._process_sb_data(
pd.read_pickle(self.test_path),
scale_factor=scale_factor,
ratio=ratio,
)
# Store the channel information
self.train_channels = train_data["channel"].values
self.test_channels = test_data["channel"].values
# fetch the features
self.feature_cols = [feat for feat in self.feature_config(model=model).keys()]
assert len(self.feature_cols) > 0, "No features found in the config file"
# fetch the spectators - can be empty
self.spectator_cols = []
if include_spectators:
self.spectator_cols = [
feat for feat in self.spectator_config(model=model).keys()
]
# print the spectators if any
if self.spectator_cols:
print(f"Using spectator variables for decorrelation: {self.spectator_cols}")
assert all(
spec in train_data.columns for spec in self.spectator_cols
), f"Missing spectator variables in training data: {[spec for spec in self.spectator_cols if spec not in train_data.columns]}"
# Check if the feature columns are in the train_data keys
assert all(
feat in train_data.columns for feat in self.feature_cols
), f"Missing features in training data: {[feat for feat in self.feature_cols if feat not in train_data.columns]}"
# HACK: store the full datasets (not just the loaders) - to enable access to channel info for efficiency histograms
self.raw_train_data = train_data.copy()
self.raw_test_data = test_data.copy()
# need at least 3 tracks in the final state for 3-body decays
if model == "ThreeBody":
insufficient_multiplicity_channels = [
"Lb_pmunu",
"Bd_Kstgmma",
"Bs_mumu",
"Kmunu",
]
train_data = train_data[
~train_data["channel"].isin(insufficient_multiplicity_channels)
]
test_data = test_data[
~test_data["channel"].isin(insufficient_multiplicity_channels)
]
print(
f"Removed {len(insufficient_multiplicity_channels)} channels with insufficient multiplicity from the training and test data: {insufficient_multiplicity_channels}"
)
# Apply preprocessing if requested
if apply_preprocessing:
# Initialize the preprocessor with transformation configs
self._initialize_preprocessor(
feature_config_file=feature_config_file, model=model
)
# Apply preprocessing to train and test data
# Only preprocess the feature columns and shuffle completely
# shuffle to ensure complete mixing of signal and background - even at small stats
# Prepare data subset with features, labels, channels, and spectators
subset_train = train_data[
self.feature_cols + ["class_label", "channel"] + self.spectator_cols
].sample(frac=1.0, random_state=42)
subset_test = test_data[
self.feature_cols + ["class_label", "channel"] + self.spectator_cols
].sample(frac=1.0, random_state=42)
# Remove NaN rows if requested within a tolerance of 1%
if remove_nan_rows:
if self.spectator_cols:
cleanup_cols = self.feature_cols + self.spectator_cols
else:
cleanup_cols = self.feature_cols
subset_train = LHCbMCModule.remove_nan_rows(
subset_train, cleanup_cols, "training"
)
subset_test = LHCbMCModule.remove_nan_rows(
subset_test, cleanup_cols, "test"
)
# Fit and transform on training data
processed_train = self._preprocessor.fit_transform(
subset_train, balance=balance_train_sample
)
# ------------------------------------------------------------------------------------------------
# Export bounds post scaling for stack integration
# ================================================================================================
# export the feature bounds to json file in the format feature: [lower bound, upper bound]
feature_bounds = {}
for feat in self.feature_cols:
feature_bounds[feat] = [
float(self._preprocessor.feature_stats[f"{feat}_lower"]),
float(self._preprocessor.feature_stats[f"{feat}_upper"]),
]
# Print feature bounds for debugging and verification
print("\nFeature bounds after preprocessing:")
print(feature_bounds)
# save the feature bounds to a json file
with open(f"feature_bounds_postscaling_{model}.json", "w") as f:
json.dump(feature_bounds, f)
# ------------------------------------------------------------------------------------------------
# Transform test data using the same fitted preprocessor
processed_test = self._preprocessor.transform(subset_test)
# Extract the processed feature columns AND target
X_train = torch.tensor(
processed_train[self.feature_cols].values, dtype=torch.float32
)
y_train = torch.tensor(
processed_train["class_label"].values, dtype=torch.float32
)
X_test = torch.tensor(
processed_test[self.feature_cols].values, dtype=torch.float32
)
y_test = torch.tensor(
processed_test["class_label"].values, dtype=torch.float32
)
# Extract spectator variables if present
if self.spectator_cols:
# Apply appropriate transformations to spectators
for spec in self.spectator_cols:
transform_type = (
self.transforms_config(model=model)[spec]
if spec in self.transforms_config(model=model)
else None
)
if transform_type == "ps":
# convert from rescale to ps
processed_train[spec] = processed_train[spec] * 1000.0
processed_test[spec] = processed_test[spec] * 1000.0
# Create tensors from spectator variables
spec_train = torch.tensor(
processed_train[self.spectator_cols].values, dtype=torch.float32
)
spec_test = torch.tensor(
processed_test[self.spectator_cols].values, dtype=torch.float32
)
# Store for future use
self.spectators_train = spec_train
self.spectators_test = spec_test
else:
# Use raw unprocessed data
X_train = torch.tensor(
train_data[self.feature_cols].values, dtype=torch.float32
)
y_train = torch.tensor(
train_data["class_label"].values, dtype=torch.float32
)
X_test = torch.tensor(
test_data[self.feature_cols].values, dtype=torch.float32
)
y_test = torch.tensor(test_data["class_label"].values, dtype=torch.float32)
# HACK - print the population to get a feel for the signal abundance relative to bkg
print(f"Ad-hoc debug: {processed_train.channel.value_counts()}")
# Store the tensors for direct access
self.X_train = X_train
self.y_train = y_train
self.X_test = X_test
self.y_test = y_test
# Create appropriate TensorDatasets, adding the spectators if present
if hasattr(self, "spectators_train") and hasattr(self, "spectators_test"):
train_dataset = torch.utils.data.TensorDataset(
X_train, y_train, self.spectators_train
)
test_dataset = torch.utils.data.TensorDataset(
X_test, y_test, self.spectators_test
)
else:
train_dataset = torch.utils.data.TensorDataset(X_train, y_train)
test_dataset = torch.utils.data.TensorDataset(X_test, y_test)
# create the dataloaders
self.train_loader = DataLoader(
train_dataset, batch_size=batch_size, shuffle=True
)
self.test_loader = DataLoader(
test_dataset, batch_size=batch_size, shuffle=True
) # NOTE: shuffling aids the inclusion of both classes in each batch - less important if I balance the dataset beforehand; can cause training instability in test loss
self.input_dim = len(self.feature_cols)
def setup_for_viz(
self,
batch_size: int = 128,
scale_factor: float = 1.0,
ratio: Union[float, None] = None,
feature_config_file: str = "features.yml",
apply_preprocessing: bool = False,
balance_train_sample: bool = False,
model: str = "TwoBody",
):
"""Ad-hoc loader and preprocessor to generate MC-only performance plots."""
# Load and sample the data
train_data = self._process_sb_data(
pd.read_pickle(self.train_path),
scale_factor=scale_factor,
ratio=ratio,
)
# Load the test data with the same sampling
test_data = self._process_sb_data(
pd.read_pickle(self.test_path),
scale_factor=scale_factor,
ratio=ratio,
)
# Store the channel information
self.train_channels = train_data["channel"].values
self.test_channels = test_data["channel"].values
# fetch the features
self.feature_cols = [feat for feat in self.feature_config(model=model).keys()]
assert len(self.feature_cols) > 0, "No features found in the config file"
# Check if the feature columns are in the train_data keys
assert all(
feat in train_data.columns for feat in self.feature_cols
), f"Missing features in training data: {[feat for feat in self.feature_cols if feat not in train_data.columns]}"
# HACK: store the full datasets (not just the loaders) - to enable access to channel info for efficiency histograms
self.raw_train_data = train_data.copy()
self.raw_test_data = test_data.copy()
# Apply preprocessing if requested
if apply_preprocessing:
# Initialize the preprocessor with transformation configs
self._initialize_preprocessor(
feature_config_file=feature_config_file, model=model
)
# Apply preprocessing to train and test data
# Only preprocess the feature columns
subset_train = train_data[self.feature_cols + ["class_label", "channel"]]
# add extra info for efficiency histograms (on test data only)
subset_test = test_data[
self.feature_cols
+ [
"class_label",
"channel",
"TwoBody_MC_LIFETIME",
]
] # add lifetime in testing for efficiency histograms
subset_test["TwoBody_PT_unscaled"] = test_data[
"TwoBody_PT"
] # add original PT for efficiency histograms - no scaling/preprocessing applied
# Fit and transform on training data
processed_train = self._preprocessor.fit_transform(
subset_train, balance=balance_train_sample
)
# Transform test data using the same fitted preprocessor
processed_test = self._preprocessor.transform(
subset_test
) # NOTE: transformed with eff observables
# Extract the processed feature columns AND target
X_train = torch.tensor(
processed_train[self.feature_cols].values, dtype=torch.float32
)
y_train = torch.tensor(
processed_train["class_label"].values, dtype=torch.float32
)
X_test = torch.tensor(
processed_test[self.feature_cols].values, dtype=torch.float32
)
y_test = torch.tensor(
processed_test["class_label"].values, dtype=torch.float32
)
else:
# Use raw unprocessed data
X_train = torch.tensor(
train_data[self.feature_cols].values, dtype=torch.float32
)
y_train = torch.tensor(
train_data["class_label"].values, dtype=torch.float32
)
X_test = torch.tensor(
test_data[self.feature_cols].values, dtype=torch.float32
)
y_test = torch.tensor(test_data["class_label"].values, dtype=torch.float32)
# HACK - print the population to get a feel for the signal abundance relative to bkg
print(f"Ad-hoc debug: {processed_train.channel.value_counts()}")
# Store the tensors for direct access
self.X_train = X_train
self.y_train = y_train
self.X_test = X_test
self.y_test = y_test
# HACK: expose the processed data for efficiency histograms
self.processed_test_data_w_obs = processed_test
# put together the dataset
train_dataset = TensorDataset(X_train, y_train)
test_dataset = TensorDataset(X_test, y_test)
# create the dataloaders
self.train_loader = DataLoader(
train_dataset, batch_size=batch_size, shuffle=True
)
self.test_loader = DataLoader(
test_dataset, batch_size=batch_size, shuffle=True
) # NOTE: shuffling aids the inclusion of both classes in each batch - less important if I balance the dataset beforehand; can cause training instability in test loss
self.input_dim = len(self.feature_cols)