@@ -26,6 +26,8 @@ adaptive.notebook_extension()
2626import asyncio
2727from functools import partial
2828import random
29+ import time
30+ from dask.distributed import Client
2931
3032offset = random.uniform(-0.5, 0.5)
3133
@@ -367,6 +369,58 @@ await runner.task # This is not needed in a notebook environment!
367369timer.result()
368370```
369371
372+ ## Executing an asynchronous runner
373+
374+ In this example we will show how to send complex tasks to adaptive as coroutines.
375+ We require an asynchronous client to perform the execution of asynchronous tasks.
376+ In this case, it is imported from ` dask.distributed ` .
377+
378+ ``` {code-cell} ipython3
379+ client = await Client(asynchronous=True)
380+ ```
381+
382+ Once we have an asynchronous client, all its instances will be coroutines and they need to be called accordingly.
383+ For example, ` await client.close() ` .
384+
385+ In this case, we consider a function ` h ` that has some internal dependency on a function ` g ` .
386+ The function to be learned is ` async_h ` , which submits ` h ` as a coroutine to the client.
387+
388+ ``` {code-cell} ipython3
389+ def h(x, offset=offset):
390+ a = 0.01
391+ x = g(x)
392+ return x + a**2 / (a**2 + (x - offset) ** 2)
393+
394+ def g(x):
395+ time.sleep(np.random.randint(5))
396+ return x**2
397+
398+ async def async_h(x):
399+ return await client.submit(h, x)
400+ ```
401+
402+ When provide the asynchronous function to the ` learner ` and run it via ` AsyncRunner ` .
403+
404+ ``` {code-cell} ipython3
405+ learner = adaptive.Learner1D(
406+ async_h,
407+ bounds=(-1, 1)
408+ )
409+
410+ runner = adaptive.AsyncRunner(
411+ learner,
412+ goal=lambda l: l.loss() < 0.01,
413+ ntasks=20
414+ )
415+ ```
416+
417+ We await for the runner to finish, and then plot the result.
418+
419+ ``` {code-cell} ipython3
420+ await runner.task
421+ learner.plot
422+ ```
423+
370424## Using Runners from a script
371425
372426Runners can also be used from a Python script independently of the notebook.
0 commit comments