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:

https://www.sfu.ca/~ssurjano/camel6.html

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 in sim_specs["out"] and pauses for sim_specs["user"]["pause_time"]] if defined.

See also

test_uniform_sampling.py # noqa

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
 16
 17import numpy as np
 18
 19from libensemble.message_numbers import EVAL_SIM_TAG, FINISHED_PERSISTENT_SIM_TAG, PERSIS_STOP, STOP_TAG
 20from libensemble.tools.persistent_support import PersistentSupport
 21
 22
 23def six_hump_camel(H, persis_info, sim_specs, libE_info):
 24    """
 25    Evaluates the six hump camel function for a collection of points given in ``H["x"]``.
 26    Additionally evaluates the gradient if ``"grad"`` is a field in
 27    ``sim_specs["out"]`` and pauses for ``sim_specs["user"]["pause_time"]]`` if
 28    defined.
 29
 30    .. seealso::
 31        `test_uniform_sampling.py  <https://github.com/Libensemble/libensemble/blob/develop/libensemble/tests/functionality_tests/test_uniform_sampling.py>`_ # noqa
 32    """
 33
 34    batch = len(H["x"])
 35    H_o = np.zeros(batch, dtype=sim_specs["out"])
 36
 37    for i, x in enumerate(H["x"]):
 38        H_o["f"][i] = six_hump_camel_func(x)
 39
 40        if "grad" in H_o.dtype.names:
 41            H_o["grad"][i] = six_hump_camel_grad(x)
 42
 43        if "user" in sim_specs and "pause_time" in sim_specs["user"]:
 44            time.sleep(sim_specs["user"]["pause_time"])
 45
 46    return H_o, persis_info
 47
 48
 49def six_hump_camel_simple(x, _, sim_specs):
 50    """
 51    Evaluates the six hump camel function for a single point ``x``.
 52
 53    .. seealso::
 54        `test_fast_alloc.py <https://github.com/Libensemble/libensemble/blob/develop/libensemble/tests/functionality_tests/test_fast_alloc.py>`_ # noqa
 55    """
 56
 57    H_o = np.zeros(1, dtype=sim_specs["out"])
 58
 59    H_o["f"] = six_hump_camel_func(x[0][0][:2])  # Ignore more than 2 entries of x
 60
 61    if sim_specs["user"].get("pause_time"):
 62        time.sleep(sim_specs["user"]["pause_time"])
 63
 64    if sim_specs["user"].get("rand"):
 65        H_o["f"] += np.random.normal(0, 1)
 66
 67    return H_o
 68
 69
 70def persistent_six_hump_camel(H, persis_info, sim_specs, libE_info):
 71    """
 72    Similar to ``six_hump_camel``, but runs in persistent mode.
 73    """
 74
 75    ps = PersistentSupport(libE_info, EVAL_SIM_TAG)
 76
 77    # Either start with a work item to process - or just start and wait for data
 78    if H.size > 0:
 79        tag = None
 80        Work = None
 81        calc_in = H
 82    else:
 83        tag, Work, calc_in = ps.recv()
 84
 85    while tag not in [STOP_TAG, PERSIS_STOP]:
 86        # calc_in: This should either be a function (unpack_work ?) or included/unpacked in ps.recv/ps.send_recv.
 87        if Work is not None:
 88            persis_info = Work.get("persis_info", persis_info)
 89            libE_info = Work.get("libE_info", libE_info)
 90
 91        # Call standard six_hump_camel sim
 92        H_o, persis_info = six_hump_camel(calc_in, persis_info, sim_specs, libE_info)
 93
 94        tag, Work, calc_in = ps.send_recv(H_o)
 95
 96    final_return = None
 97
 98    # Overwrite final point - for testing only
 99    if sim_specs["user"].get("replace_final_fields", 0):
100        calc_in = np.ones(1, dtype=[("x", float, (2,))])
101        H_o, persis_info = six_hump_camel(calc_in, persis_info, sim_specs, libE_info)
102        final_return = H_o
103
104    return final_return, persis_info, FINISHED_PERSISTENT_SIM_TAG
105
106
107def six_hump_camel_func(x):
108    """
109    Definition of the six-hump camel
110    """
111    x1 = x[0]
112    x2 = x[1]
113    term1 = (4 - 2.1 * x1**2 + (x1**4) / 3) * x1**2
114    term2 = x1 * x2
115    term3 = (-4 + 4 * x2**2) * x2**2
116
117    return term1 + term2 + term3
118
119
120def six_hump_camel_grad(x):
121    """
122    Definition of the six-hump camel gradient
123    """
124
125    x1 = x[0]
126    x2 = x[1]
127    grad = np.zeros(2)
128
129    grad[0] = 2.0 * (x1**5 - 4.2 * x1**3 + 4.0 * x1 + 0.5 * x2)
130    grad[1] = x1 + 16 * x2**3 - 8 * x2
131
132    return grad
133
134
135if __name__ == "__main__":
136    x = (float(sys.argv[1]), float(sys.argv[2]))
137    result = six_hump_camel_func(x)
138    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 in sim_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_persistent_aposmm_pounders.py # noqa for an example where the entire fvec is computed each call.

See also

test_uniform_sampling_one_residual_at_a_time.py # noqa 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

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 (numpy.typing.NDArray) –

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:

f – vector of dimension (n, 1): flow rate through the Borehole (m^3/year)

Return type:

numpy.ndarray

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, info)

Tests launching and polling task and exiting on task finish

executor_hworld.py
  1import numpy as np
  2
  3from libensemble.message_numbers import (
  4    MAN_SIGNAL_FINISH,
  5    TASK_FAILED,
  6    UNSET_TAG,
  7    WORKER_DONE,
  8    WORKER_KILL_ON_ERR,
  9    WORKER_KILL_ON_TIMEOUT,
 10)
 11
 12__all__ = ["executor_hworld"]
 13
 14# Alt send values through X
 15sim_ended_count = 0
 16
 17
 18def custom_polling_loop(exctr, task, timeout_sec=5.0, delay=0.3):
 19    import time
 20
 21    calc_status = UNSET_TAG  # Sim func determines status of libensemble calc - returned to worker
 22
 23    while task.runtime < timeout_sec:
 24        time.sleep(delay)
 25
 26        if exctr.manager_kill_received():
 27            exctr.kill(task)
 28            calc_status = MAN_SIGNAL_FINISH  # Worker will pick this up and close down
 29            print(f"Task {task.id} killed by manager on worker {exctr.workerID}")
 30            break
 31
 32        task.poll()
 33        if task.finished:
 34            break
 35        elif task.state == "RUNNING":
 36            print(f"Task {task.id} still running on worker {exctr.workerID} ....")
 37
 38        if task.stdout_exists():
 39            if "Error" in task.read_stdout():
 40                print(
 41                    "Found (deliberate) Error in output file - cancelling " f"task {task.id} on worker {exctr.workerID}"
 42                )
 43                exctr.kill(task)
 44                calc_status = WORKER_KILL_ON_ERR
 45                break
 46
 47    # After exiting loop
 48    if task.finished:
 49        print(f"Task {task.id} done on worker {exctr.workerID}")
 50        # Fill in calc_status if not already
 51        if calc_status == UNSET_TAG:
 52            if task.state == "FINISHED":  # Means finished successfully
 53                calc_status = WORKER_DONE
 54            elif task.state == "FAILED":
 55                calc_status = TASK_FAILED
 56
 57    else:
 58        # assert task.state == 'RUNNING', "task.state expected to be RUNNING. Returned: " + str(task.state)
 59        print(f"Task {task.id} timed out - killing on worker {exctr.workerID}")
 60        exctr.kill(task)
 61        if task.finished:
 62            print(f"Task {task.id} done on worker {exctr.workerID}")
 63        calc_status = WORKER_KILL_ON_TIMEOUT
 64
 65    return task, calc_status
 66
 67
 68def executor_hworld(H, _, sim_specs, info):
 69    """Tests launching and polling task and exiting on task finish"""
 70    exctr = info["executor"]
 71    cores = sim_specs["user"]["cores"]
 72    ELAPSED_TIMEOUT = "elapsed_timeout" in sim_specs["user"]
 73
 74    wait = False
 75    args_for_sim = "sleep 1"
 76    calc_status = UNSET_TAG
 77
 78    batch = len(H["x"])
 79    H_o = np.zeros(batch, dtype=sim_specs["out"])
 80
 81    if "six_hump_camel" not in exctr.default_app("sim").full_path:
 82        global sim_ended_count
 83        sim_ended_count += 1
 84        print("sim_ended_count", sim_ended_count, flush=True)
 85
 86        if ELAPSED_TIMEOUT:
 87            args_for_sim = "sleep 60"  # Manager kill - if signal received else completes
 88            timeout = 65.0
 89
 90        else:
 91            timeout = 6.0
 92            launch_shc = False
 93
 94            if sim_ended_count == 1:
 95                args_for_sim = "sleep 1"  # Should finish
 96            elif sim_ended_count == 2:
 97                args_for_sim = "sleep 1 Error"  # Worker kill on error
 98            elif sim_ended_count == 3:
 99                wait = True
100                args_for_sim = "sleep 1"  # Should finish
101                launch_shc = True
102            elif sim_ended_count == 4:
103                args_for_sim = "sleep 8"  # Worker kill on timeout
104                timeout = 1.0
105            elif sim_ended_count == 5:
106                args_for_sim = "sleep 2 Fail"  # Manager kill - if signal received else completes
107
108        task = exctr.submit(calc_type="sim", num_procs=cores, app_args=args_for_sim, hyperthreads=True)
109
110        if wait:
111            task.wait()
112            if not task.finished:
113                calc_status = UNSET_TAG
114            if task.state == "FINISHED":
115                calc_status = WORKER_DONE
116            elif task.state == "FAILED":
117                calc_status = TASK_FAILED
118
119        else:
120            if sim_ended_count >= 2:
121                calc_status = exctr.polling_loop(task, timeout=timeout, delay=0.3, poll_manager=True)
122                if sim_ended_count == 2 and task.stdout_exists() and "Error" in task.read_stdout():
123                    calc_status = WORKER_KILL_ON_ERR
124            else:
125                task, calc_status = custom_polling_loop(exctr, task, timeout)
126
127    else:
128        launch_shc = True
129        calc_status = UNSET_TAG
130
131        # Comparing six_hump_camel output, directly called vs. submitted as app
132        for i, x in enumerate(H["x"]):
133            H_o["f"][i] = six_hump_camel_func(x)
134            if launch_shc:
135                # Test launching a named app.
136                app_args = " ".join(str(val) for val in list(x[:]))
137                task = exctr.submit(app_name="six_hump_camel", num_procs=1, app_args=app_args)
138                task.wait()
139                output = np.float64(task.read_stdout())
140                assert np.isclose(H_o["f"][i], output)
141                calc_status = WORKER_DONE
142
143    # This is just for testing at calling script level - status of each task
144    H_o["cstat"] = calc_status
145
146    return H_o, calc_status
147
148
149def six_hump_camel_func(x):
150    """
151    Definition of the six-hump camel
152    """
153    x1 = x[0]
154    x2 = x[1]
155    term1 = (4 - 2.1 * x1**2 + (x1**4) / 3) * x1**2
156    term2 = x1 * x2
157    term3 = (-4 + 4 * x2**2) * x2**2
158
159    return term1 + term2 + term3