Simulation Functions
Below are example simulation functions available in libEnsemble. Most of these demonstrate an inexpensive algorithm and do not launch tasks (user applications). To see an example of a simulation function launching tasks, see the Electrostatic Forces tutorial.
Important
See the API for simulation functions here.
six_hump_camel
This module contains various versions that evaluate the six-hump camel function.
- Six-hump camel function is documented here:
- six_hump_camel.six_hump_camel(H, persis_info, sim_specs, libE_info)
Evaluates the six hump camel function for a collection of points given in
H["x"]
. Additionally evaluates the gradient if"grad"
is a field insim_specs["out"]
and pauses forsim_specs["user"]["pause_time"]]
if defined.See also
- six_hump_camel.six_hump_camel_simple(x, _, sim_specs)
Evaluates the six hump camel function for a single point
x
.See also
test_fast_alloc.py # noqa
- six_hump_camel.persistent_six_hump_camel(H, persis_info, sim_specs, libE_info)
Similar to
six_hump_camel
, but runs in persistent mode.
six_hump_camel.py
1"""
2This module contains various versions that evaluate the six-hump camel function.
3
4Six-hump camel function is documented here:
5 https://www.sfu.ca/~ssurjano/camel6.html
6
7"""
8__all__ = [
9 "six_hump_camel",
10 "six_hump_camel_simple",
11 "persistent_six_hump_camel",
12]
13
14import sys
15import time
16import numpy as np
17
18from libensemble.message_numbers import (
19 EVAL_SIM_TAG,
20 FINISHED_PERSISTENT_SIM_TAG,
21 PERSIS_STOP,
22 STOP_TAG,
23)
24from libensemble.tools.persistent_support import PersistentSupport
25
26
27def six_hump_camel(H, persis_info, sim_specs, libE_info):
28 """
29 Evaluates the six hump camel function for a collection of points given in ``H["x"]``.
30 Additionally evaluates the gradient if ``"grad"`` is a field in
31 ``sim_specs["out"]`` and pauses for ``sim_specs["user"]["pause_time"]]`` if
32 defined.
33
34 .. seealso::
35 `test_old_aposmm_with_gradients.py <https://github.com/Libensemble/libensemble/blob/develop/libensemble/tests/regression_tests/test_old_aposmm_with_gradients.py>`_ # noqa
36 """
37
38 batch = len(H["x"])
39 H_o = np.zeros(batch, dtype=sim_specs["out"])
40
41 for i, x in enumerate(H["x"]):
42 H_o["f"][i] = six_hump_camel_func(x)
43
44 if "grad" in H_o.dtype.names:
45 H_o["grad"][i] = six_hump_camel_grad(x)
46
47 if "user" in sim_specs and "pause_time" in sim_specs["user"]:
48 time.sleep(sim_specs["user"]["pause_time"])
49
50 return H_o, persis_info
51
52
53def six_hump_camel_simple(x, _, sim_specs):
54 """
55 Evaluates the six hump camel function for a single point ``x``.
56
57 .. seealso::
58 `test_fast_alloc.py <https://github.com/Libensemble/libensemble/blob/develop/libensemble/tests/regression_tests/test_fast_alloc.py>`_ # noqa
59 """
60
61 H_o = np.zeros(1, dtype=sim_specs["out"])
62
63 H_o["f"] = six_hump_camel_func(x[0][0])
64
65 if "pause_time" in sim_specs["user"]:
66 time.sleep(sim_specs["user"]["pause_time"])
67
68 return H_o
69
70
71def persistent_six_hump_camel(H, persis_info, sim_specs, libE_info):
72 """
73 Similar to ``six_hump_camel``, but runs in persistent mode.
74 """
75
76 ps = PersistentSupport(libE_info, EVAL_SIM_TAG)
77
78 # Either start with a work item to process - or just start and wait for data
79 if H.size > 0:
80 tag = None
81 Work = None
82 calc_in = H
83 else:
84 tag, Work, calc_in = ps.recv()
85
86 while tag not in [STOP_TAG, PERSIS_STOP]:
87 # calc_in: This should either be a function (unpack_work ?) or included/unpacked in ps.recv/ps.send_recv.
88 if Work is not None:
89 persis_info = Work.get("persis_info", persis_info)
90 libE_info = Work.get("libE_info", libE_info)
91
92 # Call standard six_hump_camel sim
93 H_o, persis_info = six_hump_camel(calc_in, persis_info, sim_specs, libE_info)
94
95 tag, Work, calc_in = ps.send_recv(H_o)
96
97 final_return = None
98
99 # Overwrite final point - for testing only
100 if sim_specs["user"].get("replace_final_fields", 0):
101 calc_in = np.ones(1, dtype=[("x", float, (2,))])
102 H_o, persis_info = six_hump_camel(calc_in, persis_info, sim_specs, libE_info)
103 final_return = H_o
104
105 return final_return, persis_info, FINISHED_PERSISTENT_SIM_TAG
106
107
108def six_hump_camel_func(x):
109 """
110 Definition of the six-hump camel
111 """
112 x1 = x[0]
113 x2 = x[1]
114 term1 = (4 - 2.1 * x1**2 + (x1**4) / 3) * x1**2
115 term2 = x1 * x2
116 term3 = (-4 + 4 * x2**2) * x2**2
117
118 return term1 + term2 + term3
119
120
121def six_hump_camel_grad(x):
122 """
123 Definition of the six-hump camel gradient
124 """
125
126 x1 = x[0]
127 x2 = x[1]
128 grad = np.zeros(2)
129
130 grad[0] = 2.0 * (x1**5 - 4.2 * x1**3 + 4.0 * x1 + 0.5 * x2)
131 grad[1] = x1 + 16 * x2**3 - 8 * x2
132
133 return grad
134
135
136if __name__ == "__main__":
137 x = (float(sys.argv[1]), float(sys.argv[2]))
138 result = six_hump_camel_func(x)
139 print(result)
chwirut
- chwirut1.chwirut_eval(H, _, sim_specs)
Evaluates the chwirut objective function at a given set of points in
H["x"]
. If"obj_component"
is a field insim_specs["out"]
, only that component of the objective will be evaluated. Otherwise, all 214 components are evaluated and returned in the"fvec"
field.See also
test_old_aposmm_pounders.py for an example where the entire fvec is computed each call.
See also
test_old_aposmm_one_residual_at_a_time.py for an example where one component of fvec is computed per call
noisy_vector_mapping
This module contains a test noisy function
- noisy_vector_mapping.func_wrapper(H, persis_info, sim_specs, libE_info)
Wraps an objective function
See also
test_persistent_fd_param_finder.py <https://github.com/Libensemble/libensemble/blob/develop/libensemble/tests/regression_tests/test_persistent_fd_param_finder.py>`_ # noqa
- noisy_vector_mapping.noisy_function(x)
noisy_vector_mapping.py
1"""
2This module contains a test noisy function
3"""
4
5import numpy as np
6from numpy import cos, sin
7from numpy.linalg import norm
8
9
10def func_wrapper(H, persis_info, sim_specs, libE_info):
11 """
12 Wraps an objective function
13
14 .. seealso::
15 `test_persistent_fd_param_finder.py` <https://github.com/Libensemble/libensemble/blob/develop/libensemble/tests/regression_tests/test_persistent_fd_param_finder.py>`_ # noqa
16 """
17
18 batch = len(H["x"])
19 H0 = np.zeros(batch, dtype=sim_specs["out"])
20
21 for i, x in enumerate(H["x"]):
22 H0["f_val"][i] = noisy_function(x)[H["f_ind"][i]]
23
24 return H0, persis_info
25
26
27def noisy_function(x):
28 """ """
29 x1 = x[0]
30 x2 = x[1]
31 term1 = (4 - 2.1 * x1**2 + (x1**4) / 3) * x1**2
32 term2 = x1 * x2
33 term3 = (-4 + 4 * x2**2) * x2**2
34
35 phi1 = 0.9 * sin(100 * norm(x, 1)) * cos(100 * norm(x, np.inf)) + 0.1 * cos(norm(x, 2))
36 phi1 = phi1 * (4 * phi1**2 - 3)
37
38 phi2 = 0.8 * sin(100 * norm(x, 1)) * cos(100 * norm(x, np.inf)) + 0.2 * cos(norm(x, 2))
39 phi2 = phi2 * (4 * phi2**2 - 3)
40
41 phi3 = 0.7 * sin(100 * norm(x, 1)) * cos(100 * norm(x, np.inf)) + 0.3 * cos(norm(x, 2))
42 phi3 = phi3 * (4 * phi3**2 - 3)
43
44 F = np.zeros(3)
45 F[0] = (1 + 1e-1 * phi1) * term1
46 F[1] = (1 + 1e-2 * phi2) * term2
47 F[2] = (1 + 1e-3 * phi3) * term3
48
49 return F
periodic_func
This module contains a periodic test function
- periodic_func.func_wrapper(H, persis_info, sim_specs, libE_info)
Wraps an objective function
- periodic_func.periodic_func(x)
This function is periodic
borehole
- borehole.borehole(H, persis_info, sim_specs, _)
Wraps the borehole function
- borehole.borehole_func(x)
This evaluates the Borehole function for n-by-8 input matrix x, and returns the flow rate through the Borehole. (Harper and Gupta, 1983) input:
- Parameters:
x (matrix of dimension (n, 8), where n is the number of input configurations:) –
x[:,0]: Tu, transmissivity of upper aquifer (m^2/year) x[:,1]: Tl, transmissivity of lower aquifer (m^2/year) x[:,2]: Hu, potentiometric head of upper aquifer (m) x[:,3]: Hl, potentiometric head of lower aquifer (m) x[:,4]: r, radius of influence (m) x[:,5]: rw, radius of borehole (m) x[:,6]: Kw, hydraulic conductivity of borehole (m/year) x[:,7]: L, length of borehole (m)
- Returns:
flow rate through the Borehole (m^3/year)
- Return type:
vector of dimension (n, 1)
- borehole.gen_borehole_input(n)
Generates and returns n inputs for the Borehole function, according to distributions outlined in Harper and Gupta (1983).
- input:
n: number of input to generate
- output:
matrix of (n, 8), input to borehole_func(x) function
executor_hworld
- executor_hworld.executor_hworld(H, _, sim_specs)
Tests launching and polling task and exiting on task finish
executor_hworld.py
1import numpy as np
2
3from libensemble.executors.mpi_executor import MPIExecutor
4from libensemble.message_numbers import (
5 MAN_SIGNAL_FINISH,
6 TASK_FAILED,
7 UNSET_TAG,
8 WORKER_DONE,
9 WORKER_KILL_ON_ERR,
10 WORKER_KILL_ON_TIMEOUT,
11)
12
13__all__ = ["executor_hworld"]
14
15# Alt send values through X
16sim_ended_count = 0
17
18
19def custom_polling_loop(exctr, task, timeout_sec=5.0, delay=0.3):
20 import time
21
22 calc_status = UNSET_TAG # Sim func determines status of libensemble calc - returned to worker
23
24 while task.runtime < timeout_sec:
25 time.sleep(delay)
26
27 if exctr.manager_kill_received():
28 exctr.kill(task)
29 calc_status = MAN_SIGNAL_FINISH # Worker will pick this up and close down
30 print(f"Task {task.id} killed by manager on worker {exctr.workerID}")
31 break
32
33 task.poll()
34 if task.finished:
35 break
36 elif task.state == "RUNNING":
37 print(f"Task {task.id} still running on worker {exctr.workerID} ....")
38
39 if task.stdout_exists():
40 if "Error" in task.read_stdout():
41 print(
42 "Found (deliberate) Error in output file - cancelling " f"task {task.id} on worker {exctr.workerID}"
43 )
44 exctr.kill(task)
45 calc_status = WORKER_KILL_ON_ERR
46 break
47
48 # After exiting loop
49 if task.finished:
50 print(f"Task {task.id} done on worker {exctr.workerID}")
51 # Fill in calc_status if not already
52 if calc_status == UNSET_TAG:
53 if task.state == "FINISHED": # Means finished successfully
54 calc_status = WORKER_DONE
55 elif task.state == "FAILED":
56 calc_status = TASK_FAILED
57
58 else:
59 # assert task.state == 'RUNNING', "task.state expected to be RUNNING. Returned: " + str(task.state)
60 print(f"Task {task.id} timed out - killing on worker {exctr.workerID}")
61 exctr.kill(task)
62 if task.finished:
63 print(f"Task {task.id} done on worker {exctr.workerID}")
64 calc_status = WORKER_KILL_ON_TIMEOUT
65
66 return task, calc_status
67
68
69def executor_hworld(H, _, sim_specs):
70 """Tests launching and polling task and exiting on task finish"""
71 exctr = MPIExecutor.executor
72 cores = sim_specs["user"]["cores"]
73 ELAPSED_TIMEOUT = "elapsed_timeout" in sim_specs["user"]
74
75 wait = False
76 args_for_sim = "sleep 1"
77 calc_status = UNSET_TAG
78
79 batch = len(H["x"])
80 H_o = np.zeros(batch, dtype=sim_specs["out"])
81
82 if "six_hump_camel" not in exctr.default_app("sim").full_path:
83 global sim_ended_count
84 sim_ended_count += 1
85 print("sim_ended_count", sim_ended_count, flush=True)
86
87 if ELAPSED_TIMEOUT:
88 args_for_sim = "sleep 60" # Manager kill - if signal received else completes
89 timeout = 65.0
90
91 else:
92 timeout = 6.0
93 launch_shc = False
94
95 if sim_ended_count == 1:
96 args_for_sim = "sleep 1" # Should finish
97 elif sim_ended_count == 2:
98 args_for_sim = "sleep 1 Error" # Worker kill on error
99 elif sim_ended_count == 3:
100 wait = True
101 args_for_sim = "sleep 1" # Should finish
102 launch_shc = True
103 elif sim_ended_count == 4:
104 args_for_sim = "sleep 8" # Worker kill on timeout
105 timeout = 1.0
106 elif sim_ended_count == 5:
107 args_for_sim = "sleep 2 Fail" # Manager kill - if signal received else completes
108
109 task = exctr.submit(calc_type="sim", num_procs=cores, app_args=args_for_sim, hyperthreads=True)
110
111 if wait:
112 task.wait()
113 if not task.finished:
114 calc_status = UNSET_TAG
115 if task.state == "FINISHED":
116 calc_status = WORKER_DONE
117 elif task.state == "FAILED":
118 calc_status = TASK_FAILED
119
120 else:
121 if sim_ended_count >= 2:
122 calc_status = exctr.polling_loop(task, timeout=timeout, delay=0.3, poll_manager=True)
123 if sim_ended_count == 2 and task.stdout_exists() and "Error" in task.read_stdout():
124 calc_status = WORKER_KILL_ON_ERR
125 else:
126 task, calc_status = custom_polling_loop(exctr, task, timeout)
127
128 else:
129 launch_shc = True
130 calc_status = UNSET_TAG
131
132 # Comparing six_hump_camel output, directly called vs. submitted as app
133 for i, x in enumerate(H["x"]):
134 H_o["f"][i] = six_hump_camel_func(x)
135 if launch_shc:
136 # Test launching a named app.
137 app_args = " ".join(str(val) for val in list(x[:]))
138 task = exctr.submit(app_name="six_hump_camel", num_procs=1, app_args=app_args)
139 task.wait()
140 output = np.float64(task.read_stdout())
141 assert np.isclose(H_o["f"][i], output)
142 calc_status = WORKER_DONE
143
144 # This is just for testing at calling script level - status of each task
145 H_o["cstat"] = calc_status
146
147 return H_o, calc_status
148
149
150def six_hump_camel_func(x):
151 """
152 Definition of the six-hump camel
153 """
154 x1 = x[0]
155 x2 = x[1]
156 term1 = (4 - 2.1 * x1**2 + (x1**4) / 3) * x1**2
157 term2 = x1 * x2
158 term3 = (-4 + 4 * x2**2) * x2**2
159
160 return term1 + term2 + term3