Top-Level Scripts¶
Many other examples of top-level scripts can be found in libEnsemble’s regression tests.
Local Sine Tutorial¶
This example is from the Local Sine Tutorial,
meant to run with Python’s multiprocessing as the primary comms method.
1import numpy as np
2from gest_api.vocs import VOCS
3from sine_gen_std import RandomSample
4from sine_sim import sim_find_sine
5
6from libensemble import Ensemble
7from libensemble.specs import GenSpecs, LibeSpecs, SimSpecs
8
9if __name__ == "__main__": # Python-quirk required on macOS and windows
10 libE_specs = LibeSpecs(nworkers=4, comms="local")
11
12 vocs = VOCS(variables={"x": [-3, 3]}, objectives={"y": "EXPLORE"}) # Configure our generator with this object
13
14 generator = RandomSample(vocs) # Instantiate our generator
15
16 gen_specs = GenSpecs(
17 generator=generator, # Pass our generator and config to libEnsemble
18 vocs=vocs,
19 batch_size=4,
20 )
21
22 sim_specs = SimSpecs(
23 sim_f=sim_find_sine, # Our simulator function
24 inputs=["x"], # InputArray field names. "x" from gen_f output
25 out=[("y", float)], # sim_f output. "y" = sine("x")
26 ) # sim_specs_end_tag
27
28 ensemble = Ensemble(sim_specs, gen_specs, libE_specs=libE_specs)
29 ensemble.run(sim_max=80) # start the ensemble. Blocks until completion.
30
31 history = ensemble.H # start visualizing our results
32
33 print([i for i in history.dtype.fields]) # (optional) to visualize our history array
34 print(history)
35
36 import matplotlib.pyplot as plt
37
38 colors = ["b", "g", "r", "y", "m", "c", "k", "w"]
39
40 for i in range(1, libE_specs.nworkers + 1): # type: ignore
41 worker_xy = np.extract(history["sim_worker"] == i, history)
42 x = [entry.tolist() for entry in worker_xy["x"]]
43 y = [entry for entry in worker_xy["y"]]
44 plt.scatter(x, y, label="Worker {}".format(i), c=colors[i - 1])
45
46 plt.title("Sine calculations for a uniformly sampled random distribution")
47 plt.xlabel("x")
48 plt.ylabel("sine(x)")
49 plt.legend(loc="lower right")
50 plt.savefig("tutorial_sines.png")
Electrostatic Forces with Executor¶
These examples are from a test for evaluating the scaling capabilities of libEnsemble
by calculating particle electrostatic forces through a user application. This
application is registered with the MPIExecutor, then submitted
for execution in the sim_f. Note the use of the parse_args=True which allows
reading arguments such as the number of workers from the command line.
Traditional Version¶
Run using five workers with:
python run_libe_forces.py -n 5
1#!/usr/bin/env python
2import os
3import sys
4from pathlib import Path
5
6import numpy as np
7from forces_simf import run_forces # Sim func from current dir
8
9from libensemble import Ensemble
10from libensemble.executors import MPIExecutor
11from libensemble.gen_funcs.persistent_sampling import persistent_uniform as gen_f
12from libensemble.specs import GenSpecs, LibeSpecs, SimSpecs
13
14if __name__ == "__main__":
15 # Initialize MPI Executor
16 exctr = MPIExecutor()
17
18 # Register simulation executable with executor
19 sim_app = Path.cwd() / "../forces_app/forces.x"
20
21 if not os.path.isfile(sim_app):
22 sys.exit("forces.x not found - please build first in ../forces_app dir")
23
24 exctr.register_app(full_path=sim_app, app_name="forces")
25
26 # Parse number of workers, comms type, etc. from arguments
27 ensemble = Ensemble(parse_args=True, executor=exctr)
28 nsim_workers = ensemble.nworkers - 1 # One worker is for persistent generator
29
30 # Persistent gen does not need resources
31 ensemble.libE_specs = LibeSpecs(
32 num_resource_sets=nsim_workers,
33 sim_dirs_make=True,
34 )
35
36 ensemble.sim_specs = SimSpecs(
37 sim_f=run_forces,
38 inputs=["x"],
39 outputs=[("energy", float)],
40 )
41
42 ensemble.gen_specs = GenSpecs(
43 gen_f=gen_f,
44 inputs=[], # No input when start persistent generator
45 persis_in=["sim_id"], # Return sim_ids of evaluated points to generator
46 outputs=[("x", float, (1,))],
47 initial_batch_size=nsim_workers,
48 async_return=False,
49 user={
50 "lb": np.array([1000]), # min particles
51 "ub": np.array([3000]), # max particles
52 },
53 )
54
55 # Starts one persistent generator. Simulated values are returned in batch.
56
57 # Run ensemble; exit after this many simulations
58 ensemble.run(sim_max=8)
59
60 if ensemble.is_manager:
61 # Note, this will change if changing sim_max, nworkers, lb, ub, etc.
62 print(f'Final energy checksum: {np.sum(ensemble.H["energy"])}')
gest-api APOSMM¶
This example from the regression tests demonstrates the gest-api interface with a
standardized APOSMM generator class parameterized by a VOCS object, and
paired with a gest-api simulator callable.
1"""
2Runs libEnsemble with APOSMM with the NLopt local optimizer.
3
4Execute via one of the following commands (e.g. 3 workers):
5 mpiexec -np 4 python test_aposmm_nlopt.py
6 python test_aposmm_nlopt.py --nworkers 3 --comms local
7 python test_aposmm_nlopt.py --nworkers 3 --comms threads
8
9When running with the above commands, the number of concurrent evaluations of
10the objective function will be 3, as the generator runs on the manager.
11"""
12
13# Do not change these lines - they are parsed by run-tests.sh
14# TESTSUITE_COMMS: local mpi threads
15# TESTSUITE_NPROCS: 4
16
17from math import gamma, pi, sqrt
18
19import numpy as np
20
21import libensemble.gen_funcs
22
23libensemble.gen_funcs.rc.aposmm_optimizers = "nlopt"
24from time import time
25
26from gest_api.vocs import VOCS
27
28from libensemble import Ensemble
29from libensemble.gen_classes import APOSMM
30from libensemble.specs import GenSpecs, SimSpecs
31from libensemble.tests.regression_tests.support import six_hump_camel_minima as minima
32
33
34def six_hump_camel_func(x):
35 """
36 Definition of the six-hump camel
37 """
38 x1 = x["x0"]
39 x2 = x["x1"]
40 term1 = (4 - 2.1 * x1**2 + (x1**4) / 3) * x1**2
41 term2 = x1 * x2
42 term3 = (-4 + 4 * x2**2) * x2**2
43 return {"f": term1 + term2 + term3}
44
45
46# Main block is necessary only when using local comms with spawn start method (default on macOS and Windows).
47if __name__ == "__main__":
48 n = 2
49
50 vocs = VOCS(
51 variables={
52 "x0": [-3, 3],
53 "x1": [-2, 2],
54 },
55 objectives={"f": "MINIMIZE"},
56 )
57
58 passed = False
59 for attempt in range(2):
60 workflow = Ensemble(parse_args=True)
61 if workflow.is_manager:
62 start_time = time()
63
64 aposmm = APOSMM(
65 vocs,
66 max_active_runs=6,
67 variables_mapping={
68 "x": ["x0", "x1"],
69 "f": ["f"],
70 },
71 initial_sample_size=100,
72 sample_points=np.round(minima, 1),
73 localopt_method="LN_BOBYQA",
74 rk_const=0.5 * ((gamma(1 + (n / 2)) * 5) ** (1 / n)) / sqrt(pi),
75 xtol_abs=1e-5,
76 ftol_abs=1e-5,
77 dist_to_bound_multiple=0.5,
78 )
79
80 workflow.gen_specs = GenSpecs(
81 generator=aposmm,
82 vocs=vocs,
83 initial_batch_size=100,
84 )
85
86 workflow.sim_specs = SimSpecs(simulator=six_hump_camel_func, vocs=vocs)
87 H, _, _ = workflow.run(sim_max=3000, wallclock_max=600)