bax-algorithms 0.1.2__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/.github/workflows/tests.yml +1 -1
  2. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/PKG-INFO +3 -4
  3. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms/_version.py +3 -3
  4. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms/emittance.py +93 -32
  5. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms/pathwise/base.py +4 -24
  6. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms/solenoid_alignment.py +50 -32
  7. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms/visualize.py +170 -1
  8. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms.egg-info/PKG-INFO +3 -4
  9. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms.egg-info/SOURCES.txt +2 -0
  10. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms.egg-info/requires.txt +1 -1
  11. bax_algorithms-0.1.3/bax_algorithms.egg-info/scm_file_list.json +26 -0
  12. bax_algorithms-0.1.3/bax_algorithms.egg-info/scm_version.json +8 -0
  13. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/examples/emittance.ipynb +7 -39
  14. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/examples/solenoid_alignment.ipynb +10 -10
  15. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/pyproject.toml +2 -3
  16. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/tests/test_emittance.py +2 -2
  17. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/.gitattributes +0 -0
  18. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/.github/workflows/lint.yml +0 -0
  19. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/.github/workflows/pypi_upload.yml +0 -0
  20. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/.gitignore +0 -0
  21. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/.pre-commit-config.yaml +0 -0
  22. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/LICENSE +0 -0
  23. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/README.md +0 -0
  24. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms/__init__.py +0 -0
  25. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms/pathwise/optimize.py +0 -0
  26. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms/pathwise/sampling.py +0 -0
  27. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms/utils.py +0 -0
  28. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms.egg-info/dependency_links.txt +0 -0
  29. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/bax_algorithms.egg-info/top_level.txt +0 -0
  30. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/examples/pathwise_tutorial.ipynb +0 -0
  31. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/setup.cfg +0 -0
  32. {bax_algorithms-0.1.2 → bax_algorithms-0.1.3}/tests/test_solenoid_alignment.py +0 -0
@@ -13,7 +13,7 @@ jobs:
13
13
  strategy:
14
14
  fail-fast: false
15
15
  matrix:
16
- python-version: ["3.10", "3.11", "3.12", "3.13"]
16
+ python-version: ["3.11", "3.12", "3.13"]
17
17
 
18
18
  name: Python ${{ matrix.python-version }}
19
19
  steps:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bax_algorithms
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Collection of algorithms that can be used in Bayesian Algorithm Execution (BAX) Xopt generators.
5
5
  Author: Dylan Kennedy, Sean Gasiorowski, Samuel Klein
6
6
  License: Apache License
@@ -209,13 +209,12 @@ Project-URL: Homepage, https://github.com/xopt-org/bax_algorithms
209
209
  Keywords: machine learning,accelerator physics
210
210
  Classifier: Natural Language :: English
211
211
  Classifier: Programming Language :: Python :: 3 :: Only
212
- Classifier: Programming Language :: Python :: 3.10
213
212
  Classifier: Programming Language :: Python :: 3.11
214
213
  Classifier: Programming Language :: Python :: 3.12
215
214
  Classifier: Programming Language :: Python :: 3.13
216
215
  Classifier: Intended Audience :: Science/Research
217
216
  Classifier: Topic :: Scientific/Engineering
218
- Requires-Python: >=3.10
217
+ Requires-Python: >=3.11
219
218
  Description-Content-Type: text/markdown
220
219
  License-File: LICENSE
221
220
  Requires-Dist: numpy
@@ -223,7 +222,7 @@ Requires-Dist: botorch>=0.8.5
223
222
  Requires-Dist: gpytorch>=1.10
224
223
  Requires-Dist: pydantic>=1.10.9
225
224
  Requires-Dist: scipy>=1.10.1
226
- Requires-Dist: xopt>=2.6.11
225
+ Requires-Dist: xopt>=3.1.2
227
226
  Requires-Dist: jupyterlab>=3
228
227
  Provides-Extra: dev
229
228
  Requires-Dist: pytest; extra == "dev"
@@ -18,7 +18,7 @@ version_tuple: tuple[int | str, ...]
18
18
  commit_id: str | None
19
19
  __commit_id__: str | None
20
20
 
21
- __version__ = version = '0.1.2'
22
- __version_tuple__ = version_tuple = (0, 1, 2)
21
+ __version__ = version = '0.1.3'
22
+ __version_tuple__ = version_tuple = (0, 1, 3)
23
23
 
24
- __commit_id__ = commit_id = 'g2ece0b40e'
24
+ __commit_id__ = commit_id = 'gb41cacfc2'
@@ -1,4 +1,5 @@
1
- from pydantic import Field
1
+ from pydantic import Field, PositiveInt
2
+ from typing import Optional
2
3
  import torch
3
4
  from torch import Tensor
4
5
 
@@ -7,7 +8,11 @@ from bax_algorithms.pathwise.base import PathwiseOptimization
7
8
  from bax_algorithms.pathwise.sampling import draw_product_kernel_post_paths
8
9
  from botorch.sampling.pathwise.posterior_samplers import draw_matheron_paths
9
10
  from botorch.models.model import Model
10
- from xopt.generators.bayesian.bax.algorithms import Algorithm
11
+ from xopt.generators.bayesian.bax.algorithms import (
12
+ Algorithm,
13
+ OptimizationAlgorithmResult,
14
+ VirtualMeasurementResult,
15
+ )
11
16
 
12
17
  import numpy as np
13
18
  from scipy.optimize import minimize
@@ -438,6 +443,23 @@ def compute_emit_bmag_quad_scan(
438
443
  return rv
439
444
 
440
445
 
446
+ class VirtualEmittanceMeasurementResult(VirtualMeasurementResult):
447
+ emittance_x: Optional[Tensor] = Field(
448
+ default=None,
449
+ description="The geometric emittance in the x transverse dimension.",
450
+ )
451
+ emittance_y: Optional[Tensor] = Field(
452
+ default=None,
453
+ description="The geometric emittance in the y transverse dimension.",
454
+ )
455
+ bmag_x: Optional[Tensor] = Field(
456
+ default=None, description="The Bmag in the x transverse dimension."
457
+ )
458
+ bmag_y: Optional[Tensor] = Field(
459
+ default=None, description="The Bmag in the y transverse dimension."
460
+ )
461
+
462
+
441
463
  class EmittanceAlgorithm(Algorithm):
442
464
  x_key: str = Field(
443
465
  None,
@@ -518,7 +540,7 @@ class EmittanceAlgorithm(Algorithm):
518
540
  at which to evaluate the objective.
519
541
  bounds: tensor shape (2, n_dim) specifying the upper and lower measurement bounds
520
542
  returns:
521
- result: dict containing measurement results
543
+ VirtualEmittanceMeasurementResult
522
544
  """
523
545
  tuning_idxs = torch.arange(bounds.shape[1])
524
546
  tuning_idxs = tuning_idxs[
@@ -536,21 +558,26 @@ class EmittanceAlgorithm(Algorithm):
536
558
  )
537
559
 
538
560
  # store virtual measurement results
539
- result = {}
561
+ result = {
562
+ "emittance_x": None,
563
+ "emittance_y": None,
564
+ "bmag_x": None,
565
+ "bmag_y": None,
566
+ }
540
567
  if self.x_key:
541
- result["emit_x"] = emit[..., self.x_idx]
568
+ result["emittance_x"] = emit[..., self.x_idx]
542
569
  best_bmag_x = torch.min(bmag[..., self.x_idx], dim=-1, keepdim=True)[0]
543
570
  result["bmag_x"] = best_bmag_x
544
- objective = result["emit_x"]
571
+ objective = result["emittance_x"]
545
572
  mean_bmag = result["bmag_x"]
546
573
  if self.y_key:
547
- result["emit_y"] = emit[..., self.y_idx]
574
+ result["emittance_y"] = emit[..., self.y_idx]
548
575
  best_bmag_y = torch.min(bmag[..., self.y_idx], dim=-1, keepdim=True)[0]
549
576
  result["bmag_y"] = best_bmag_y
550
- objective = result["emit_y"]
577
+ objective = result["emittance_y"]
551
578
  mean_bmag = result["bmag_y"]
552
579
  if self.x_key and self.y_key:
553
- objective = (result["emit_x"] * result["emit_y"]).sqrt()
580
+ objective = (result["emittance_x"] * result["emittance_y"]).sqrt()
554
581
  best_bmag_idcs = torch.min(
555
582
  (bmag[..., self.x_idx] * bmag[..., self.y_idx]), dim=-1, keepdim=True
556
583
  )[1]
@@ -562,9 +589,14 @@ class EmittanceAlgorithm(Algorithm):
562
589
  if self.use_bmag:
563
590
  objective *= mean_bmag
564
591
 
565
- result["objective"] = objective
566
-
567
- return result
592
+ algorithm_result = VirtualEmittanceMeasurementResult(
593
+ objective=objective,
594
+ emittance_x=result["emittance_x"],
595
+ emittance_y=result["emittance_y"],
596
+ bmag_x=result["bmag_x"],
597
+ bmag_y=result["bmag_y"],
598
+ )
599
+ return algorithm_result
568
600
 
569
601
  def get_meas_scan_inputs(
570
602
  self, x_tuning: Tensor, bounds: Tensor, tkwargs: dict = None
@@ -758,28 +790,57 @@ class EmittanceAlgorithm(Algorithm):
758
790
 
759
791
 
760
792
  class PathwiseMinimizeEmittance(EmittanceAlgorithm, PathwiseOptimization):
761
- def get_execution_paths(self, model: Model, bounds: Tensor) -> Tensor:
762
- # draw callable sample functions
763
- sample_functions_list = self.draw_sample_functions_list(model)
764
-
765
- best_inputs = self.execute_algorithm(sample_functions_list, bounds)
766
- best_meas_scan_inputs = self.get_meas_scan_inputs(best_inputs, bounds)
767
- best_meas_scan_outputs = torch.vstack(
768
- [
769
- sample_func(best_meas_scan_inputs)
770
- for sample_func in sample_functions_list
771
- ]
772
- ).T.unsqueeze(0)
773
- best_emit, best_bmag = self.evaluate_posterior_emittance(
774
- sample_functions_list, best_inputs, bounds
793
+ n_batch: PositiveInt = Field(
794
+ 1,
795
+ description="Number of sample batches to optimize, with each batch containing self.n_samples",
796
+ )
797
+
798
+ def execute(self, model: Model, bounds: Tensor) -> Tensor:
799
+ best_tuning_inputs_list = []
800
+ best_objective_list = []
801
+ best_scan_inputs_list = []
802
+ best_scan_outputs_list = []
803
+ for i in range(self.n_batch):
804
+ # draw callable sample functions
805
+ sample_functions_list = self.draw_sample_functions_list(model)
806
+
807
+ best_tuning_inputs = self.optimize_samples_funcs_list(
808
+ sample_functions_list, bounds
809
+ )
810
+ best_meas_scan_inputs = self.get_meas_scan_inputs(
811
+ best_tuning_inputs, bounds
812
+ )
813
+ best_meas_scan_outputs = torch.vstack(
814
+ [
815
+ sample_func(best_meas_scan_inputs)
816
+ for sample_func in sample_functions_list
817
+ ]
818
+ ).T.unsqueeze(0)
819
+ best_result = self.perform_virtual_measurement(
820
+ sample_functions_list, best_meas_scan_inputs[:, :1, :], bounds
821
+ )
822
+ best_tuning_inputs_list += [best_tuning_inputs]
823
+ best_objective_list += [best_result.objective]
824
+ best_scan_inputs_list += [best_meas_scan_inputs]
825
+ best_scan_outputs_list += [best_meas_scan_outputs]
826
+
827
+ input_execution_paths = torch.cat(best_scan_inputs_list)
828
+ output_execution_paths = torch.cat(best_scan_outputs_list)
829
+ best_inputs = torch.cat(best_tuning_inputs_list)
830
+ best_objective = torch.cat(best_objective_list)
831
+ solution_center = best_inputs.mean(dim=0)
832
+ solution_entropy = float(torch.log(best_inputs.std(dim=0) ** 2).sum())
833
+
834
+ algorithm_result = OptimizationAlgorithmResult(
835
+ best_inputs=best_inputs.detach(),
836
+ best_objective=best_objective.detach(),
837
+ input_execution_paths=input_execution_paths.detach(),
838
+ output_execution_paths=output_execution_paths.detach(),
839
+ solution_center=solution_center.detach(),
840
+ solution_entropy=solution_entropy,
775
841
  )
776
- self.results = {}
777
- self.results["best_inputs"] = best_inputs
778
- self.results["best_emit"] = best_emit
779
- self.results["best_bmag"] = best_bmag
780
- self.results["sample_functions_list"] = sample_functions_list
781
842
 
782
- return best_meas_scan_inputs, best_meas_scan_outputs, {}
843
+ return algorithm_result
783
844
 
784
845
  def draw_sample_functions_list(self, model):
785
846
  sample_funcs_list = []
@@ -84,9 +84,9 @@ class PathwiseOptimization(Algorithm):
84
84
  model, x, bounds, n_samples, tkwargs
85
85
  )
86
86
 
87
- return measurement_result["objective"]
87
+ return measurement_result.objective
88
88
 
89
- def execute_algorithm(
89
+ def optimize_samples_funcs_list(
90
90
  self, sample_functions_list: List[Callable], bounds: Tensor
91
91
  ) -> Tensor:
92
92
  """
@@ -96,7 +96,7 @@ class PathwiseOptimization(Algorithm):
96
96
  optimization_indeces = self._get_optimization_indeces(bounds)
97
97
 
98
98
  # optimize sample functions
99
- best_inputs = self.optimizer.optimize(
99
+ best_tuning_inputs = self.optimizer.optimize(
100
100
  virtual_objective=self.evaluate_virtual_objective,
101
101
  sample_functions_list=sample_functions_list,
102
102
  bounds=bounds,
@@ -104,27 +104,7 @@ class PathwiseOptimization(Algorithm):
104
104
  n_samples=self.n_samples,
105
105
  )
106
106
 
107
- return best_inputs
108
-
109
- def get_execution_paths(self, model: Model, bounds: Tensor) -> Tensor:
110
- """
111
- Execute algorithm and get execution paths from optimization result.
112
- """
113
-
114
- # draw callable sample functions
115
- sample_functions_list = self.draw_sample_functions_list(model)
116
-
117
- best_inputs = self.execute_algorithm(sample_functions_list, bounds)
118
- best_objective = self.evaluate_virtual_objective(
119
- sample_functions_list, best_inputs, bounds
120
- )
121
-
122
- self.results = {}
123
- self.results["best_inputs"] = best_inputs
124
- self.results["best_objective"] = best_objective
125
- self.results["sample_functions_list"] = sample_functions_list
126
-
127
- return best_inputs, best_objective, self.results
107
+ return best_tuning_inputs
128
108
 
129
109
  def draw_sample_functions_list(self, model: Model) -> List:
130
110
  """
@@ -3,9 +3,23 @@ from torch import Tensor
3
3
  from botorch.models.model import Model
4
4
  from pydantic import Field, PositiveInt
5
5
  from bax_algorithms.pathwise.base import PathwiseOptimization
6
+ from xopt.generators.bayesian.bax.algorithms import (
7
+ OptimizationAlgorithmResult,
8
+ VirtualMeasurementResult,
9
+ )
10
+
11
+
12
+ class VirtualAlignmentMeasurementResult(VirtualMeasurementResult):
13
+ misalignment_x: Tensor = Field(
14
+ description="The misalignment in the x transverse dimension."
15
+ )
16
+ misalignment_y: Tensor = Field(
17
+ description="The misalignment in the y transverse dimension."
18
+ )
6
19
 
7
20
 
8
21
  class PathwiseSolenoidAlignment(PathwiseOptimization):
22
+ name: str = Field("PathwiseSolenoidAlignment", frozen=True)
9
23
  x_key: str = Field(
10
24
  None,
11
25
  description="key designating the centroid position in x from evaluate function",
@@ -21,9 +35,6 @@ class PathwiseSolenoidAlignment(PathwiseOptimization):
21
35
  n_steps_measurement_param: int = Field(
22
36
  3, description="number of steps to use in the virtual measurement scans"
23
37
  )
24
- results: dict = Field(
25
- {}, description="Dictionary to store results from emittance calculcation"
26
- )
27
38
  n_batch: PositiveInt = Field(
28
39
  1,
29
40
  description="Number of sample batches to optimize, with each batch containing self.n_samples",
@@ -56,7 +67,7 @@ class PathwiseSolenoidAlignment(PathwiseOptimization):
56
67
  at which to evaluate the objective.
57
68
  bounds: tensor shape (2, n_dim) specifying the upper and lower measurement bounds
58
69
  returns:
59
- result: dict containing measurement results
70
+ VirtualAlignmentMeasurementResult
60
71
  """
61
72
  tuning_idxs = torch.arange(bounds.shape[1])
62
73
  tuning_idxs = tuning_idxs[
@@ -74,12 +85,16 @@ class PathwiseSolenoidAlignment(PathwiseOptimization):
74
85
  )
75
86
 
76
87
  # store virtual measurement results
77
- result = {}
78
- result["misalignment_x"] = misalignment[..., self.x_idx]
79
- result["misalignment_y"] = misalignment[..., self.y_idx]
80
- result["objective"] = result["misalignment_x"] + result["misalignment_y"]
88
+ misalignment_x = misalignment[..., self.x_idx]
89
+ misalignment_y = misalignment[..., self.y_idx]
90
+ objective = misalignment_x + misalignment_y
91
+ virtual_alignment_result = VirtualAlignmentMeasurementResult(
92
+ objective=objective,
93
+ misalignment_x=misalignment_x,
94
+ misalignment_y=misalignment_y,
95
+ )
81
96
 
82
- return result
97
+ return virtual_alignment_result
83
98
 
84
99
  def get_meas_scan_inputs(
85
100
  self, x_tuning: Tensor, bounds: Tensor, tkwargs: dict = None
@@ -173,19 +188,21 @@ class PathwiseSolenoidAlignment(PathwiseOptimization):
173
188
 
174
189
  return misalignment
175
190
 
176
- def get_execution_paths(self, model: Model, bounds: Tensor) -> Tensor:
177
- best_inputs_list = []
191
+ def execute(self, model: Model, bounds: Tensor) -> Tensor:
192
+ best_tuning_inputs_list = []
178
193
  best_objective_list = []
179
- best_misalignment_list = []
180
194
  best_scan_inputs_list = []
181
195
  best_scan_outputs_list = []
182
-
183
196
  for i in range(self.n_batch):
184
197
  # draw callable sample functions
185
198
  sample_functions_list = self.draw_sample_functions_list(model)
186
199
 
187
- best_inputs = self.execute_algorithm(sample_functions_list, bounds)
188
- best_meas_scan_inputs = self.get_meas_scan_inputs(best_inputs, bounds)
200
+ best_tuning_inputs = self.optimize_samples_funcs_list(
201
+ sample_functions_list, bounds
202
+ )
203
+ best_meas_scan_inputs = self.get_meas_scan_inputs(
204
+ best_tuning_inputs, bounds
205
+ )
189
206
  scan_outputs = [
190
207
  sample_func(best_meas_scan_inputs).unsqueeze(-1)
191
208
  for sample_func in sample_functions_list
@@ -194,28 +211,29 @@ class PathwiseSolenoidAlignment(PathwiseOptimization):
194
211
  best_result = self.perform_virtual_measurement(
195
212
  sample_functions_list, best_meas_scan_inputs[:, :1, :], bounds
196
213
  )
197
- best_misalignment = self.evaluate_posterior_misalignment(
198
- sample_functions_list, best_inputs, bounds
199
- )
200
- best_inputs_list += [best_inputs]
201
- best_objective_list += [best_result["objective"]]
202
- best_misalignment_list += [best_misalignment]
214
+ best_tuning_inputs_list += [best_tuning_inputs]
215
+ best_objective_list += [best_result.objective]
203
216
  best_scan_inputs_list += [best_meas_scan_inputs]
204
217
  best_scan_outputs_list += [best_meas_scan_outputs]
205
218
 
206
- self.results = {}
207
- self.results["best_inputs"] = torch.cat(best_inputs_list)
208
- self.results["best_objective"] = torch.cat(best_objective_list)
209
- self.results["best_misalignment"] = torch.cat(best_misalignment_list)
210
- self.results["best_meas_scan_inputs"] = torch.cat(best_scan_inputs_list)
211
- self.results["best_meas_scan_outputs"] = torch.cat(best_scan_outputs_list)
212
-
213
- return (
214
- self.results["best_meas_scan_inputs"],
215
- self.results["best_meas_scan_outputs"],
216
- {},
219
+ input_execution_paths = torch.cat(best_scan_inputs_list)
220
+ output_execution_paths = torch.cat(best_scan_outputs_list)
221
+ best_inputs = torch.cat(best_tuning_inputs_list)
222
+ best_objective = torch.cat(best_objective_list)
223
+ solution_center = best_inputs.mean(dim=0)
224
+ solution_entropy = float(torch.log(best_inputs.std(dim=0) ** 2).sum())
225
+
226
+ algorithm_result = OptimizationAlgorithmResult(
227
+ best_inputs=best_inputs.detach(),
228
+ best_objective=best_objective.detach(),
229
+ input_execution_paths=input_execution_paths.detach(),
230
+ output_execution_paths=output_execution_paths.detach(),
231
+ solution_center=solution_center.detach(),
232
+ solution_entropy=solution_entropy,
217
233
  )
218
234
 
235
+ return algorithm_result
236
+
219
237
  def _get_optimization_indeces(self, bounds) -> Tensor:
220
238
  """
221
239
  Get indeces specifying parameters for virtual objective optimization.
@@ -1,3 +1,5 @@
1
+ import os
2
+ import pickle
1
3
  import torch
2
4
  from matplotlib import pyplot as plt
3
5
  from typing import List
@@ -16,6 +18,7 @@ def visualize_virtual_measurement_result(
16
18
  reference_point: dict = None,
17
19
  n_grid: int = 11,
18
20
  n_samples: int = 100,
21
+ show_observations: bool = False,
19
22
  kwargs: dict = None,
20
23
  result_keys: List[str] = ["objective"],
21
24
  ) -> tuple:
@@ -41,11 +44,15 @@ def visualize_virtual_measurement_result(
41
44
  Number of grid points per dimension used to display the model predictions.
42
45
  n_samples : int, optional
43
46
  Number of virtual measurement samples to evaluate for each point in the scan.
47
+ show_observations: bool, optional
48
+ Whether to add a scatter plot of the real observations ("partial measurements", i.e. training data)
49
+ to the virtual objective plots.
44
50
  kwargs : dict, optional
45
51
  Additional keyword arguments for evaluating the virtual measurement.
46
52
 
47
53
  Returns:
48
54
  --------
55
+ fig, ax
49
56
  The matplotlib figure and axes objects.
50
57
  """
51
58
  vocs, data = generator.vocs, generator.data
@@ -93,7 +100,7 @@ def visualize_virtual_measurement_result(
93
100
  kwargs = kwargs if kwargs else {}
94
101
  measurement_result = generator.algorithm.perform_virtual_measurement(
95
102
  bax_model, x, bounds, tkwargs=tkwargs, n_samples=n_samples, **kwargs
96
- )
103
+ ).model_dump()
97
104
 
98
105
  # create figure and subplots
99
106
  figsize = (4 * dim_x, 3 * len(result_keys))
@@ -129,6 +136,12 @@ def visualize_virtual_measurement_result(
129
136
  alpha=0.5,
130
137
  label="95% C.I.",
131
138
  )
139
+ if show_observations:
140
+ x_obs = generator.data[variable_names[0]].to_numpy()
141
+ label = "Partial Measurements"
142
+ for val in x_obs:
143
+ ax_i.axvline(val, ymax=0.1, c="C1", label=label)
144
+ label = None
132
145
  ax_i.legend()
133
146
  ax_i.set_ylabel(key)
134
147
  ax_i.set_xlabel(variable_names[0])
@@ -160,6 +173,12 @@ def visualize_virtual_measurement_result(
160
173
  rasterized=True,
161
174
  )
162
175
 
176
+ if show_observations:
177
+ x_obs = generator.data[variable_names].to_numpy()
178
+ label = "Partial Measurements"
179
+ ax_ij.scatter(x=x_obs[:, 0], y=x_obs[:, 1], c="C1", label=label)
180
+ ax_ij.legend()
181
+
163
182
  from mpl_toolkits.axes_grid1 import make_axes_locatable # lazy import
164
183
 
165
184
  divider = make_axes_locatable(ax_ij)
@@ -172,3 +191,153 @@ def visualize_virtual_measurement_result(
172
191
 
173
192
  fig.tight_layout()
174
193
  return fig, ax
194
+
195
+
196
+ def plot_bax_objective_convergence(
197
+ generator: BaxGenerator,
198
+ ) -> tuple:
199
+ """
200
+ Plots the algorithm sample objective optimization results from each step of BAX.
201
+
202
+ Parameters
203
+ ----------
204
+ generator : BaxGenerator
205
+
206
+ Returns:
207
+ --------
208
+ fig, ax
209
+ The matplotlib figure and axes objects.
210
+ """
211
+ file_prefix = os.path.basename(generator.algorithm_results_file) + "_"
212
+ file_ext = ".pkl"
213
+ prefix_len = len(file_prefix)
214
+ ext_len = len(file_ext)
215
+ directory = os.path.dirname(os.path.abspath(generator.algorithm_results_file))
216
+ file_names = [
217
+ file_name
218
+ for file_name in os.listdir(directory)
219
+ if file_name.startswith(file_prefix)
220
+ ]
221
+ file_names = sorted(file_names, key=lambda x: int(x[prefix_len:-ext_len]))
222
+ file_paths = [os.path.abspath(file_name) for file_name in file_names]
223
+
224
+ results_dicts = []
225
+ aggregated_results_dict = {}
226
+ for file_path in file_paths:
227
+ with open(file_path, "rb") as fpath:
228
+ loaded_dict = pickle.load(fpath)
229
+ results_dicts += [loaded_dict]
230
+ aggregated_results_dict["best_objective"] = torch.stack(
231
+ [res["best_objective"] for res in results_dicts]
232
+ )
233
+
234
+ # plot the sample objective optima
235
+ objs = aggregated_results_dict["best_objective"].squeeze(-1).squeeze(-1)
236
+ iters = range(objs.shape[0])
237
+ med = objs.quantile(0.5, dim=1).detach()
238
+ upper = objs.quantile(0.975, dim=1).detach()
239
+ lower = objs.quantile(0.025, dim=1).detach()
240
+
241
+ fig, ax = plt.subplots(1, 1)
242
+ ax.set_title("BAX Solutions: Objective")
243
+ ax.plot(iters, med, label="median")
244
+ ax.fill_between(iters, lower, upper, alpha=0.5, label="95% C.I.")
245
+ ax.legend(loc="upper left")
246
+ ax.set_xlabel("iteration")
247
+ ax.set_ylabel("Objective")
248
+
249
+ fig.set_size_inches(6, 3)
250
+ fig.tight_layout()
251
+
252
+ return fig, ax
253
+
254
+
255
+ def plot_bax_input_convergence(
256
+ generator: BaxGenerator,
257
+ ) -> tuple:
258
+ """
259
+ Plots the algorithm sample input optimization results from each step of BAX.
260
+
261
+ Parameters
262
+ ----------
263
+ generator : BaxGenerator
264
+
265
+ Returns:
266
+ --------
267
+ fig, ax
268
+ The matplotlib figure and axes objects.
269
+ """
270
+ file_prefix = os.path.basename(generator.algorithm_results_file) + "_"
271
+ file_ext = ".pkl"
272
+ prefix_len = len(file_prefix)
273
+ ext_len = len(file_ext)
274
+ directory = os.path.dirname(os.path.abspath(generator.algorithm_results_file))
275
+ file_names = [
276
+ file_name
277
+ for file_name in os.listdir(directory)
278
+ if file_name.startswith(file_prefix)
279
+ ]
280
+ file_names = sorted(file_names, key=lambda x: int(x[prefix_len:-ext_len]))
281
+ file_paths = [os.path.abspath(file_name) for file_name in file_names]
282
+
283
+ results_dicts = []
284
+ aggregated_results_dict = {}
285
+ for file_path in file_paths:
286
+ with open(file_path, "rb") as fpath:
287
+ loaded_dict = pickle.load(fpath)
288
+ results_dicts += [loaded_dict]
289
+ aggregated_results_dict["best_inputs"] = torch.stack(
290
+ [res["best_inputs"] for res in results_dicts]
291
+ )
292
+
293
+ # plot the sample input optima
294
+ solutions = aggregated_results_dict["best_inputs"]
295
+ solutions = solutions.squeeze(-2)
296
+ iters = range(solutions.shape[0])
297
+ if hasattr(generator.algorithm, "_get_optimization_indeces") and callable(
298
+ getattr(generator.algorithm, "_get_optimization_indeces")
299
+ ):
300
+ variable_indeces = generator.algorithm._get_optimization_indeces(
301
+ generator._get_optimization_bounds()
302
+ )
303
+ ndim = len(variable_indeces)
304
+ else:
305
+ ndim = solutions.shape[-1]
306
+ variable_indeces = range(ndim)
307
+ fig, ax = plt.subplots(ndim, 1, sharex=True)
308
+ if ndim == 1:
309
+ ax = [ax]
310
+ for i, j in enumerate(variable_indeces):
311
+ med = solutions[..., i].quantile(0.5, dim=1)
312
+ upper = solutions[..., i].quantile(0.975, dim=1)
313
+ lower = solutions[..., i].quantile(0.025, dim=1)
314
+ ax_i = ax[i]
315
+ if i == 0:
316
+ ax_i.set_title("BAX Solutions: Input(s)")
317
+ ax_i.plot(iters, med, label="median")
318
+ ax_i.fill_between(iters, lower, upper, alpha=0.5, label="95% C.I.")
319
+ var_name = list(generator.vocs.variables.keys())[j]
320
+ bbox = dict(
321
+ boxstyle="round,pad=0.5",
322
+ facecolor="lightgray",
323
+ edgecolor="silver",
324
+ alpha=0.7,
325
+ )
326
+ ax_i.text(
327
+ 0.0275,
328
+ 0.06,
329
+ var_name,
330
+ transform=ax_i.transAxes,
331
+ fontsize=12,
332
+ verticalalignment="bottom",
333
+ horizontalalignment="left",
334
+ bbox=bbox,
335
+ )
336
+ ax_i.set_ylim(generator.vocs.variables[var_name].domain)
337
+ ax_i.legend(loc="upper left")
338
+ ax_i.set_xlabel("iteration")
339
+
340
+ fig.set_size_inches(6, 3 * ndim)
341
+ fig.tight_layout()
342
+
343
+ return fig, ax
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bax_algorithms
3
- Version: 0.1.2
3
+ Version: 0.1.3
4
4
  Summary: Collection of algorithms that can be used in Bayesian Algorithm Execution (BAX) Xopt generators.
5
5
  Author: Dylan Kennedy, Sean Gasiorowski, Samuel Klein
6
6
  License: Apache License
@@ -209,13 +209,12 @@ Project-URL: Homepage, https://github.com/xopt-org/bax_algorithms
209
209
  Keywords: machine learning,accelerator physics
210
210
  Classifier: Natural Language :: English
211
211
  Classifier: Programming Language :: Python :: 3 :: Only
212
- Classifier: Programming Language :: Python :: 3.10
213
212
  Classifier: Programming Language :: Python :: 3.11
214
213
  Classifier: Programming Language :: Python :: 3.12
215
214
  Classifier: Programming Language :: Python :: 3.13
216
215
  Classifier: Intended Audience :: Science/Research
217
216
  Classifier: Topic :: Scientific/Engineering
218
- Requires-Python: >=3.10
217
+ Requires-Python: >=3.11
219
218
  Description-Content-Type: text/markdown
220
219
  License-File: LICENSE
221
220
  Requires-Dist: numpy
@@ -223,7 +222,7 @@ Requires-Dist: botorch>=0.8.5
223
222
  Requires-Dist: gpytorch>=1.10
224
223
  Requires-Dist: pydantic>=1.10.9
225
224
  Requires-Dist: scipy>=1.10.1
226
- Requires-Dist: xopt>=2.6.11
225
+ Requires-Dist: xopt>=3.1.2
227
226
  Requires-Dist: jupyterlab>=3
228
227
  Provides-Extra: dev
229
228
  Requires-Dist: pytest; extra == "dev"
@@ -17,6 +17,8 @@ bax_algorithms.egg-info/PKG-INFO
17
17
  bax_algorithms.egg-info/SOURCES.txt
18
18
  bax_algorithms.egg-info/dependency_links.txt
19
19
  bax_algorithms.egg-info/requires.txt
20
+ bax_algorithms.egg-info/scm_file_list.json
21
+ bax_algorithms.egg-info/scm_version.json
20
22
  bax_algorithms.egg-info/top_level.txt
21
23
  bax_algorithms/pathwise/base.py
22
24
  bax_algorithms/pathwise/optimize.py
@@ -3,7 +3,7 @@ botorch>=0.8.5
3
3
  gpytorch>=1.10
4
4
  pydantic>=1.10.9
5
5
  scipy>=1.10.1
6
- xopt>=2.6.11
6
+ xopt>=3.1.2
7
7
  jupyterlab>=3
8
8
 
9
9
  [dev]
@@ -0,0 +1,26 @@
1
+ {
2
+ "files": [
3
+ ".pre-commit-config.yaml",
4
+ "README.md",
5
+ "LICENSE",
6
+ "pyproject.toml",
7
+ ".gitattributes",
8
+ ".gitignore",
9
+ "bax_algorithms/__init__.py",
10
+ "bax_algorithms/emittance.py",
11
+ "bax_algorithms/utils.py",
12
+ "bax_algorithms/solenoid_alignment.py",
13
+ "bax_algorithms/visualize.py",
14
+ "bax_algorithms/pathwise/optimize.py",
15
+ "bax_algorithms/pathwise/base.py",
16
+ "bax_algorithms/pathwise/sampling.py",
17
+ "tests/test_solenoid_alignment.py",
18
+ "tests/test_emittance.py",
19
+ "examples/solenoid_alignment.ipynb",
20
+ "examples/emittance.ipynb",
21
+ "examples/pathwise_tutorial.ipynb",
22
+ ".github/workflows/pypi_upload.yml",
23
+ ".github/workflows/tests.yml",
24
+ ".github/workflows/lint.yml"
25
+ ]
26
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "0.1.3",
3
+ "distance": 0,
4
+ "node": "gb41cacfc297935a25721930f589c896ecef6d227",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-07-01"
8
+ }
@@ -196,7 +196,7 @@
196
196
  "\n",
197
197
  "print(\"variable_names =\", vocs.variable_names)\n",
198
198
  "print(\"meas_param =\", \"'\" + meas_param + \"'\")\n",
199
- "print(\"domain =\\n\", vocs.bounds.T)"
199
+ "print(\"domain =\\n\", vocs.bounds)"
200
200
  ]
201
201
  },
202
202
  {
@@ -267,7 +267,7 @@
267
267
  "outputs": [],
268
268
  "source": [
269
269
  "x = torch.zeros(100, ndim)\n",
270
- "x[:, 0] = torch.linspace(*vocs.bounds.T[0], 100)\n",
270
+ "x[:, 0] = torch.linspace(*vocs.bounds[0], 100)\n",
271
271
  "plt.plot(x[:, 0], eval_true_emittance(x, use_bmag=use_bmag), c=\"k\")"
272
272
  ]
273
273
  },
@@ -445,16 +445,6 @@
445
445
  ")"
446
446
  ]
447
447
  },
448
- {
449
- "cell_type": "code",
450
- "execution_count": null,
451
- "id": "a2915525-0490-4749-8439-1df1abe55d7c",
452
- "metadata": {},
453
- "outputs": [],
454
- "source": [
455
- "X.generator.algorithm.results[\"best_inputs\"]"
456
- ]
457
- },
458
448
  {
459
449
  "cell_type": "code",
460
450
  "execution_count": null,
@@ -471,12 +461,12 @@
471
461
  " reference_point=reference_point,\n",
472
462
  " n_grid=100,\n",
473
463
  " n_samples=100,\n",
474
- " result_keys=[\"objective\", \"emit_x\", \"emit_y\", \"bmag_x\", \"bmag_y\"],\n",
464
+ " result_keys=[\"objective\", \"emittance_x\", \"emittance_y\", \"bmag_x\", \"bmag_y\"],\n",
475
465
  " # show_samples=True,\n",
476
466
  ")\n",
477
467
  "print(time.time() - start)\n",
478
468
  "x = torch.zeros(100, ndim)\n",
479
- "x[:, 0] = torch.linspace(*vocs.bounds.T[0], 100)\n",
469
+ "x[:, 0] = torch.linspace(*vocs.bounds[0], 100)\n",
480
470
  "ax[0].plot(x[:, 0], eval_true_emittance(x, use_bmag=use_bmag), c=\"k\")\n",
481
471
  "# plt.ylim(top=0.01)"
482
472
  ]
@@ -567,12 +557,12 @@
567
557
  " reference_point=reference_point,\n",
568
558
  " n_grid=100,\n",
569
559
  " n_samples=100,\n",
570
- " result_keys=[\"objective\", \"emit_x\", \"emit_y\", \"bmag_x\", \"bmag_y\"],\n",
560
+ " result_keys=[\"objective\", \"emittance_x\", \"emittance_y\", \"bmag_x\", \"bmag_y\"],\n",
571
561
  " # show_samples=True,\n",
572
562
  ")\n",
573
563
  "print(time.time() - start)\n",
574
564
  "x = torch.zeros(100, ndim)\n",
575
- "x[:, 0] = torch.linspace(*vocs.bounds.T[0], 100)\n",
565
+ "x[:, 0] = torch.linspace(*vocs.bounds[0], 100)\n",
576
566
  "ax[0].plot(x[:, 0], eval_true_emittance(x, use_bmag=use_bmag), c=\"k\")"
577
567
  ]
578
568
  },
@@ -592,7 +582,7 @@
592
582
  " reference_point=reference_point,\n",
593
583
  " n_grid=15,\n",
594
584
  " n_samples=100,\n",
595
- " result_keys=[\"objective\", \"emit_x\", \"emit_y\", \"bmag_x\", \"bmag_y\"],\n",
585
+ " result_keys=[\"objective\", \"emittance_x\", \"emittance_y\", \"bmag_x\", \"bmag_y\"],\n",
596
586
  " # show_samples=True,\n",
597
587
  ")\n",
598
588
  "print(time.time() - start)"
@@ -627,28 +617,6 @@
627
617
  "outputs": [],
628
618
  "source": []
629
619
  },
630
- {
631
- "cell_type": "code",
632
- "execution_count": null,
633
- "id": "c2bbf136-7f1e-4d6f-964c-f0a9ed634cde",
634
- "metadata": {},
635
- "outputs": [],
636
- "source": [
637
- "from bax_algorithms.utils import uniform_random_sample_in_bounds\n",
638
- "from bax_algorithms.utils import get_bax_model_and_bounds\n",
639
- "\n",
640
- "bax_model, bounds = get_bax_model_and_bounds(X.generator)\n",
641
- "x0 = uniform_random_sample_in_bounds(3000, bounds)\n",
642
- "start = time.time()\n",
643
- "algo.n_steps_measurement_param = 11\n",
644
- "algo.evaluate_virtual_objective(\n",
645
- " X.generator.algorithm.results[\"sample_functions_list\"],\n",
646
- " x0.reshape(n_samples, 1000, -1),\n",
647
- " bounds,\n",
648
- ")\n",
649
- "print(time.time() - start)"
650
- ]
651
- },
652
620
  {
653
621
  "cell_type": "code",
654
622
  "execution_count": null,
@@ -231,16 +231,6 @@
231
231
  "X.data"
232
232
  ]
233
233
  },
234
- {
235
- "cell_type": "code",
236
- "execution_count": null,
237
- "id": "235e773e-d35e-4916-a063-48692db44988",
238
- "metadata": {},
239
- "outputs": [],
240
- "source": [
241
- "X.generator.algorithm.results[\"best_inputs\"]"
242
- ]
243
- },
244
234
  {
245
235
  "cell_type": "code",
246
236
  "execution_count": null,
@@ -448,6 +438,16 @@
448
438
  "id": "6473cd0e-bd20-4c64-953f-e34c0dcd4c46",
449
439
  "metadata": {},
450
440
  "outputs": [],
441
+ "source": [
442
+ "X.generator.vocs.bounds"
443
+ ]
444
+ },
445
+ {
446
+ "cell_type": "code",
447
+ "execution_count": null,
448
+ "id": "d381a0d4-3f83-432e-a2e2-4ce63150ec07",
449
+ "metadata": {},
450
+ "outputs": [],
451
451
  "source": []
452
452
  }
453
453
  ],
@@ -15,21 +15,20 @@ keywords = ["machine learning", "accelerator physics"]
15
15
  classifiers = [
16
16
  "Natural Language :: English",
17
17
  "Programming Language :: Python :: 3 :: Only",
18
- "Programming Language :: Python :: 3.10",
19
18
  "Programming Language :: Python :: 3.11",
20
19
  "Programming Language :: Python :: 3.12",
21
20
  "Programming Language :: Python :: 3.13",
22
21
  "Intended Audience :: Science/Research",
23
22
  "Topic :: Scientific/Engineering",
24
23
  ]
25
- requires-python = ">=3.10"
24
+ requires-python = ">=3.11"
26
25
  dependencies = [
27
26
  "numpy",
28
27
  "botorch>=0.8.5",
29
28
  "gpytorch>=1.10",
30
29
  "pydantic>=1.10.9",
31
30
  "scipy>=1.10.1",
32
- "xopt>=2.6.11",
31
+ "xopt>=3.1.2",
33
32
  "jupyterlab>=3",
34
33
  ]
35
34
  dynamic = ["version"]
@@ -106,7 +106,7 @@ class TestEmittanceBax:
106
106
  reference_point=self.reference_point,
107
107
  n_grid=100,
108
108
  n_samples=100,
109
- result_keys=["objective", "emit_x", "emit_y", "bmag_x", "bmag_y"],
109
+ result_keys=["objective", "emittance_x", "emittance_y", "bmag_x", "bmag_y"],
110
110
  )
111
111
 
112
112
  def test_visualize_virtual_measurement_result_2d(self):
@@ -116,5 +116,5 @@ class TestEmittanceBax:
116
116
  reference_point=self.reference_point,
117
117
  n_grid=10,
118
118
  n_samples=100,
119
- result_keys=["objective", "emit_x", "emit_y", "bmag_x", "bmag_y"],
119
+ result_keys=["objective", "emittance_x", "emittance_y", "bmag_x", "bmag_y"],
120
120
  )
File without changes
File without changes
File without changes