Skip to content

Commit 295516b

Browse files
Only really import packages when needed (#410)
* Only really import packages when needed * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 815fd31 commit 295516b

10 files changed

+63
-48
lines changed

adaptive/learner/triangulation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@
1616
ones,
1717
square,
1818
subtract,
19+
zeros,
1920
)
2021
from numpy import sum as np_sum
21-
from numpy import zeros
2222
from numpy.linalg import det as ndet
2323
from numpy.linalg import matrix_rank, norm, slogdet, solve
2424

adaptive/runner.py

+32-25
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import warnings
1515
from contextlib import suppress
1616
from datetime import datetime, timedelta
17+
from importlib.util import find_spec
1718
from typing import TYPE_CHECKING, Any, Callable, Union
1819

1920
import loky
@@ -49,35 +50,32 @@
4950
except ImportError:
5051
from typing_extensions import Literal
5152

52-
try:
53-
import ipyparallel
54-
from ipyparallel.client.asyncresult import AsyncResult
5553

56-
with_ipyparallel = True
57-
ExecutorTypes: TypeAlias = Union[
58-
ExecutorTypes, ipyparallel.Client, ipyparallel.client.view.ViewExecutor
59-
]
60-
FutureTypes: TypeAlias = Union[FutureTypes, AsyncResult]
61-
except ModuleNotFoundError:
62-
with_ipyparallel = False
54+
with_ipyparallel = find_spec("ipyparallel") is not None
55+
with_distributed = find_spec("distributed") is not None
56+
with_mpi4py = find_spec("mpi4py") is not None
6357

64-
try:
65-
import distributed
58+
if TYPE_CHECKING:
59+
if with_distributed:
60+
import distributed
6661

67-
with_distributed = True
68-
ExecutorTypes: TypeAlias = Union[
69-
ExecutorTypes, distributed.Client, distributed.cfexecutor.ClientExecutor
70-
]
71-
except ModuleNotFoundError:
72-
with_distributed = False
62+
ExecutorTypes: TypeAlias = Union[
63+
ExecutorTypes, distributed.Client, distributed.cfexecutor.ClientExecutor
64+
]
7365

74-
try:
75-
import mpi4py.futures
66+
if with_mpi4py:
67+
import mpi4py.futures
7668

77-
with_mpi4py = True
78-
ExecutorTypes: TypeAlias = Union[ExecutorTypes, mpi4py.futures.MPIPoolExecutor]
79-
except ModuleNotFoundError:
80-
with_mpi4py = False
69+
ExecutorTypes: TypeAlias = Union[ExecutorTypes, mpi4py.futures.MPIPoolExecutor]
70+
71+
if with_ipyparallel:
72+
import ipyparallel
73+
from ipyparallel.client.asyncresult import AsyncResult
74+
75+
ExecutorTypes: TypeAlias = Union[
76+
ExecutorTypes, ipyparallel.Client, ipyparallel.client.view.ViewExecutor
77+
]
78+
FutureTypes: TypeAlias = Union[FutureTypes, AsyncResult]
8179

8280
with suppress(ModuleNotFoundError):
8381
import uvloop
@@ -934,9 +932,12 @@ def replay_log(
934932

935933

936934
def _ensure_executor(executor: ExecutorTypes | None) -> concurrent.Executor:
935+
if with_ipyparallel:
936+
import ipyparallel
937+
if with_distributed:
938+
import distributed
937939
if executor is None:
938940
executor = _default_executor()
939-
940941
if isinstance(executor, concurrent.Executor):
941942
return executor
942943
elif with_ipyparallel and isinstance(executor, ipyparallel.Client):
@@ -955,6 +956,12 @@ def _get_ncores(
955956
ex: (ExecutorTypes),
956957
) -> int:
957958
"""Return the maximum number of cores that an executor can use."""
959+
if with_ipyparallel:
960+
import ipyparallel
961+
if with_distributed:
962+
import distributed
963+
if with_mpi4py:
964+
import mpi4py.futures
958965
if with_ipyparallel and isinstance(ex, ipyparallel.client.view.ViewExecutor):
959966
return len(ex.view)
960967
elif isinstance(

docs/logo.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33

44
import holoviews
55
import matplotlib.pyplot as plt
6-
import numpy as np
76
import matplotlib.tri as mtri
7+
import numpy as np
88
from PIL import Image, ImageDraw
99

1010
sys.path.insert(0, os.path.abspath("..")) # to get adaptive on the path

docs/source/algorithms_and_examples.md

+4-2
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,13 @@ Click on the *Play* {fa}`play` button or move the sliders.
4646
:tags: [hide-cell]
4747
4848
import itertools
49-
import adaptive
50-
from adaptive.learner.learner1D import uniform_loss, default_loss
49+
5150
import holoviews as hv
5251
import numpy as np
5352
53+
import adaptive
54+
from adaptive.learner.learner1D import default_loss, uniform_loss
55+
5456
adaptive.notebook_extension()
5557
hv.output(holomap="scrubber")
5658
```

docs/source/tutorial/tutorial.AverageLearner1D.md

+8-6
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
---
2-
kernelspec:
3-
name: python3
4-
display_name: python3
52
jupytext:
63
text_representation:
74
extension: .md
85
format_name: myst
9-
format_version: '0.13'
10-
jupytext_version: 1.13.8
6+
format_version: 0.13
7+
jupytext_version: 1.14.5
8+
kernelspec:
9+
display_name: python3
10+
name: python3
1111
---
12+
1213
# Tutorial {class}`~adaptive.AverageLearner1D`
1314

1415
```{note}
@@ -23,9 +24,10 @@ import adaptive
2324
2425
adaptive.notebook_extension()
2526
27+
from functools import partial
28+
2629
import holoviews as hv
2730
import numpy as np
28-
from functools import partial
2931
```
3032

3133
## General use

docs/source/tutorial/tutorial.BalancingLearner.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,11 @@ import adaptive
2424
2525
adaptive.notebook_extension()
2626
27+
import random
28+
from functools import partial
29+
2730
import holoviews as hv
2831
import numpy as np
29-
from functools import partial
30-
import random
3132
```
3233

3334
The balancing learner is a “meta-learner” that takes a list of learners.

docs/source/tutorial/tutorial.Learner1D.md

+5-4
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,10 @@ import adaptive
2525
2626
adaptive.notebook_extension()
2727
28-
import numpy as np
29-
from functools import partial
3028
import random
29+
from functools import partial
30+
31+
import numpy as np
3132
```
3233

3334
## scalar output: `f:ℝ → ℝ`
@@ -41,8 +42,8 @@ offset = random.uniform(-0.5, 0.5)
4142
4243
4344
def f(x, offset=offset, wait=True):
44-
from time import sleep
4545
from random import random
46+
from time import sleep
4647
4748
a = 0.01
4849
if wait:
@@ -155,8 +156,8 @@ To do this, you need to tell the learner to look at the curvature by specifying
155156
```{code-cell} ipython3
156157
from adaptive.learner.learner1D import (
157158
curvature_loss_function,
158-
uniform_loss,
159159
default_loss,
160+
uniform_loss,
160161
)
161162
162163
curvature_loss = curvature_loss_function()

docs/source/tutorial/tutorial.Learner2D.md

+6-4
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,12 @@ Download the notebook in order to see the real behaviour. [^download]
2020
```{code-cell} ipython3
2121
:tags: [hide-cell]
2222
23-
import adaptive
23+
from functools import partial
24+
2425
import holoviews as hv
2526
import numpy as np
2627
27-
from functools import partial
28+
import adaptive
2829
2930
adaptive.notebook_extension()
3031
```
@@ -33,9 +34,10 @@ Besides 1D functions, we can also learn 2D functions: $f: ℝ^2 → ℝ$.
3334

3435
```{code-cell} ipython3
3536
def ring(xy, wait=True):
36-
import numpy as np
37-
from time import sleep
3837
from random import random
38+
from time import sleep
39+
40+
import numpy as np
3941
4042
if wait:
4143
sleep(random() / 10)

docs/source/tutorial/tutorial.custom_loss.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,8 @@ import adaptive
2525
adaptive.notebook_extension()
2626
2727
# Import modules that are used in multiple cells
28-
import numpy as np
2928
import holoviews as hv
29+
import numpy as np
3030
```
3131

3232
{class}`~adaptive.Learner1D` and {class}`~adaptive.Learner2D` both work on the principle of subdividing their domain into subdomains, and assigning a property to each subdomain, which we call the *loss*.
@@ -137,7 +137,7 @@ def resolution_loss_function(min_distance=0, max_distance=1):
137137
because the total area is normalized to 1."""
138138
139139
def resolution_loss(ip):
140-
from adaptive.learner.learner2D import default_loss, areas
140+
from adaptive.learner.learner2D import areas, default_loss
141141
142142
loss = default_loss(ip)
143143

pyproject.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ python_version = "3.7"
9898
[tool.ruff]
9999
line-length = 150
100100
target-version = "py37"
101-
select = ["B", "C", "E", "F", "W", "T", "B9"]
101+
select = ["B", "C", "E", "F", "W", "T", "B9", "I"]
102102
ignore = [
103103
"T20", # flake8-print
104104
"ANN101", # Missing type annotation for {name} in method

0 commit comments

Comments
 (0)