### Development Installation Source: https://github.com/python-adaptive/adaptive/blob/main/README.md Guides on cloning the repository and installing the adaptive library in development mode with optional dependencies for notebook, testing, and other features. ```Bash git clone git@github.com:python-adaptive/adaptive.git cd adaptive pip install -e ".[notebook,test,other]" ``` -------------------------------- ### Setup Adaptive Environment Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.IntegratorLearner.md Imports necessary libraries (adaptive, holoviews, numpy) and sets up the adaptive notebook extension. ```ipython3 import adaptive adaptive.notebook_extension() import holoviews as hv import numpy as np ``` -------------------------------- ### Installing Pre-commit Hooks Source: https://github.com/python-adaptive/adaptive/blob/main/README.md Instructions for installing pre-commit to maintain consistent code style within the repository. ```Bash pre-commit install ``` -------------------------------- ### Setup Adaptive Environment Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.SequenceLearner.md Initializes the adaptive notebook extension and imports necessary libraries like holoviews and numpy for plotting and numerical operations. ```ipython3 import adaptive adaptive.notebook_extension() import holoviews as hv import numpy as np ``` -------------------------------- ### Installing JupyterLab Extensions Source: https://github.com/python-adaptive/adaptive/blob/main/README.md Instructions for installing necessary JupyterLab extensions to use Adaptive within JupyterLab. ```Bash jupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter labextension install @pyviz/jupyterlab_pyviz ``` -------------------------------- ### Setup Adaptive Notebook Extension Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.AverageLearner.md Imports the adaptive library and enables the notebook extension for interactive use. This is typically hidden in final documentation. ```ipython3 import adaptive adaptive.notebook_extension() ``` -------------------------------- ### Setup and Helper Function Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.LearnerND.md Imports necessary libraries (adaptive, holoviews, numpy) and defines a helper function to convert HoloViews DynamicMaps to HoloMaps for static display. ```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)) ``` -------------------------------- ### Installing Adaptive with Pip Source: https://github.com/python-adaptive/adaptive/blob/main/README.md Provides instructions for installing the adaptive library using pip, including optional dependencies for Jupyter notebook support. ```Bash pip install "adaptive[notebook]" ``` -------------------------------- ### Adaptive Learner Setup and Animation Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/logo.md Functions for setting up an adaptive simulation and creating animations. `create_and_run_learner` defines and runs a 2D adaptive learner with a 'ring' function. `get_figure` creates a matplotlib figure with specific styling. `setup` orchestrates the learner creation, data collection, and figure preparation for animation. ```python def create_and_run_learner(): def ring(xy): import numpy as np x, y = xy a = 0.2 return x + np.exp(-((x**2 + y**2 - 0.75**2) ** 2) / a**4) learner = adaptive.Learner2D(ring, bounds=[(-1, 1), (-1, 1)]) adaptive.runner.simple(learner, loss_goal=0.005) return learner def get_figure(): fig, ax = plt.subplots(figsize=(5, 5)) fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None) ax.set_xticks([]) ax.set_yticks([]) ax.spines["top"].set_visible(False) ax.spines["right"].set_visible(False) ax.spines["bottom"].set_visible(False) ax.spines["left"].set_visible(False) return fig, ax def setup(nseconds=15): learner = create_and_run_learner() data = list(learner.data.items()) fig, ax = get_figure() npoints = (len(data) * np.linspace(0, 1, 24 * nseconds) ** 2).astype(int) rounded_corners = add_rounded_corners(size=(1000, 1000), rad=300) return npoints, learner, data, rounded_corners, fig, ax ``` -------------------------------- ### Installing Adaptive with Conda Source: https://github.com/python-adaptive/adaptive/blob/main/README.md Provides instructions for installing the adaptive library using the conda package manager, including optional dependencies for Jupyter notebook support. ```Bash conda install -c conda-forge adaptive ``` -------------------------------- ### Setup Adaptive Notebook Extension Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.Learner2D.md Imports necessary libraries (functools, holoviews, numpy) and enables the adaptive notebook extension. This is a prerequisite for using adaptive in a Jupyter environment. ```ipython3 from functools import partial import holoviews as hv import numpy as np import adaptive adaptive.notebook_extension() ``` -------------------------------- ### Adaptive Learner and AsyncRunner Setup Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.advanced-topics.md Initializes an adaptive Learner1D with the `f_parallel` function and sets up an AsyncRunner to manage the adaptive evaluation process with a specified loss goal and number of tasks. ```python import adaptive learner = adaptive.Learner1D(f_parallel, bounds=(-3.5, 3.5)) runner = adaptive.AsyncRunner(learner, loss_goal=0.01, ntasks=20) ``` -------------------------------- ### Retrieve and Print Learner Results Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.SequenceLearner.md Demonstrates how to get the results from the learner using `learner.result()` and prints the first 10 values to show the computed outputs. ```ipython3 result = learner.result() print(result[:10]) # print the 10 first values ``` -------------------------------- ### Example Function for Parallelization Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.advanced-topics.md Defines an example function `f(x)` composed of a slow, reusable part `g(x)` and a fast part `h(x)`. This setup is used to illustrate custom parallelization. ```python def f(x): # example function without caching """ Integer part of `x` repeats and should be reused Decimal part requires a new computation """ return g(int(x)) + h(x % 1) def g(x): """Slow but reusable function""" from time import sleep sleep(random.randrange(5)) return x**2 def h(x): """Fast function""" return x**3 ``` -------------------------------- ### Adaptive Function Evaluation Example Source: https://github.com/python-adaptive/adaptive/blob/main/README.md This example demonstrates how to use the Adaptive library for parallel active learning of a mathematical function. It shows the basic setup for defining a function, its bounds, and initiating the adaptive sampling process. The library intelligently selects points for evaluation, optimizing the process. ```Python from adaptive.learner import Learner1D from adaptive.runner import Runner def f(x): # Example function: sin(x) * x return math.sin(x) * x learner = Learner1D(f, bounds=(-5, 5)) runner = Runner(learner, ntasks=4) runner.start() # To stop the runner: # runner.stop() # To get the data: # data = learner.data() ``` -------------------------------- ### Start New Development Branch Tag Source: https://github.com/python-adaptive/adaptive/blob/main/RELEASE.md Creates an empty commit and tags it to mark the start of development for the next version. This ensures that subsequent commits are correctly versioned as development versions. ```bash git commit --allow-empty -m 'start development towards v' git tag -am 'Start development towards v' v-dev ``` -------------------------------- ### Adaptive Learner1D Example Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/algorithms_and_examples.md Demonstrates how to use Learner1D for adaptively learning a 1D function. It includes setting up the learner, defining a goal for the sampling process, and running the sampling with live status and plotting. ```python from adaptive import notebook_extension, 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() ``` -------------------------------- ### 1D Adaptive Sampling Benchmarks Setup Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/benchmarks.md Sets up the environment for 1D adaptive sampling benchmarks. Includes imports for necessary libraries like holoviews, numpy, pandas, scipy, and adaptive. Defines helper functions for creating homogeneous learners, plotting, calculating errors, running benchmarks, and converting results to DataFrames. ```python 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://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.BalancingLearner.md Imports necessary libraries and initializes the adaptive notebook extension for interactive use. This includes adaptive, random, functools.partial, holoviews, and numpy. ```ipython3 import adaptive adaptive.notebook_extension() import random from functools import partial import holoviews as hv import numpy as np ``` -------------------------------- ### Initialize Notebook Extension and Imports Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.AverageLearner1D.md Initializes the adaptive notebook extension and imports necessary libraries like functools, holoviews, and numpy for the tutorial. ```ipython3 import adaptive adaptive.notebook_extension() from functools import partial import holoviews as hv import numpy as np ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.Learner1D.md Imports necessary libraries and initializes the adaptive notebook extension for interactive plotting and data handling. ```ipython3 import adaptive adaptive.notebook_extension() import random from functools import partial import numpy as np ``` -------------------------------- ### Initialize and Run IntegratorLearner Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.IntegratorLearner.md Initializes an `IntegratorLearner` with the function `f24`, specified bounds, and tolerance. It then sets up a `Runner` with a `SequentialExecutor` to manage the learning process. ```python 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()) ``` -------------------------------- ### Live Plotting of Adaptive Sampling Source: https://github.com/python-adaptive/adaptive/blob/main/example-notebook.ipynb Starts live plotting for the adaptive sampling process, visualizing the estimated mean value and its errorbars as samples are collected. ```Python runner.live_plot(update_interval=1) ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.custom_loss.md Imports necessary libraries and initializes the adaptive notebook extension for interactive plotting and data visualization. ```ipython3 import adaptive adaptive.notebook_extension() # Import modules that are used in multiple cells import holoviews as hv import numpy as np ``` -------------------------------- ### Exporting Learned Data Source: https://github.com/python-adaptive/adaptive/blob/main/README.md Shows how to export the learned data from an adaptive learner. The data can be exported as a NumPy array or, if Pandas is installed, as a DataFrame. ```Python data = learner.to_numpy() ``` ```Python df = learner.to_dataframe() ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://github.com/python-adaptive/adaptive/blob/main/example-notebook.ipynb Imports necessary libraries and initializes the adaptive notebook extension for interactive use within Jupyter notebooks. ```Python import random from functools import partial import holoviews as hv import numpy as np import adaptive adaptive.notebook_extension() ``` -------------------------------- ### DataSaver and Runner Initialization Source: https://github.com/python-adaptive/adaptive/blob/main/example-notebook.ipynb Demonstrates wrapping a learner with DataSaver to save data and initializing a Runner to manage the learning process. It also shows how to access the original learner and its methods. ```Python from operator import itemgetter import adaptive # Wrapping the learner with 'adaptive.DataSaver' and tell it which key it needs to learn learner = adaptive.DataSaver(_learner, arg_picker=itemgetter("y")) # `learner.learner` is the original learner, so `learner.learner.loss()` will call the correct loss method. runner = adaptive.Runner(learner, loss_goal=0.05) runner.live_info() runner.live_plot(plotter=lambda lrn: lrn.learner.plot(), update_interval=0.1) # Now the `DataSavingLearner` will have an dictionary attribute `extra_data` that has `x` as key and the data that was returned by `learner.function` as values. print(learner.extra_data) ``` -------------------------------- ### Live Plotting for Vector Output Function Source: https://github.com/python-adaptive/adaptive/blob/main/example-notebook.ipynb Starts live plotting for the adaptive learning process of the vector output function. This visualizes how the learner approximates the multi-dimensional output. ```Python runner.live_plot(update_interval=0.3) ``` -------------------------------- ### ND Learner with Convex Hull Domain Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.LearnerND.md Demonstrates using a scipy.spatial.ConvexHull as the domain for LearnerND. This example uses a custom-defined shape (a cube split diagonally) to sample a function. ```python import scipy def f(xyz): x, y, z = xyz return x**4 + y**4 + z**4 - (x**2 + y**2 + z**2) ** 2 # set the bound points, you can change this to be any shape b = [(-1, -1, -1), (-1, 1, -1), (-1, -1, 1), (-1, 1, 1), (1, 1, -1), (1, -1, -1)] # you have to convert the points into a scipy.spatial.ConvexHull hull = scipy.spatial.ConvexHull(b) learner = adaptive.LearnerND(f, hull) adaptive.BlockingRunner(learner, npoints_goal=2000) learner.plot_isosurface(-0.5) ``` -------------------------------- ### Using adaptive.runner.simple Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.advanced-topics.md Demonstrates the use of `adaptive.runner.simple` which blocks until completion. It also shows how to plot the learner's progress. ```python import adaptive def f(x): return x**2 learner = adaptive.Learner1D(f, bounds=(-1, 1)) adaptive.runner.simple(learner, loss_goal=0.01) learner.plot() ``` -------------------------------- ### Display Live Info Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.LearnerND.md Displays live information about the learner and runner. ```ipython3 runner.live_info() ``` -------------------------------- ### MP4 Animation Generation Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/logo.md Generates an MP4 animation from the adaptive simulation. It uses `setup` to prepare the simulation environment and `get_new_artists` to render each frame. The animation is saved using `FFMpegWriter`. ```python def animate_mp4(fname="source/_static/logo_docs.mp4", nseconds=15): npoints, learner, data, rounded_corners, fig, ax = setup() artists = [ get_new_artists(n, learner, data, rounded_corners, ax) for n in tqdm(npoints) ] ani = animation.ArtistAnimation(fig, artists, blit=True) ani.save(fname, writer=FFMpegWriter(fps=24)) ``` -------------------------------- ### Initialize SequenceLearner Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.SequenceLearner.md Creates a SequenceLearner instance with a function `f(x) = x^2` and a sequence of numbers from -15 to 15. A Runner is initialized 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()` ``` -------------------------------- ### Get Commits Since Last Tag Source: https://github.com/python-adaptive/adaptive/blob/main/RELEASE.md This command retrieves the number of commits made by each author since the last annotated tag, helping to verify the AUTHORS.md file. ```bash t=$(git describe --abbrev=0); echo Commits since $t; git shortlog -s $t.. ``` -------------------------------- ### Create Balancing Learner from Parameter Product Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.BalancingLearner.md Demonstrates the use of `BalancingLearner.from_product` to create learners for a Cartesian product of parameters. It defines a `jacobi` function using `scipy.special.eval_jacobi` and specifies parameter combinations for 'n', 'alpha', and 'beta'. A `BalancingLearner` is created with `Learner1D` instances for these combinations, and a `BlockingRunner` is initialized. ```python from scipy.special import eval_jacobi def jacobi(x, n, alpha, beta): return eval_jacobi(n, alpha, beta, x) combos = { "n": [1, 2, 4, 8], "alpha": np.linspace(0, 2, 3), "beta": np.linspace(0, 1, 5), } learner = adaptive.BalancingLearner.from_product( jacobi, adaptive.Learner1D, {"bounds": (0, 1)}, combos ) runner = adaptive.BlockingRunner(learner, loss_goal=0.01) ``` -------------------------------- ### Balancing Learner with Learner1D Source: https://github.com/python-adaptive/adaptive/blob/main/example-notebook.ipynb Implements a meta-learner that queries multiple child learners to determine which one offers the most improvement. This example uses Learner1D instances to demonstrate the balancing learner's capability. ```python 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) runner.live_info() ``` -------------------------------- ### Setting up Git Filter Source: https://github.com/python-adaptive/adaptive/blob/main/README.md Instructions for setting up a git filter to prevent notebook output from polluting the commit history. ```Bash python ipynb_filter.py ``` -------------------------------- ### DataSaver with Dictionary Return Source: https://github.com/python-adaptive/adaptive/blob/main/example-notebook.ipynb Shows how to use `adaptive.DataSaver` to store results from a function that returns metadata along with the primary output. This example uses a function that returns a dictionary containing the result and execution time. ```python from operator import itemgetter def f_dict(x): """The function evaluation takes roughly the time we `sleep`.""" import random from time import sleep waiting_time = random.random() sleep(waiting_time) a = 0.01 y = x + a**2 / (a**2 + x**2) return {"y": y, "waiting_time": waiting_time} # Create the learner with the function that returns a 'dict' # This learner cannot be run directly, as Learner1D does not know what to do with the 'dict' _learner = adaptive.Learner1D(f_dict, bounds=(-1, 1)) ``` -------------------------------- ### Sinusoidal Function Approximation Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/benchmarks.md Approximates a sinusoidal function using adaptive sampling. This example shows that adaptive sampling may not offer significant advantages over uniform sampling for smoother functions like the sinusoid. ```python import numpy as np import adaptive def sinusoidal(x, amplitude=1, frequency=1, phase=0): return amplitude * np.sin(frequency * x + phase) learner = adaptive.Learner1D(sinusoidal, bounds=(-2 * np.pi, 2 * np.pi)) run_and_plot(learner, loss_goal=0.1) ``` -------------------------------- ### Create and Run Balancing Learner Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.BalancingLearner.md Defines a function `h(x)` and creates a list of 10 `Learner1D` instances with randomized offsets. These learners are then passed to `BalancingLearner`, and a `Runner` is initialized with a loss goal of 0.01 to manage the execution of the balancing learner. ```python 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) ``` -------------------------------- ### Initialize and Run Adaptive Learner Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.AverageLearner1D.md Initializes an `adaptive.Runner` with the learner and the defined goal. It then awaits the completion of the runner's task. ```ipython3 runner = adaptive.Runner(learner, goal=goal(10_000)) await runner.task # This is not needed in a notebook environment! ``` -------------------------------- ### Adaptive Sampling of Noisy Function Source: https://github.com/python-adaptive/adaptive/blob/main/example-notebook.ipynb Demonstrates adaptive sampling of a noisy 1D function using `AverageLearner1D`. It sets up a learner, defines a goal for the runner, and starts the runner to collect samples and estimate the mean value. ```Python learner = adaptive.AverageLearner1D(partial(noisy_peak, sigma=1), bounds=(-2, 2)) def goal(lrn): return lrn.nsamples >= 10_000 and lrn.min_samples_per_point >= 20 runner = adaptive.Runner(learner, goal=goal) runner.live_info() ``` -------------------------------- ### Getting Learner2D Data on a Grid Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/faq.md To obtain data from a `Learner2D` object on a grid, use the `interpolated_on_grid()` method. An optional `n` argument can specify the number of points along the x and y axes. ```python Use learner.interpolated_on_grid() optionally with a argument `n` to specify the the amount of points in `x` and `y`. ``` -------------------------------- ### ND Learner Initialization Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.LearnerND.md Initializes a LearnerND for a 3D sphere function with bounds and sets up a Runner to achieve a loss goal. ```python def sphere(xyz): x, y, z = xyz a = 0.4 return x + z**2 + np.exp(-((x**2 + y**2 + z**2 - 0.75**2) ** 2) / a**4) learner = adaptive.LearnerND(sphere, bounds=[(-1, 1), (-1, 1), (-1, 1)]) runner = adaptive.Runner(learner, loss_goal=1e-3) ``` -------------------------------- ### Running Adaptive with MPIPoolExecutor Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.parallelism.md Provides a script and execution commands for running adaptive learners non-interactively on a cluster using mpi4py.futures.MPIPoolExecutor. It includes examples for setting max workers and running via mpiexec, including a SLURM job script. ```python from mpi4py.futures import MPIPoolExecutor # use the idiom below, see the warning at # https://mpi4py.readthedocs.io/en/stable/mpi4py.futures.html#mpipoolexecutor if __name__ == "__main__": learner = adaptive.Learner1D(f, bounds=(-1, 1)) # load the data learner.load(fname) # run until `goal` is reached with an `MPIPoolExecutor` runner = adaptive.Runner( learner, executor=MPIPoolExecutor(), shutdown_executor=True, loss_goal=0.01, ) # periodically save the data (in case the job dies) runner.start_periodic_saving(dict(fname=fname), interval=600) # block until runner goal reached runner.block_until_done() # save one final time before exiting learner.save(fname) ``` ```bash export MPI4PY_MAX_WORKERS=15 mpiexec -n 1 python run_learner.py ``` ```bash mpiexec -n 16 python -m mpi4py.futures run_learner.py ``` ```bash #!/bin/bash #SBATCH --job-name adaptive-example #SBATCH --ntasks 100 srun -n $SLURM_NTASKS --mpi=pmi2 ~/miniconda3/envs/py37_min/bin/python -m mpi4py.futures run_learner.py ``` -------------------------------- ### Define function returning dictionary and save data with adaptive.DataSaver Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.DataSaver.md This example defines a function `f_dict` that returns a dictionary containing the result 'y' and 'waiting_time'. It then wraps a Learner1D with adaptive.DataSaver, specifying 'y' as the key to learn using itemgetter. This allows the learner to process the dictionary output and save the associated data. ```python from operator import itemgetter def f_dict(x): """The function evaluation takes roughly the time we `sleep`.""" import random from time import sleep waiting_time = random.random() sleep(waiting_time) a = 0.01 y = x + a**2 / (a**2 + x**2) return {"y": y, "waiting_time": waiting_time} # Create the learner with the function that returns a 'dict' # This learner cannot be run directly, as Learner1D does not know what to do with the 'dict' _learner = adaptive.Learner1D(f_dict, bounds=(-1, 1)) # Wrapping the learner with 'adaptive.DataSaver' and tell it which key it needs to learn learner = adaptive.DataSaver(_learner, arg_picker=itemgetter("y")) ``` -------------------------------- ### Display Live Learner Information Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.SequenceLearner.md Uses the `live_info()` method of the runner to display real-time information about the learner's progress and status. ```ipython3 runner.live_info() ``` -------------------------------- ### Saving and Loading Learner Data with Pickle Source: https://github.com/python-adaptive/adaptive/blob/main/example-notebook.ipynb Explains and demonstrates how to save and load the data of an adaptive learner using pickle files. It covers naming files using `fname` argument or attribute, and disabling compression. ```Python import adaptive from functools import partial # Let's create two learners and run only one. learner = adaptive.Learner1D(partial(peak, wait=False), bounds=(-1, 1)) control = adaptive.Learner1D(partial(peak, wait=False), bounds=(-1, 1)) # Let's only run the learner runner = adaptive.Runner(learner, loss_goal=0.01) runner.live_info() fname = "data/example_file.p" learner.save(fname) control.load(fname) # Plotting saved and loaded learners learner.plot().relabel("saved learner") + control.plot().relabel("loaded learner") # Alternative: Copying data without saving control_copy = adaptive.Learner1D(partial(peak, wait=False), bounds=(-1, 1)) control_copy.copy_from(learner) ``` -------------------------------- ### Initialize and Run AverageLearner Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.AverageLearner.md Initializes an `AverageLearner` with the defined function `g` and sets a loss goal. A `Runner` is created to manage the learner's execution until the 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) ``` -------------------------------- ### Initialize Adaptive Notebook Extension Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/algorithms_and_examples.md Initializes the adaptive library for use within Jupyter notebooks, enabling interactive features and visualizations. It also sets up HoloViews for output. ```ipython3 import itertools import holoviews as hv import numpy as np import adaptive from adaptive.learner.learner1D import default_loss, uniform_loss adaptive.notebook_extension() hv.output(holomap="scrubber") ``` -------------------------------- ### Run Adaptive Sampling and Monitor Progress Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.Learner1D.md Shows how to run an adaptive sampling task and monitor its progress. The `runner.task` is awaited for completion, and `runner.live_info()` provides real-time updates. ```ipython3 :tags: [hide-cell] await runner.task # This is not needed in a notebook environment! ``` ```ipython3 runner.live_info() ``` ```ipython3 runner.live_plot(update_interval=0.1) ``` -------------------------------- ### Initialize adaptive notebook extension Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.advanced-topics.md Initializes the adaptive notebook extension for interactive use within Jupyter environments. This is often a prerequisite for using adaptive's visualization and interactive features. ```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 Runner for Adaptive Sampling Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.Learner1D.md Creates an adaptive.Runner to manage the sampling process, targeting a loss goal of 0.01. It handles parallel execution using ProcessPoolExecutor or loky. ```ipython3 # The end condition is when the "loss" is less than 0.01. In the context of the # 1D learner this means that we will resolve features in 'func' with width 0.01 or wider. runner = adaptive.Runner(learner, loss_goal=0.01) ``` -------------------------------- ### Initialize adaptive notebook extension Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.DataSaver.md This code snippet initializes the adaptive notebook extension, which is necessary for using adaptive functionalities within a Jupyter notebook environment. ```ipython3 import adaptive adaptive.notebook_extension() ``` -------------------------------- ### Initialize and Run 1D Learner Source: https://github.com/python-adaptive/adaptive/blob/main/example-notebook.ipynb Initializes a 1D learner for the 'peak' function within specified bounds and sets up a runner to evaluate points adaptively until a loss goal is met. Includes live information display. ```Python learner = adaptive.Learner1D(peak, bounds=(-1, 1)) # The end condition is when the "loss" is less than 0.01. In the context of the # 1D learner this means that we will resolve features in 'func' with width 0.01 or wider. runner = adaptive.Runner(learner, loss_goal=0.01) runner.live_info() ``` -------------------------------- ### Upload to PyPI Source: https://github.com/python-adaptive/adaptive/blob/main/RELEASE.md Uploads the built distribution files (tarball and wheels) to the Python Package Index (PyPI) using the 'twine' tool. ```bash twine upload dist/* ``` -------------------------------- ### Run Adaptive Learner Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.Learner2D.md Initializes an adaptive.Runner with the Learner2D object and sets a loss goal. The runner manages the adaptive sampling process. ```ipython3 runner = adaptive.Runner(learner, loss_goal=0.01) ``` -------------------------------- ### Run ASV Benchmarks Source: https://github.com/python-adaptive/adaptive/blob/main/benchmarks/README.md Commands to execute Airspeed Velocity benchmarks for the adaptive library. This includes running the benchmarks, skipping existing commits, setting the number of steps, and publishing the results. ```bash cd benchmarks asv run --skip-existing-commits --steps 10 ALL asv publish asv preview ``` -------------------------------- ### Run and Monitor Learner Task Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.SequenceLearner.md This snippet shows how to await the completion of the runner's task. Note that this is typically not needed in a notebook environment where execution is managed differently. ```ipython3 await runner.task # This is not needed in a notebook environment! ``` -------------------------------- ### Using ipyparallel.Client with Adaptive Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.parallelism.md Shows how to integrate ipyparallel.Client for distributed computing with the adaptive library. Requires an ipcluster to be running. ```python import ipyparallel client = ipyparallel.Client() # You will need to start an `ipcluster` to make this work learner = adaptive.Learner1D(f, bounds=(-1, 1)) runner = adaptive.Runner(learner, executor=client, loss_goal=0.01) runner.live_info() runner.live_plot() ``` -------------------------------- ### Initialize Learner1D with Curvature Loss Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.Learner1D.md Demonstrates initializing a Learner1D with a custom curvature loss function for adaptive sampling. It sets up the learner and a runner to achieve a specific loss goal. ```ipython3 from adaptive.learner.learner1D import ( curvature_loss_function, default_loss, uniform_loss, ) curvature_loss = curvature_loss_function() learner = adaptive.Learner1D(f, bounds=(-1, 1), loss_per_interval=curvature_loss) runner = adaptive.Runner(learner, loss_goal=0.01) ``` -------------------------------- ### Push Tags to Origin Source: https://github.com/python-adaptive/adaptive/blob/main/RELEASE.md Pushes the newly created release and development tags to the remote repository. ```bash git push origin v v-dev ``` -------------------------------- ### Display Live Runner Information for Vector Output Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.Learner1D.md Displays live information during the adaptive sampling of a vector output function. ```ipython3 runner.live_info() ``` -------------------------------- ### Visualize Parameter Product Learner Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.BalancingLearner.md Visualizes the `BalancingLearner` created from the parameter product. The `plot()` method is called, and the output is overlaid by 'beta' and gridded, with the y-axis range selected between -1 and 3. This visualization helps in understanding how the learners perform across different parameter combinations. ```python # The `cdims` will automatically be set when using `from_product`, so # `plot()` will return a HoloMap with correctly labeled sliders. learner.plot().overlay("beta").grid().select(y=(-1, 3)) ``` -------------------------------- ### Display Live Information Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.BalancingLearner.md Calls the `live_info()` method on the runner object to display real-time information about the learning process. This is useful for monitoring the progress and status of the adaptive learning. ```python runner.live_info() ``` -------------------------------- ### Initialize and Run Averaging Learner Source: https://github.com/python-adaptive/adaptive/blob/main/example-notebook.ipynb Initializes an AverageLearner for the function 'g' with relative tolerance and sets up a runner to achieve a loss goal of 2.0. ```Python learner = adaptive.AverageLearner(g, atol=None, rtol=0.01) runner = adaptive.Runner(learner, loss_goal=2.0) runner.live_info() ``` -------------------------------- ### Display Live Runner Information Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.Learner1D.md Displays live information about the adaptive runner, such as the number of points evaluated and the current loss. ```ipython3 runner.live_info() ``` -------------------------------- ### Compare Sampling Strategies for sin(15x) * exp(-2x^2) Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.Learner1D.md Compares three sampling strategies (homogeneous, euclidean loss, curvature loss) for the function sin(15x) * exp(-2x^2) by sampling 100 points. It uses a simple, non-parallel runner and plots the results. ```ipython3 def sin_exp(x): from math import exp, sin return sin(15 * x) * exp(-(x**2) * 2) learner_h = adaptive.Learner1D(sin_exp, (-1, 1), loss_per_interval=uniform_loss) learner_1 = adaptive.Learner1D(sin_exp, (-1, 1), loss_per_interval=default_loss) learner_2 = adaptive.Learner1D(sin_exp, (-1, 1), loss_per_interval=curvature_loss) # adaptive.runner.simple is a non parallel blocking runner. adaptive.runner.simple(learner_h, npoints_goal=100) adaptive.runner.simple(learner_1, npoints_goal=100) adaptive.runner.simple(learner_2, npoints_goal=100) ( learner_h.plot().relabel("homogeneous") + learner_1.plot().relabel("euclidean loss") + learner_2.plot().relabel("curvature loss") ).cols(2) ``` -------------------------------- ### Initialize and Run 2D Learner Source: https://github.com/python-adaptive/adaptive/blob/main/example-notebook.ipynb Initializes a 2D learner for the 'ring' function within specified 2D bounds and sets up a runner for adaptive evaluation. ```Python learner = adaptive.Learner2D(ring, bounds=[(-1, 1), (-1, 1)]) runner = adaptive.Runner(learner, loss_goal=0.01) runner.live_info() ``` -------------------------------- ### Compare with SciPy Integrator Source: https://github.com/python-adaptive/adaptive/blob/main/docs/source/tutorial/tutorial.IntegratorLearner.md Uses `scipy.integrate.quad` to integrate the defined function `f24` and demonstrates potential warnings due to the function's complexity. ```python import scipy.integrate scipy.integrate.quad(f24, 0, 3) ```