Just in case it helps someone, I recently needed to use PyNomad in a Python project which was based on asyncio. Here is simpleExample_basic_asyncio.py, an async version of the simpleExample_basic.py example:
import asyncio
import PyNomad
async def optimize_async(bb_async, *args):
loop = asyncio.get_running_loop()
def _bb_sync(p):
return asyncio.run_coroutine_threadsafe(bb_async(p), loop).result()
def _start():
return PyNomad.optimize(_bb_sync, *args)
return await asyncio.to_thread(_start)
PyNomad.optimize_async = optimize_async
async def main():
# This example of blackbox function is for a single process
# The blackbox output must be put in the EvalPoint passed as argument
async def bb(x):
dim = x.size()
f = sum([x.get_coord(i)**2 for i in range(dim)])
x.setBBO(str(f).encode("UTF-8"))
return 1 # 1: success 0: failed evaluation
x0 = [0.71, 0.51, 0.51]
lb = [-1, -1, -1]
ub=[]
params = ["BB_OUTPUT_TYPE OBJ", "MAX_BB_EVAL 100", "UPPER_BOUND * 1", "DISPLAY_DEGREE 2", "DISPLAY_ALL_EVAL false", "DISPLAY_STATS BBE OBJ"]
result = await PyNomad.optimize_async(bb, x0, lb, ub, params)
fmt = ["{} = {}".format(n,v) for (n,v) in result.items()]
output = "\n".join(fmt)
print("\nNOMAD results \n" + output + " \n")
asyncio.run(main())
Essentially a new thread is created just to run the PyNomad.optimize function so that it does not block all the other async stuff going on in the meantime. It is then connected to the existing event loop so that you can call and await the functions.
I am not sure if this is the correct approach, but seems to be working fine for me.
Just in case it helps someone, I recently needed to use PyNomad in a Python project which was based on asyncio. Here is
simpleExample_basic_asyncio.py, an async version of thesimpleExample_basic.pyexample:Essentially a new thread is created just to run the
PyNomad.optimizefunction so that it does not block all the other async stuff going on in the meantime. It is then connected to the existing event loop so that you can call and await the functions.I am not sure if this is the correct approach, but seems to be working fine for me.