Learning utilities
mlpoppyns.learning.utils.benchmark
Network benchmarking.
Utility functions for benchmarking model performance. For more details see here.
Authors:
Alberto Garcia Garcia (garciagarcia@ice.csic.es)
benchmark(model, device, input_dummy, output_dummy)
Measure median time for forward/backward passes of a model on a device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
module
|
Model to benchmark. |
required |
device
|
device
|
Device in which the model will be executed. |
required |
input_dummy
|
tensor
|
Dummy tensor for input purposes. |
required |
output_dummy
|
tensor
|
Dummy tensor for output purposes. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[float, float]
|
A tuple that contains the median time spent in the forward pass and the backward pass, both in milliseconds. |
Source code in mlpoppyns/learning/utils/benchmark.py
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 | |
measure(model, device, input_dummy, output_dummy)
Measure timing for one single forward and backward pass with the model and the specified device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
module
|
Model to benchmark. |
required |
device
|
device
|
Device in which the model will be executed. |
required |
input_dummy
|
tensor
|
Dummy tensor for input purposes. |
required |
output_dummy
|
tensor
|
Dummy tensor for output purposes. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[float, float]
|
A tuple that contains the time spent in the forward pass and the runtime of the backward pass, both in seconds. |
Source code in mlpoppyns/learning/utils/benchmark.py
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 | |
mlpoppyns.learning.utils.data_folder_struct_sbi
Create data folder structure for running sbi.
Authors:
Celsa Pardo Araujo (pardo@ice.csic.es)
create_structure(base, structure)
Recursively creates a fixed directory and file structure on the filesystem.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
str
|
Base directory path where the folder structure will be created. |
required |
structure
|
Dict[str, Optional[dict]]
|
Nested dictionary representing the folder/file structure. |
required |
Source code in mlpoppyns/learning/utils/data_folder_struct_sbi.py
14 15 16 17 18 19 20 21 22 23 24 25 | |
mlpoppyns.learning.utils.json_utils
JSON utils.
Authors:
Alberto Garcia Garcia (garciagarcia@ice.csic.es)
read_json(filename)
Read a specified JSON file and generate an ordered dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filename
|
str
|
File path to the JSON file. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary containing the JSON information. |
Source code in mlpoppyns/learning/utils/json_utils.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
mlpoppyns.learning.utils.metric_tracker
Metric tracker.
Authors:
Alberto Garcia Garcia (garciagarcia@ice.csic.es)
MetricTracker
Metric tracker.
This class is responsible for keeping track of metrics throughout training and testing. It is able to update the values, add new metrics to be tracked, reset them all or extract higher-level info. such as averaging.
Source code in mlpoppyns/learning/utils/metric_tracker.py
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 | |
__init__(keys=None, writer=None)
Metric tracker initialization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
Optional[set]
|
A set of metric keys/identifiers to initialize the tracking. |
None
|
writer
|
Optional[SummaryWriter]
|
A TensorBoard writer to output metric info to. |
None
|
Source code in mlpoppyns/learning/utils/metric_tracker.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | |
avg(key)
Metric average.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Key of the metric. |
required |
Returns:
| Type | Description |
|---|---|
float
|
The average of that metric. |
Source code in mlpoppyns/learning/utils/metric_tracker.py
87 88 89 90 91 92 93 94 95 96 97 98 | |
reset()
Resets all tracked metrics values to zero.
Source code in mlpoppyns/learning/utils/metric_tracker.py
44 45 46 47 48 49 50 | |
result()
Results dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
The averages of all tracked metrics in a dictionary. |
Source code in mlpoppyns/learning/utils/metric_tracker.py
100 101 102 103 104 105 106 107 108 | |
update(key, value, n=1)
Metric update.
Updates a given metric adding the provided value and a specified count. If the metric is not yet tracked, it creates a new track for it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Identifier/key for the metric in the dictionary. |
required |
value
|
float
|
Value to add to the metric entry. |
required |
n
|
int
|
Count value. |
1
|
Source code in mlpoppyns/learning/utils/metric_tracker.py
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 | |
mlpoppyns.learning.utils.posterior_sampler
Sampler from a sbi posterior distribution.
Display help message to run the code:
python posterior_sampler.py --help
Displays all the relevant arguments that can be used.
Authors:
Celsa Pardo Araujo (pardo@ice.csic.es)
handler(signum, frame)
Signal handler that raises a TimeoutError when a SIGALRM signal is received. This function is needed in the sample_with_timeout function to raise an error if the sampling exceeds the maximum time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signum
|
int
|
The signal number. |
required |
frame
|
Any
|
The current stack frame. |
required |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
Indicates that the operation timed out. |
Source code in mlpoppyns/learning/utils/posterior_sampler.py
23 24 25 26 27 28 29 30 31 32 33 34 35 | |
sample_with_timeout(posterior, simulation_output, n_samples, timeout=180)
Perform sampling from the posterior distribution with a specified timeout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
posterior
|
DirectPosterior
|
Posterior distribution. |
required |
simulation_output
|
Tensor
|
Simulation output matrix. |
required |
n_samples
|
int
|
The number of samples to draw from the posterior distribution. |
required |
timeout
|
int
|
The maximum time in seconds to allow for n_samples to be drawn. Defaults to 180 seconds. |
180
|
Returns:
| Type | Description |
|---|---|
Tuple[Optional[Tensor], bool]
|
A tuple containing the result of the sampling (or None if it times out) and a boolean indicating whether the sampling was successful. |
Source code in mlpoppyns/learning/utils/posterior_sampler.py
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 | |
sampler(posterior, simulation_output, n_samples)
Perform sampling from the posterior distribution. This function is designed to be used with a signal handler to enforce a timeout during sampling, see below.
Args: posterior (DirectPosterior): Posterior distribution. simulation_output (torch.Tensor): Simulation output matrix. n_samples (int): The number of samples to draw from the posterior distribution.
Returns:
| Type | Description |
|---|---|
Tensor
|
The samples drawn from the posterior distribution. |
Source code in mlpoppyns/learning/utils/posterior_sampler.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | |
mlpoppyns.learning.utils.posterior_sampler_mcmc_sbi
Posterior Sampling Script for SNLE-Trained SBI Models
This script samples from the posterior distribution of an SNLE-trained method and computes the log probability for
each sample. Note that this is performed nchain times to create chains of posterior samples and log probability
to latter use them with the harmonic package (https://github.com/astro-informatics/harmonic) to compute the model
evidence at the observed data.
Display help message to run the code:
python posterior_sampler_mcmc_sbi.py --help
Displays all the relevant arguments that can be used.
Authors:
Celsa Pardo Araujo (pardo@ice.csic.es)
run_posterior_sampling(args)
Samples from the posterior distribution of an SNLE-trained SBI model and computes the log-probability of each sample. The process is repeated across multiple MCMC chains to facilitate evidence estimation using the harmonic package (https://github.com/astro-informatics/harmonic).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
args
|
Namespace
|
An argparse.Namespace object containing the following attributes:
|
required |
Source code in mlpoppyns/learning/utils/posterior_sampler_mcmc_sbi.py
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 | |
mlpoppyns.learning.utils.request_device
Request device.
Authors:
Alberto Garcia Garcia (garciagarcia@ice.csic.es)
request_device(logger, num_gpu=0)
Selects the requested devices for training/testing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logger
|
Logger
|
A logger to log information to. |
required |
num_gpu
|
int
|
Number of GPUs requested. |
0
|
Returns:
| Type | Description |
|---|---|
Tuple[device, list]
|
A tuple containing the kind of device the pipeline can run on and a list of devices if available. If no GPUs are available or zero are requested, the returned device is CPU. |
Source code in mlpoppyns/learning/utils/request_device.py
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 | |
mlpoppyns.learning.utils.sbi_builder
Builder of sbi.
Display help message to run the code:
python sbi_builder.py --help
Displays all the relevant arguments that can be used.
Authors:
Celsa Pardo Araujo (pardo@ice.csic.es)
build_inference_network(model_type, logger, config, device, prior)
Build an inference object (SNPE, SNLE, or SNRE) based on the selected model_type, using the provided configuration, device, and prior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_type
|
str
|
The inference model_type to use. Must be one of: "snpe", "snle", or "snre". |
required |
logger
|
Logger
|
Logger object. |
required |
config
|
ConfigurationParser
|
Configuration object that defines the architecture and training parameters for the model. |
required |
device
|
device
|
The device (CPU or GPU) on which to build and run the model. |
required |
prior
|
BoxUniform
|
The prior distribution over the parameters. |
required |
Returns:
| Type | Description |
|---|---|
Union[SNPE_C, SNLE_A, SNRE_B]
|
Union[SNPE_C, SNLE_A, SNRE_B]: An instance of the corresponding sbi inference class, depending on the model_type specified. |
Source code in mlpoppyns/learning/utils/sbi_builder.py
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 | |
compute_proposal_prior(posterior_obs, config, prior, device)
Compute the proposal prior by restricting the prior to the regions where the posterior of the observation has non-negligible probability mass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
posterior_obs
|
DirectPosterior
|
Posterior distribution at the observation. |
required |
config
|
ConfigurationParser
|
Configuration object specifying the model settings. |
required |
prior
|
BoxUniform
|
Prior distribution. |
required |
device
|
device
|
Device used to run the script. |
required |
Returns:
| Type | Description |
|---|---|
RestrictedPrior
|
The restricted prior based on the posterior distribution of the observation. |
Source code in mlpoppyns/learning/utils/sbi_builder.py
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 | |
initialize_inference(config, device, prior, logger, ensemble=False)
Initialize inference objects using the provided configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ConfigurationParser
|
Configuration object specifying the settings. |
required |
device
|
device
|
Device used to run the script. |
required |
prior
|
BoxUniform
|
Prior distribution used for inference. |
required |
logger
|
Logger
|
Logger object. |
required |
ensemble
|
bool
|
Flag indicating if ensemble mode is enabled. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[SNPE], List[SNLE], List[SNRE]]
|
List of initialized inference objects. |
Source code in mlpoppyns/learning/utils/sbi_builder.py
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 | |
initialize_prior(config, device, dataset)
Initialize the prior distribution for the model based on the configuration and dataset.
The prior is initialized as a uniform distribution over the parameter space. If the dataset is normalized or standardized, the prior is scaled accordingly to ensure that it fits the transformed space. If no normalization or standardization is applied, the prior is defined over the raw parameter space as specified in the configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ConfigurationParser
|
Configuration object specifying the model settings. |
required |
device
|
device
|
Device used to run the script. |
required |
dataset
|
DatasetMultichannelArray
|
Dataset where the statistics are saved. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
BoxUniform |
BoxUniform
|
The initialized prior distribution as a BoxUniform object. |
Source code in mlpoppyns/learning/utils/sbi_builder.py
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 | |
load_inference(config, round_number, save_dir, ensemble=False)
Load inference objects from pickle files. Note that this is used when resume mode is enabled or when doing inference with SNLE.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ConfigurationParser
|
Configuration object specifying the model settings. |
required |
round_number
|
int
|
The round number to load the inference from. |
required |
save_dir
|
Path
|
The directory to load the inference from. |
required |
ensemble
|
bool
|
Flag indicating if ensemble mode is enabled. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
Union[List[SNPE], List[SNLE], List[SNRE]]
|
A list of inference objects. |
Source code in mlpoppyns/learning/utils/sbi_builder.py
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 | |
load_posterior(config, logger, inference_list, device, round_current)
Load the trained density estimator for a given round.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ConfigurationParser
|
Configuration object specifying the model settings. |
required |
logger
|
Logger
|
Logger object. |
required |
inference_list
|
Union[List[SNPE], List[SNLE]]
|
List of sbi inference object. |
required |
device
|
device
|
Device used to run the script. |
required |
round_current
|
int
|
Current round number. This parameter starts at zero. |
required |
Returns:
| Type | Description |
|---|---|
Union[DirectPosterior, NeuralPosteriorEnsemble]
|
Trained density estimator or ensemble of estimators. |
Source code in mlpoppyns/learning/utils/sbi_builder.py
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 | |
train_posterior(config, save_dir_round, logger, inference_list, parameter_round, matrix_round, device, round_current, prof_log_path, prof_json_path, retrain_from_scratch=False, proposal=None)
Train the density estimator for a given round.
If resume is set to True in the configuration file, this mode allows training to continue from the last completed round if interrupted. It uses the previously saved state to resume training without starting over. If ensemble is set to True in the configuration file, multiple models (an ensemble) that differ only through their initialization are trained and their predictions are combined to ensure conservative coverages. Each of the neural networks will be trained on the same training dataset.
Note that the inference object should be different for each component of the ensemble to ensure independent weights
for each component. Moreover, if config['trainer']['model_type'] == 'snle' or 'snre', then a MCMC sampler is
needed to sample from the posterior distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ConfigurationParser
|
Configuration object specifying the model settings. |
required |
save_dir_round
|
Path
|
Directory where the trained model will be saved or is saved already. |
required |
logger
|
Logger
|
Logger object. |
required |
inference_list
|
Union[List[SNPE], List[SNLE]]
|
List of inference sbi objects. |
required |
parameter_round
|
Tensor
|
Tensor containing the parameters for the current round. |
required |
matrix_round
|
Tensor
|
Tensor containing the matrices for the current round. |
required |
device
|
device
|
Device used to run the script. |
required |
round_current
|
int
|
Current round number. This parameter starts at zero. |
required |
prof_json_path
|
str
|
The profile.json path. |
required |
prof_log_path
|
str
|
The profile.log path. |
required |
retrain_from_scratch
|
bool
|
Whether to retrain the conditional density estimator for the posterior from scratch each round. Default value is False. |
False
|
proposal
|
DirectPosterior
|
The proposal prior used in the current round. |
None
|
Returns:
| Type | Description |
|---|---|
Union[DirectPosterior, NeuralPosteriorEnsemble]
|
Trained density estimator or ensemble of estimators. |
Source code in mlpoppyns/learning/utils/sbi_builder.py
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 | |
mlpoppyns.learning.utils.sbi_utils
Sbi utilities.
Display help message to run the code:
python sbi_utils.py --help
Displays all the relevant arguments that can be used.
Authors:
Celsa Pardo Araujo (pardo@ice.csic.es)
calculate_smallest_hdr(posterior, theta, matrix, n_samples, logger, device)
Calculating the smallest highest density region of the posterior distribution, that contains the true value for the test dataset produced with the ground truths and simulation output stored in the arguments theta and matrix, respectively. Additionally, this function returns the posterior samples for each test case for further analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
posterior
|
DirectPosterior
|
Posterior distribution. |
required |
theta
|
tensor
|
Tensor containing the values of the parameters used to generate the simulated population in matrix. |
required |
matrix
|
tensor
|
Tensor containing the maps of the simulated population. |
required |
n_samples
|
int
|
The number of samples to draw from the posterior distribution. |
required |
logger
|
Logger
|
Logger object. |
required |
device
|
device
|
Device used to run the script. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
Smallest highest density region of the posterior that contains the true value, posterior samples for all test simulations. |
Source code in mlpoppyns/learning/utils/sbi_utils.py
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 | |
cnn_compression(n_samples, parameter, config, dataset, input_shape, logger, normalize, standardize)
Apply CNN-based compression to compress input samples using a previously trained embedding network.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
Number of samples in the dataset. |
required |
parameter
|
ndarray
|
Array to store physical parameters (theta). |
required |
config
|
ConfigurationParser
|
Configuration including the CNN compression model path. |
required |
dataset
|
DatasetMultichannelArray
|
Dataset object. |
required |
input_shape
|
Tuple[int, int, int]
|
Expected input shape. |
required |
logger
|
Logger
|
Logger for reporting. |
required |
normalize
|
bool
|
Whether to normalize embedded values. |
required |
standardize
|
bool
|
Whether to standardize embedded values. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
Parameter array (theta) of shape (n_samples, n_parameters), CNN-compressed input array of shape (n_samples, len_output_layer). |
Source code in mlpoppyns/learning/utils/sbi_utils.py
740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 | |
compute_rank_coverage(save_dir, parameter, matrix, posterior, device, parameter_labels, logger, effective_round)
Compute and visualize ranks and coverage probability for a test dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_dir
|
pathlib
|
Directory to save the computed results and plots. |
required |
parameter
|
Tensor
|
Tensor containing the parameters for the test dataset in the current round. |
required |
matrix
|
Tensor
|
Tensor containing the matrices for the test dataset in the current round. |
required |
posterior
|
DirectPosterior
|
Approximated posterior distribution. |
required |
device
|
device
|
Device used to run the script. |
required |
parameter_labels
|
List[str]
|
Labels for the parameters in the test dataset. |
required |
logger
|
Logger
|
Logger object. |
required |
effective_round
|
int
|
Number of the effective round during the sequential inference approach. Note that when resume is False, the effective round is the same as the actual round. On the other hand, if resume mode is enabled, effective_round = last_completed_round + actual_round. |
required |
Source code in mlpoppyns/learning/utils/sbi_utils.py
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 | |
corner_plot(observed_samples, dataset, save_dir)
Plotting the corner plot for the posterior distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
observed_samples
|
tensor
|
Samples of the distribution to plot. |
required |
dataset
|
DatasetMultichannelArray
|
Dataset where the statistics are saved. |
required |
save_dir
|
str
|
Directory to save the corner plot. |
required |
Source code in mlpoppyns/learning/utils/sbi_utils.py
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 | |
initialize_environment(config, logger)
Set device, profiling paths, and optionally Dask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ConfigurationParser
|
Configuration object specifying the model settings. |
required |
logger
|
Logger
|
Logger object. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[device, HTCondorCluster, str, str]
|
A tuple containing the selected device, the optional Dask cluster, the profiling log path, and the profiling JSON path. |
Source code in mlpoppyns/learning/utils/sbi_utils.py
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 | |
merge_all_rounds_dataset(base_path, last_completed_round)
Merge all dataset_full.csv files from each round into a single DataFrame. This is necessary in resume mode because, during the first round of resuming the training, we need to load all the previous training datasets from the earlier rounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_path
|
Path
|
The base path where the generated datasets are stored. |
required |
last_completed_round
|
int
|
Last completed round number. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path to the merged dataset. |
Source code in mlpoppyns/learning/utils/sbi_utils.py
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 | |
pca_compression(n_samples, input_shape, dataset, logger, config, parameter, normalize, standardize)
Compress input samples using a pre-trained PCA model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
Number of samples in the dataset. |
required |
input_shape
|
Tuple[int, int, int]
|
Expected shape of each input sample. |
required |
dataset
|
DatasetMultichannelArray
|
Dataset object. |
required |
logger
|
Logger
|
Logger object for error reporting. |
required |
config
|
ConfigurationParser
|
Configuration containing the PCA model path. |
required |
parameter
|
ndarray
|
Array to store extracted physical parameters. |
required |
normalize
|
bool
|
Whether to normalize compressed values between 0 and 1. |
required |
standardize
|
bool
|
Whether to standardize compressed values to zero mean and unit variance. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
Parameter array (theta) of shape (n_samples, n_parameters), PCA-compressed input array of shape (n_samples, n_pca_components). |
Source code in mlpoppyns/learning/utils/sbi_utils.py
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 | |
prepare_dataset_sbi(dataset_folder, config, logger, atnf=False)
Prepare dataset for use in sbi. If compression is enabled, either PCA or CNN compression will be applied to the input matrix tensor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_folder
|
str
|
Path to the folder where the dataset is saved. |
required |
config
|
ConfigurationParser
|
Configuration object specifying the model settings. |
required |
logger
|
Logger
|
Logger object. |
required |
atnf
|
bool
|
Indicates whether the PPdot density maps in the 'train_data_set' folder correspond to the observed population or to a simulated population. If set to True, the simulations correspond to the observed ATNF population. The default is False. |
False
|
Returns:
| Type | Description |
|---|---|
Tuple[DatasetMultichannelArray, tensor, tensor]
|
A tuple containing the dataset containing the statistics, parameter tensor and input matrix tensor. |
Source code in mlpoppyns/learning/utils/sbi_utils.py
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 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 | |
raw_vector(n_samples, input_shape, dataset, logger, parameter)
Load raw data vectors without compression for use as input to the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
Number of samples in the dataset. |
required |
input_shape
|
ndarray
|
Shape of input sample. |
required |
dataset
|
DatasetMultichannelArray
|
Dataset to extract raw vectors from. |
required |
logger
|
Logger
|
Logger for error reporting. |
required |
parameter
|
ndarray
|
Array with the physical parameters. |
required |
Returns:
| Type | Description |
|---|---|
Tuple[ndarray, ndarray]
|
Tensor of physical parameters (theta), Tensor of raw input vectors with shape (n_samples, *input_shape). |
Source code in mlpoppyns/learning/utils/sbi_utils.py
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 | |
save_training_statistics(config, inference, index, effective_round)
Save training statistics including scalars and training/validation loss plots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ConfigurationParser
|
Configuration object specifying the model settings. |
required |
inference
|
Union[SNPE_C, SNLE_A]
|
sbi inference object. |
required |
index
|
int
|
The ensemble index, if ensemble is set to False index is equal to 0. |
required |
effective_round
|
int
|
Number of the effective round during the sequential inference approach. Note that when resume is False, the effective round is the same as the actual round. On the other hand, if resume mode is enabled, effective_round = last_completed_round + actual_round. |
required |
Source code in mlpoppyns/learning/utils/sbi_utils.py
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 | |
wrapper_mlpoppyns(proposal, num_sim, config, effective_round, test, dataset, device)
Simulating num_sim of mock neutron star populations given the proposal distribution.
After simulation, generate density maps from the resulting populations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
proposal
|
Union[DirectPosterior, RestrictedPrior]
|
Proposal distribution used for sampling the parameters. |
required |
num_sim
|
int
|
Number of simulations to perform. |
required |
config
|
ConfigurationParser
|
Configuration object specifying the model settings. |
required |
effective_round
|
int
|
Number of the effective round during the sequential inference approach. Note that when resume is False, the effective round is the same as the actual round. On the other hand, if resume mode is enabled, effective_round = last_completed_round + actual_round. |
required |
test
|
bool
|
Flag indicating whether the simulations are for testing or training. If set to True, the simulations are for testing purposes. |
required |
dataset
|
DatasetMultichannelArray
|
Dataset where the statistics are saved. |
required |
device
|
device
|
Device used to run the script. |
required |
Returns:
| Type | Description |
|---|---|
str
|
Path to the generated dataset. |
Source code in mlpoppyns/learning/utils/sbi_utils.py
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 | |