Skip to content

Commit f415fb4

Browse files
committed
tutorial about executing coroutines
1 parent 914495c commit f415fb4

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

docs/source/tutorial/tutorial.advanced-topics.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ adaptive.notebook_extension()
2626
import asyncio
2727
from functools import partial
2828
import random
29+
import time
30+
from dask.distributed import Client
2931
3032
offset = random.uniform(-0.5, 0.5)
3133
@@ -367,6 +369,58 @@ await runner.task # This is not needed in a notebook environment!
367369
timer.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

372426
Runners can also be used from a Python script independently of the notebook.

0 commit comments

Comments
 (0)