### Development Installation Source: https://adaptive.readthedocs.io/en/latest/docs For development, clone the repository and install the library in editable mode with development and testing dependencies. This command adds the cloned repository to your Python path. ```bash pip install -e ".[notebook,test,other]" ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://adaptive.readthedocs.io/en/latest/_downloads/d8992eb4d2c8564d423ead2ad758095b/tutorial Initializes the adaptive notebook extension for interactive use. This is typically a one-time setup for the environment. ```ipython3 import adaptive adaptive.notebook_extension() from functools import partial import holoviews as hv import numpy as np ``` -------------------------------- ### Install adaptive with PyPI Source: https://adaptive.readthedocs.io/en/latest/docs The adaptive library can also be installed using pip from PyPI. The `[notebook]` extra installs optional dependencies for Jupyter/IPython Notebook integration. ```bash pip install "adaptive[notebook]" ``` -------------------------------- ### Install adaptive with conda Source: https://adaptive.readthedocs.io/en/latest/docs The recommended way to install the adaptive library is using conda. This command installs the core library. ```bash conda install -c conda-forge adaptive ``` -------------------------------- ### Install pre-commit for Code Style Source: https://adaptive.readthedocs.io/en/latest/docs To maintain consistent code style, install pre-commit by running this command in the repository. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Adaptive Runner Module Imports and Setup Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/runner This snippet shows the necessary imports and setup for the adaptive.runner module. It includes standard libraries like asyncio, concurrent.futures, and typing, as well as specific adaptive library components like BalancingLearner and DataSaver. It also checks for optional dependencies like ipyparallel, distributed, and mpi4py, and configures asyncio event loop policy if uvloop is available. ```Python from__future__import annotations importabc importasyncio importconcurrent.futuresasconcurrent importfunctools importinspect importitertools importpickle importplatform importtime importtraceback importwarnings fromcollections.abcimport Callable fromcontextlibimport suppress fromdatetimeimport datetime, timedelta fromimportlib.utilimport find_spec fromtypingimport TYPE_CHECKING, Any, Literal, TypeAlias importloky fromadaptiveimport BalancingLearner, DataSaver, IntegratorLearner, SequenceLearner fromadaptive.learner.base_learnerimport LearnerType fromadaptive.notebook_integrationimport in_ipynb, live_info, live_plot fromadaptive.utilsimport SequentialExecutor FutureTypes: TypeAlias = concurrent.Future | asyncio.Future if TYPE_CHECKING: importholoviews from._typesimport ExecutorTypes with_ipyparallel = find_spec("ipyparallel") is not None with_distributed = find_spec("distributed") is not None with_mpi4py = find_spec("mpi4py") is not None with suppress(ModuleNotFoundError): importuvloop asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) ``` -------------------------------- ### Custom Parallelization with dask.distributed and adaptive.utils.daskify Source: https://adaptive.readthedocs.io/en/latest/tutorial/tutorial Illustrates custom parallelization using dask.distributed and the `adaptive.utils.daskify` decorator. This example shows how to parallelize functions with and without caching, and how to integrate them into an Adaptive runner. ```python from dask.distributed import Client import adaptive client = await Client(asynchronous=True) # The g function has caching enabled g_dask = adaptive.utils.daskify(client, cache=True)(g) # The h function does not use caching h_dask = adaptive.utils.daskify(client)(h) async def f_parallel(x): g_result = await g_dask(int(x)) h_result = await h_dask(x % 1) return (g_result + h_result) ** 2 learner = adaptive.Learner1D(f_parallel, bounds=(-3.5, 3.5)) runner = adaptive.AsyncRunner(learner, loss_goal=0.01, ntasks=20) runner.live_info() ``` ```python await runner.task learner.plot() ``` -------------------------------- ### Get Intervals from Neighbors Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/learner1D Calculates intervals based on a given point, its neighbors, and the number of neighboring intervals to consider. It determines the start and end points for slicing the neighbors and returns a list of tuples representing the intervals. ```Python def_get_intervals( x: float, neighbors: NeighborsType, nth_neighbors: int ) -> list[tuple[float, float]]: nn = nth_neighbors i = neighbors.index(x) start = max(0, i - nn - 1) end = min(len(neighbors), i + nn + 2) points = neighbors.keys()[start:end] return list(zip(points, points[1:])) ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://adaptive.readthedocs.io/en/latest/_downloads/334f4cbebd44fe403db1c1cc5d230513/tutorial Initializes the adaptive notebook extension and imports necessary libraries for adaptive learning, random number generation, partial function application, holoviews plotting, and numerical operations. ```ipython3 import adaptive adaptive.notebook_extension() import random from functools import partial import holoviews as hv import numpy as np ``` -------------------------------- ### Initialize Adaptive and HoloViews Source: https://adaptive.readthedocs.io/en/latest/_downloads/396068400fdf2e098d3be60246629d77/tutorial Imports necessary libraries (adaptive, holoviews, numpy) and sets up the adaptive notebook extension. Includes a helper function to convert HoloViews DynamicMaps to HoloMaps. ```ipython3 import adaptive adaptive.notebook_extension() import holoviews as hv import numpy as np def dynamicmap_to_holomap(dm): # XXX: change when https://github.com/ioam/holoviews/issues/3085 # is fixed. vals = {d.name: d.values for d in dm.dimensions() if d.values} return hv.HoloMap(dm.select(**vals)) ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://adaptive.readthedocs.io/en/latest/_downloads/85bb926f4b795cc0e3af11284c388a6c/tutorial Imports the adaptive library and initializes the notebook extension for interactive plotting and data visualization. ```ipython3 import adaptive adaptive.notebook_extension() import random from functools import partial import numpy as np ``` -------------------------------- ### Create and Run AverageLearner Source: https://adaptive.readthedocs.io/en/latest/_downloads/26281dec19e19addeaa397f6b415f6b3/tutorial Creates an instance of `adaptive.AverageLearner` with a specified function `g` and relative tolerance `rtol`. It then initializes an `adaptive.Runner` to execute the learner until a loss goal is met. ```ipython3 learner = adaptive.AverageLearner(g, atol=None, rtol=0.01) # `loss < 1.0` means that we reached the `rtol` or `atol` runner = adaptive.Runner(learner, loss_goal=1.0) ``` -------------------------------- ### Ensure Plotly Availability Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/notebook_integration Checks if the plotly library is installed and available, initializing its notebook mode if it's the first time it's being used. Raises a RuntimeError if plotly is not installed. ```Python [docs] defensure_plotly(): global _plotly_enabled try: importplotly if not _plotly_enabled: importplotly.figure_factory importplotly.graph_objs importplotly.offline # This injects javascript and should happen only once plotly.offline.init_notebook_mode() _plotly_enabled = True return plotly except ModuleNotFoundError as e: raise RuntimeError("plotly is not installed; plotting is disabled.") frome ``` -------------------------------- ### Adaptive Learner Setup and Benchmarking Utilities Source: https://adaptive.readthedocs.io/en/latest/_downloads/e40908f34f34adb446212d2eca21c8dd/benchmarks Sets up adaptive learners, homogeneous learners, plotting functions, error metrics (L1 norm), and benchmark execution for 1D and 2D cases. Includes functions to run benchmarks, store results, and plot comparisons. ```ipython3 from __future__ import annotations import itertools import holoviews as hv import numpy as np import pandas as pd from scipy.interpolate import interp1d import adaptive adaptive.notebook_extension() benchmarks = {} benchmarks_2d = {} def homogeneous_learner(learner): if isinstance(learner, adaptive.Learner1D): xs = np.linspace(*learner.bounds, learner.npoints) homo_learner = adaptive.Learner1D(learner.function, learner.bounds) homo_learner.tell_many(xs, learner.function(xs)) else: homo_learner = adaptive.Learner2D(learner.function, bounds=learner.bounds) n = int(learner.npoints**0.5) xs, ys = (np.linspace(*bounds, n) for bounds in learner.bounds) xys = list(itertools.product(xs, ys)) zs = map(homo_learner.function, xys) homo_learner.tell_many(xys, zs) return homo_learner def plot(learner, other_learner): if isinstance(learner, adaptive.Learner1D): return learner.plot() + other_learner.plot() else: n = int(learner.npoints**0.5) return ( ( other_learner.plot(n).relabel("Homogeneous grid") + learner.plot().relabel("With adaptive") + other_learner.plot(n, tri_alpha=0.4) + learner.plot(tri_alpha=0.4) ) .cols(2) .options(hv.opts.EdgePaths(color="w")) ) def err(ys, ys_other): abserr = np.abs(ys - ys_other) return np.average(abserr**2) ** 0.5 def l1_norm_error(learner, other_learner): if isinstance(learner, adaptive.Learner1D): ys_interp = interp1d(*learner.to_numpy().T) xs, _ = other_learner.to_numpy().T ys = ys_interp(xs) # interpolate the other learner's points _, ys_other = other_learner.to_numpy().T return err(ys, ys_other) else: xys = other_learner.to_numpy()[:, :2] zs = learner.function(xys.T) interpolator = learner.interpolator() zs_interp = interpolator(xys) # Compute the L1 norm error between the true function and the interpolator return err(zs_interp, zs) def run_and_plot(learner, **goal): adaptive.runner.simple(learner, **goal) homo_learner = homogeneous_learner(learner) bms = benchmarks if isinstance(learner, adaptive.Learner1D) else benchmarks_2d bm = { "npoints": learner.npoints, "error": l1_norm_error(learner, homo_learner), "uniform_error": l1_norm_error(homo_learner, learner), } bm["error_ratio"] = bm["uniform_error"] / bm["error"] bms[learner.function.__name__] = bm display(pd.DataFrame([bm])) # noqa: F821 return plot(learner, homo_learner).relabel( f"{learner.function.__name__} function with {learner.npoints} points" ) def to_df(benchmarks): df = pd.DataFrame(benchmarks).T df.sort_values("error_ratio", ascending=False, inplace=True) return df def plot_benchmarks(df, max_ratio: float = 1000, *, log_scale: bool = True): import matplotlib.pyplot as plt import numpy as np df_hist = df.copy() # Replace infinite values with 1000 df_hist.loc[np.isinf(df_hist.error_ratio), "error_ratio"] = max_ratio # Convert the DataFrame index (function names) into a column df_hist.reset_index(inplace=True) df_hist.rename(columns={"index": "function_name"}, inplace=True) # Create a list of colors based on the error_ratio values bar_colors = ["green" if x > 1 else "red" for x in df_hist["error_ratio"]] # Create the bar chart plt.figure(figsize=(12, 6)) plt.bar(df_hist["function_name"], df_hist["error_ratio"], color=bar_colors) # Add a dashed horizontal line at 1 plt.axhline(y=1, linestyle="--", color="gray", linewidth=1) if log_scale: # Set the y-axis to log scale plt.yscale("log") # Customize the plot plt.xlabel("Function Name") plt.ylabel("Error Ratio (uniform Error / Learner Error)") plt.title("Error Ratio Comparison for Different Functions") plt.xticks(rotation=45) # Show the plot plt.show() ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://adaptive.readthedocs.io/en/latest/_downloads/1eb289b40446b5fe66720f1653f84170/tutorial Imports necessary libraries (functools, holoviews, numpy) and initializes the adaptive notebook extension. This is a prerequisite for using adaptive features in a Jupyter environment. ```ipython3 from functools import partial import holoviews as hv import numpy as np import adaptive adaptive.notebook_extension() ``` -------------------------------- ### Get Hull Mesh - Plotly Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/learnerND Internal helper function to get the hull mesh for plotting. It computes the convex hull of the domain points and assigns colors to coplanar triangles to form faces. ```Python def _get_hull_mesh(self, opacity=0.2): plotly = ensure_plotly() hull = scipy.spatial.ConvexHull(self._bounds_points) # Find the colors of each plane, giving triangles which are coplanar # the same color, such that a square face has the same color. color_dict = {} def _get_plane_color(simplex): simplex = tuple(simplex) # If the volume of the two triangles combined is zero then they # belong to the same plane. for simplex_key, color in color_dict.items(): points = [hull.points[i] for i in set(simplex_key + simplex)] points = np.array(points) if np.linalg.matrix_rank(points[1:] - points[0]) < 3: return color if scipy.spatial.ConvexHull(points).volume < 1e-5: return color color_dict[simplex] = tuple(random.randint(0, 255) for _ in range(3)) return color_dict[simplex] colors = [_get_plane_color(simplex) for simplex in hull.simplices] # This is a placeholder for the actual mesh creation logic which is missing in the provided snippet. # A full implementation would involve creating a Plotly mesh3d object using hull.simplices and colors. # For demonstration, returning a dummy object. return {"type": "mesh3d", "opacity": opacity} # Dummy object representing a mesh ``` -------------------------------- ### Get Number of Evaluated Points Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/learner1D Returns the total number of points that have been evaluated. ```Python @property def npoints(self) -> int: """Number of evaluated points.""" return len(self.data) ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://adaptive.readthedocs.io/en/latest/_downloads/3f487fe826271204d366200ea9158727/tutorial Initializes the Adaptive notebook extension for interactive use within Jupyter environments. This is typically the first step when using Adaptive in a notebook. ```ipython3 import adaptive adaptive.notebook_extension() import asyncio import random offset = random.uniform(-0.5, 0.5) def f(x, offset=offset): a = 0.01 return x + a**2 / (a**2 + (x - offset) ** 2) ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://adaptive.readthedocs.io/en/latest/_downloads/6d283a3609e57fe0131eb8de6e23940d/tutorial Imports necessary libraries and initializes the adaptive notebook extension for interactive plotting and functionality within a Jupyter environment. ```ipython3 import adaptive adaptive.notebook_extension() # Import modules that are used in multiple cells import holoviews as hv import numpy as np ``` -------------------------------- ### Dimension Property Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/triangulation A property to get the dimension of the triangulation based on the coordinates of its vertices. ```Python @property def dim(self): return len(self.vertices[0]) ``` -------------------------------- ### Get Number of Evaluated Points Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/learnerND Returns the total number of points that have been evaluated by the learner. ```Python @property def npoints(self): """Number of evaluated points.""" return len(self.data) ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://adaptive.readthedocs.io/en/latest/_downloads/163be7a75fb97ad697e12b3c78d35bb2/tutorial Imports necessary libraries and initializes the adaptive notebook extension. This is a prerequisite for using adaptive features in a Jupyter environment. ```ipython3 import adaptive adaptive.notebook_extension() import holoviews as hv import numpy as np ``` -------------------------------- ### Get Number of Evaluated Points Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/learner2D Returns the total number of points that have been evaluated by the learner. ```Python @property def npoints(self) -> int: """Number of evaluated points.""" return len(self.data) ``` -------------------------------- ### Create and Run Balancing Learner Source: https://adaptive.readthedocs.io/en/latest/_downloads/334f4cbebd44fe403db1c1cc5d230513/tutorial Defines a function `h(x, offset)` and creates 10 instances of `Learner1D` with random offsets. These learners are then combined into a `BalancingLearner`, and a `Runner` is initialized with a loss goal of 0.01. ```ipython3 def h(x, offset=0): a = 0.01 return x + a**2 / (a**2 + (x - offset) ** 2) learners = [ adaptive.Learner1D(partial(h, offset=random.uniform(-1, 1)), bounds=(-1, 1)) for i in range(10) ] bal_learner = adaptive.BalancingLearner(learners) runner = adaptive.Runner(bal_learner, loss_goal=0.01) ``` -------------------------------- ### Adaptive Sampling Benchmark Setup and Utilities Source: https://adaptive.readthedocs.io/en/latest/benchmarks Provides core functions for adaptive sampling benchmarks. Includes creating homogeneous learners for comparison, calculating L1 norm errors, running the sampling process, and plotting results. It also includes utilities for converting benchmark data to DataFrames and plotting the error ratios. ```Python from__future__import annotations importitertools importholoviewsashv importnumpyasnp importpandasaspd fromscipy.interpolateimport interp1d importadaptive adaptive.notebook_extension() benchmarks = {} benchmarks_2d = {} defhomogeneous_learner(learner): if isinstance(learner, adaptive.Learner1D): xs = np.linspace(*learner.bounds, learner.npoints) homo_learner = adaptive.Learner1D(learner.function, learner.bounds) homo_learner.tell_many(xs, learner.function(xs)) else: homo_learner = adaptive.Learner2D(learner.function, bounds=learner.bounds) n = int(learner.npoints**0.5) xs, ys = (np.linspace(*bounds, n) for bounds in learner.bounds) xys = list(itertools.product(xs, ys)) zs = map(homo_learner.function, xys) homo_learner.tell_many(xys, zs) return homo_learner defplot(learner, other_learner): if isinstance(learner, adaptive.Learner1D): return learner.plot() + other_learner.plot() else: n = int(learner.npoints**0.5) return ( ( other_learner.plot(n).relabel("Homogeneous grid") + learner.plot().relabel("With adaptive") + other_learner.plot(n, tri_alpha=0.4) + learner.plot(tri_alpha=0.4) ) .cols(2) .options(hv.opts.EdgePaths(color="w")) ) deferr(ys, ys_other): abserr = np.abs(ys - ys_other) return np.average(abserr**2) ** 0.5 defl1_norm_error(learner, other_learner): if isinstance(learner, adaptive.Learner1D): ys_interp = interp1d(*learner.to_numpy().T) xs, _ = other_learner.to_numpy().T ys = ys_interp(xs) # interpolate the other learner's points _, ys_other = other_learner.to_numpy().T return err(ys, ys_other) else: xys = other_learner.to_numpy()[:, :2] zs = learner.function(xys.T) interpolator = learner.interpolator() zs_interp = interpolator(xys) # Compute the L1 norm error between the true function and the interpolator return err(zs_interp, zs) defrun_and_plot(learner, **goal): adaptive.runner.simple(learner, **goal) homo_learner = homogeneous_learner(learner) bms = benchmarks if isinstance(learner, adaptive.Learner1D) else benchmarks_2d bm = { "npoints": learner.npoints, "error": l1_norm_error(learner, homo_learner), "uniform_error": l1_norm_error(homo_learner, learner), } bm["error_ratio"] = bm["uniform_error"] / bm["error"] bms[learner.function.__name__] = bm display(pd.DataFrame([bm])) # noqa: F821 return plot(learner, homo_learner).relabel( f"{learner.function.__name__} function with {learner.npoints} points" ) defto_df(benchmarks): df = pd.DataFrame(benchmarks).T df.sort_values("error_ratio", ascending=False, inplace=True) return df defplot_benchmarks(df, max_ratio: float = 1000, *, log_scale: bool = True): importmatplotlib.pyplotasplt importnumpyasnp df_hist = df.copy() # Replace infinite values with 1000 df_hist.loc[np.isinf(df_hist.error_ratio), "error_ratio"] = max_ratio # Convert the DataFrame index (function names) into a column df_hist.reset_index(inplace=True) df_hist.rename(columns={"index": "function_name"}, inplace=True) # Create a list of colors based on the error_ratio values bar_colors = ["green" if x > 1 else "red" for x in df_hist["error_ratio"]] # Create the bar chart plt.figure(figsize=(12, 6)) plt.bar(df_hist["function_name"], df_hist["error_ratio"], color=bar_colors) # Add a dashed horizontal line at 1 plt.axhline(y=1, linestyle="--", color="gray", linewidth=1) if log_scale: # Set the y-axis to log scale plt.yscale("log") # Customize the plot plt.xlabel("Function Name") plt.ylabel("Error Ratio (uniform Error / Learner Error)") plt.title("Error Ratio Comparison for Different Functions") plt.xticks(rotation=45) # Show the plot plt.show() ``` -------------------------------- ### Get Neighbors from Vertices Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/triangulation Retrieves all simplices that share at least one vertex with the given simplex. ```python def get_neighbors_from_vertices(self, simplex): return set.union(*[self.vertex_to_simplices[p] for p in simplex]) ``` -------------------------------- ### Number of Evaluated Points Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/integrator_learner Provides a property to get the total number of points that have been evaluated by the learner. ```Python @property defnpoints(self) -> int: # type: ignore[override] """Number of evaluated points.""" return len(self.data) ``` -------------------------------- ### Compare Adaptive vs. Homogeneous Sampling Source: https://adaptive.readthedocs.io/en/latest/_downloads/1eb289b40446b5fe66720f1653f84170/tutorial Creates a Learner2D and populates it with data from a homogeneous grid. It then compares the visualization of this grid-based sampling with the adaptive sampling results from the `runner`. ```ipython3 import itertools # Create a learner and add data on homogeneous grid, so that we can plot it learner2 = adaptive.Learner2D(ring, bounds=learner.bounds) n = int(learner.npoints**0.5) xs, ys = (np.linspace(*bounds, n) for bounds in learner.bounds) xys = list(itertools.product(xs, ys)) learner2.tell_many(xys, map(partial(ring, wait=False), xys)) ( learner2.plot(n).relabel("Homogeneous grid") + learner.plot().relabel("With adaptive") + learner2.plot(n, tri_alpha=0.4) + learner.plot(tri_alpha=0.4) ).cols(2).opts(hv.opts.EdgePaths(color="w")) ``` -------------------------------- ### Ensure Holoviews Availability Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/notebook_integration Checks if the holoviews library is installed and available. If not, it raises a RuntimeError indicating that plotting is disabled. ```Python [docs] defensure_holoviews(): try: return importlib.import_module("holoviews") except ModuleNotFoundError: raise RuntimeError( "holoviews is not installed; plotting is disabled." ) fromNone ``` -------------------------------- ### Adaptive 1D Function Learning with Learner1D Source: https://adaptive.readthedocs.io/en/latest/algorithms_and_examples Demonstrates how to use the Learner1D class to adaptively learn a 1D function. It includes setting up the learner, defining a goal for the learning process, and running the learning process with live plotting and information display in a Jupyter notebook. ```Python from adaptive.notebook_extension import notebook_extension from adaptive import Runner, Learner1D notebook_extension() # enables notebook integration def peak(x, a=0.01): # function to "learn" return x + a**2 / (a**2 + x**2) learner = Learner1D(peak, bounds=(-1, 1)) def goal(learner): return learner.loss() < 0.01 # continue until loss is small enough runner = Runner(learner, goal) # start calculation on all CPU cores runner.live_info() # shows a widget with status information runner.live_plot() ``` -------------------------------- ### Get Opposing Vertices Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/triangulation For a given simplex, finds the vertex in each neighboring simplex that is opposite to the shared face. ```python def get_opposing_vertices(self, simplex): if simplex not in self.simplices: raise ValueError("Provided simplex is not part of the triangulation") neighbors = self.get_simplices_attached_to_points(simplex) deffind_opposing_vertex(vertex): # find the simplex: simp = next((x for x in neighbors if vertex not in x), None) if simp is None: return None opposing = set(simp) - set(simplex) assert len(opposing) == 1 return opposing.pop() result = tuple(find_opposing_vertex(v) for v in simplex) return result ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://adaptive.readthedocs.io/en/latest/_downloads/6441177176eeb88a098e436a31d62bcb/tutorial Imports necessary libraries and initializes the adaptive notebook extension. This is a prerequisite for using adaptive features in a Jupyter environment. ```ipython3 import adaptive adaptive.notebook_extension() import holoviews as hv import numpy as np ``` -------------------------------- ### Get Points as NumPy Array Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/learnerND Retrieves all the points known to the learner and returns them as a NumPy array of type float. ```Python @property def points(self): """Get the points from `data` as a numpy array.""" return np.array(list(self.data.keys()), dtype=float) ``` -------------------------------- ### Initialize IntegratorLearner and Runner Source: https://adaptive.readthedocs.io/en/latest/_downloads/6441177176eeb88a098e436a31d62bcb/tutorial Initializes an `IntegratorLearner` for the function `f24` with specified bounds and tolerance. It then sets up an `adaptive.Runner` with a `SequentialExecutor` to manage the learning process. ```ipython3 from adaptive.runner import SequentialExecutor learner = adaptive.IntegratorLearner(f24, bounds=(0, 3), tol=1e-8) # We use a SequentialExecutor, which runs the function to be learned in # *this* process only. This means we don't pay # the overhead of evaluating the function in another process. runner = adaptive.Runner(learner, executor=SequentialExecutor()) ``` -------------------------------- ### Create and Run SequenceLearner Source: https://adaptive.readthedocs.io/en/latest/_downloads/163be7a75fb97ad697e12b3c78d35bb2/tutorial Defines a function `f(x)` that squares its input and creates a SequenceLearner with this function and a predefined sequence of numbers. It then initializes an adaptive Runner to manage the learning process. ```ipython3 from adaptive import SequenceLearner def f(x): return int(x) ** 2 seq = np.linspace(-15, 15, 1000) learner = SequenceLearner(f, seq) runner = adaptive.Runner(learner) # not providing a goal is same as `lambda learner: learner.done()` ``` -------------------------------- ### Display Live Runner Information for Vector Output Source: https://adaptive.readthedocs.io/en/latest/_downloads/85bb926f4b795cc0e3af11284c388a6c/tutorial Shows live progress updates for the runner sampling the vector output function. ```ipython3 runner.live_info() ``` -------------------------------- ### Get Scale Property Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/learnerND A property that returns the scale of the output values, calculated as the difference between the maximum and minimum values observed. ```Python @property def _scale(self): # get the output scale return self._max_value - self._min_value ``` -------------------------------- ### Get Point by Index Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/learner1D Retrieves a point (x-value) from the neighbors list using its index. Returns None if the index is out of bounds. ```Python def _get_point_by_index(self, ind: int) -> float | None: if ind < 0 or ind >= len(self.neighbors): return None return self.neighbors.keys()[ind] ``` -------------------------------- ### Display Live Learner Information Source: https://adaptive.readthedocs.io/en/latest/_downloads/85bb926f4b795cc0e3af11284c388a6c/tutorial This snippet shows how to display live information about the adaptive runner, providing insights into the learner's progress and status. ```ipython3 runner.live_info() ``` -------------------------------- ### Get Face Sharing Neighbors Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/triangulation Filters a set of neighboring simplices to keep only those that share an entire face with the given simplex. ```python def get_face_sharing_neighbors(self, neighbors, simplex): """Keep only the simplices sharing a whole face with simplex.""" return { simpl for simpl in neighbors if len(set(simpl) & set(simplex)) == self.dim } # they share a face ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://adaptive.readthedocs.io/en/latest/_downloads/26281dec19e19addeaa397f6b415f6b3/tutorial Initializes the adaptive notebook extension, which is necessary for using adaptive features within a Jupyter notebook environment. ```ipython3 import adaptive adaptive.notebook_extension() ``` -------------------------------- ### BalancingLearner Properties Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/balancing_learner Provides methods to get the total number of points and samples from learners, and manages the strategy for selecting points. ```Python def npoints(self) -> int: return sum(lrn.npoints for lrn in self.learners) @property def nsamples(self): if hasattr(self.learners[0], "nsamples"): return sum(lrn.nsamples for lrn in self.learners) else: raise AttributeError( f"{type(self.learners[0])} as no attribute called `nsamples`." ) ``` -------------------------------- ### Simple Blocking Runner Source: https://adaptive.readthedocs.io/en/latest/_downloads/3f487fe826271204d366200ea9158727/tutorial Demonstrates the use of `adaptive.runner.simple` which blocks until the learning process is complete. It's a straightforward way to run a learner when sequential execution is desired. ```ipython3 import adaptive # Assuming 'learner' and 'f' are defined elsewhere # learner = adaptive.Learner1D(f, bounds=(-1, 1)) # This call blocks until the loss goal is met adaptive.runner.simple(learner, loss_goal=0.01) learner.plot() ``` -------------------------------- ### Plotting Integration Results Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/integrator_learner Generates a HoloViews Path plot of the integrated function based on the evaluated data points. Requires HoloViews to be installed. ```Python defplot(self): hv = ensure_holoviews() ivals = sorted(self.ivals, key=attrgetter("a")) if not self.data: return hv.Path([]) xs, ys = zip(*[(x, y) for ival in ivals for x, y in sorted(ival.data.items())]) return hv.Path((xs, ys)) ``` -------------------------------- ### Get Values as NumPy Array Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/learnerND Retrieves all the values associated with the learner's data points and returns them as a NumPy array of type float. ```Python @property def values(self): """Get the values from `data` as a numpy array.""" return np.array(list(self.data.values()), dtype=float) ``` -------------------------------- ### Get Interpolated Data on a Grid Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/learner2D Generates interpolated data values on a specified grid. The grid density can be automatically determined or manually set. ```Python def interpolated_on_grid(self, n: int | None = None) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """Get the interpolated data on a grid. ... """ ip = self.interpolator(scaled=True) if n is None: n = int(0.658 / sqrt(areas(ip).min())) n = max(n, 10) eps = 1e-13 xs = ys = np.linspace(-0.5 + eps, 0.5 - eps, n) zs = ip(xs[:, None], ys[None, :] * self.aspect_ratio).squeeze() xs, ys = self._unscale(np.vstack([xs, ys]).T).T return xs, ys, zs ``` -------------------------------- ### Using BlockingRunner in a Python Script Source: https://adaptive.readthedocs.io/en/latest/tutorial/tutorial Demonstrates how to use the BlockingRunner for synchronous execution of Adaptive learners from a Python script. It includes setting up a simple learner and initializing the runner. ```Python import adaptive def f(x): return x learner = adaptive.Learner1D(f, (-1, 1)) adaptive.BlockingRunner(learner, loss_goal=0.1) ``` -------------------------------- ### Vertex and Simplex Retrieval Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/triangulation Provides methods to get individual vertices by index and to retrieve a list of vertices corresponding to a given set of indices. ```Python def get_vertices(self, indices): return [self.get_vertex(i) for i in indices] def get_vertex(self, index): if index is None: return None return self.vertices[index] ``` -------------------------------- ### AverageLearner1D: Get Number of Samples Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/average_learner1D Provides the total number of samples collected by the learner. This property aggregates samples across all data points. ```Python @property def nsamples(self) -> int: """Returns the total number of samples""" return sum(self._number_samples.values()) ``` -------------------------------- ### Run Adaptive Learner Task Source: https://adaptive.readthedocs.io/en/latest/_downloads/85bb926f4b795cc0e3af11284c388a6c/tutorial This snippet demonstrates how to await the completion of an adaptive learner's task. This is typically used in non-notebook environments to ensure all computations are finished. ```ipython3 :tags: [hide-cell] await runner.task # This is not needed in a notebook environment! ``` -------------------------------- ### BalancingLearner Strategy Management Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/balancing_learner Allows setting and getting the strategy for point selection, dynamically changing the ask-and-tell mechanism based on the chosen strategy. ```Python @property def strategy(self) -> STRATEGY_TYPE: """Can be either 'loss_improvements' (default), 'loss', 'npoints', or 'cycle'. The points that the `BalancingLearner` choses can be either based on: the best 'loss_improvements', the smallest total 'loss' of the child learners, the number of points per learner, using 'npoints', or by going through all learners one by one using 'cycle'. One can dynamically change the simulation while the simulation is running by changing the ``learner.strategy`` attribute.""" return self._strategy @strategy.setter def strategy(self, strategy: STRATEGY_TYPE) -> None: self._strategy = strategy if strategy == "loss_improvements": self._ask_and_tell = self._ask_and_tell_based_on_loss_improvements elif strategy == "loss": self._ask_and_tell = self._ask_and_tell_based_on_loss elif strategy == "npoints": self._ask_and_tell = self._ask_and_tell_based_on_npoints elif strategy == "cycle": self._ask_and_tell = self._ask_and_tell_based_on_cycle self._cycle = itertools.cycle(range(len(self.learners))) else: raise ValueError( 'Only strategy="loss_improvements", strategy="loss",' ' strategy="npoints", or strategy="cycle" is implemented.' ) ``` -------------------------------- ### Import Adaptive and Define Function Source: https://adaptive.readthedocs.io/en/latest/tutorial/tutorial Imports the adaptive library and sets up the notebook extension. It also defines a mathematical function `f(x)` with an offset, which is used for adaptive learning. ```Python import adaptive adaptive.notebook_extension() import asyncio import random offset = random.uniform(-0.5, 0.5) def f(x, offset=offset): a = 0.01 return x + a**2 / (a**2 + (x - offset) ** 2) ``` -------------------------------- ### Logging and Replaying Runner Operations Source: https://adaptive.readthedocs.io/en/latest/_downloads/3f487fe826271204d366200ea9158727/tutorial Demonstrates how to enable logging for a runner to capture executed learner methods and their arguments. The captured log can then be used with `adaptive.runner.replay_log` to replicate the operations on a new learner instance. ```ipython3 import adaptive import asyncio # Assuming 'f' is defined elsewhere # learner = adaptive.Learner1D(f, bounds=(-1, 1)) # Instantiate runner with logging enabled runner = adaptive.Runner(learner, loss_goal=0.01, log=True) # await runner.task # Not needed in notebook runner.live_info() # Create a new learner # reconstructed_learner = adaptive.Learner1D(f, bounds=learner.bounds) # Replay the logged operations on the new learner # adaptive.runner.replay_log(reconstructed_learner, runner.log) # Compare the plots # learner.plot().Scatter.I.opts(size=6) * reconstructed_learner.plot() ``` -------------------------------- ### Get Dimensionality of Output Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/learner2D Determines the dimensionality (vdim) of the output from the learner's function. Returns 1 if the output is a scalar or if no data is yet available. ```Python @property def vdim(self) -> int: """Length of the output of ``learner.function``. ... """ if self._vdim is None and self.data: try: value = next(iter(self.data.values())) self._vdim = len(value) except TypeError: self._vdim = 1 return self._vdim or 1 ``` -------------------------------- ### Display Live Learner Information Source: https://adaptive.readthedocs.io/en/latest/_downloads/163be7a75fb97ad697e12b3c78d35bb2/tutorial Calls the `live_info()` method on the runner to display real-time information about the learner's progress and status. This is useful for monitoring the learning process. ```ipython3 runner.live_info() ``` -------------------------------- ### Get Simplices Attached to Points Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/triangulation Finds all simplices that are attached to a given set of points (vertices), effectively finding simplices that share at least one vertex. ```python def get_simplices_attached_to_points(self, indices): # Get all simplices that share at least a point with the simplex neighbors = self.get_neighbors_from_vertices(indices) return self.get_face_sharing_neighbors(neighbors, indices) ``` -------------------------------- ### AverageLearner1D: Get Minimum Samples Per Point Source: https://adaptive.readthedocs.io/en/latest/_modules/adaptive/learner/average_learner1D Returns the minimum number of samples recorded for any single data point. If no samples have been collected, it returns 0. ```Python @property def min_samples_per_point(self) -> int: if not self._number_samples: return 0 return min(self._number_samples.values()) ``` -------------------------------- ### Run adaptive learner with DataSaver Source: https://adaptive.readthedocs.io/en/latest/_downloads/b31b3c9f4d671614b0e4eadd418eef41/tutorial This code snippet creates an adaptive.Runner to execute the learner wrapped with DataSaver, setting a loss goal of 0.1. It then awaits the completion of the runner's task. ```ipython3 runner = adaptive.Runner(learner, loss_goal=0.1) await runner.task # This is not needed in a notebook environment! ```