Solvers#
adaptive_quadrature returns one of these two classes; both take the same
keyword-only options, listed under the uniform solver. Build a solver once and
call its integrate method repeatedly, for example in a training loop, to warm
start each call from the last one’s mesh (Warm starts with same_f).
- class padaquad.UniformAdaptiveQuadrature(*, f=None, method=None, atol=1e-05, rtol=1e-05, mesh_init=None, mesh_final=None, y0=None, remove_cut=0.1, merge_rule='predicted', max_batch=None, total_mem_usage=0.9, limit_benchmark_time=True, max_adaptive_splits=None, use_absolute_error_ratio=True, error_norm='2', mesh_failure_tolerance=0.0, error_on_nonfinite=True, dtype=torch.float64, device=None, output_speed_info=False, **distributed_options)#
Adaptive quadrature solver for methods with fixed node fractions and weights.
The nodes of every subinterval sit at the method’s fixed node fractions, so the weights are fixed numbers. For example, dopri5 always evaluates the integrand at the fractions
[0, 1/5, 3/10, 4/5, 8/9, 1, 1]of each subinterval’s width. When a subinterval fails the tolerance, it is split in half and the integrand is evaluated at fresh nodes in both halves.The method is one of
UNIFORM_METHODS: the Runge-Kutta, Gauss-Kronrod and Clenshaw-Curtis methods, withgk21the default. The constructor takes the options ofAdaptiveQuadrature, all as keyword arguments.Examples
Integrate
cos(t)from 0 to 1; the exact value issin(1):>>> import torch >>> from padaquad import UniformAdaptiveQuadrature >>> _ = torch.manual_seed(0) >>> solver = UniformAdaptiveQuadrature( ... method="gk21", atol=1e-10, rtol=1e-10, device="cpu", max_batch=10_000 ... ) >>> result = solver.integrate( ... torch.cos, ... mesh_init=torch.tensor([0.0], dtype=torch.float64), ... mesh_final=torch.tensor([1.0], dtype=torch.float64), ... ) >>> print(round(float(result.integral), 6)) 0.841471
Create a solver and store the defaults that
integratefalls back on.Every argument is keyword-only.
- Parameters:
- fCallable or None
The integrand, used by
integratecalls that pass none. It takes points of shape [N, T] and returns values of shape [N, D] (see the user guide). Default None.- methodstr or None
Name of the quadrature method, a key of
UNIFORM_METHODS(uniform solver) orVARIABLE_METHODS(variable solver); case does not matter. None (default) means"gk21"(uniform) or"interpolatory3_variable"(variable).- atolfloat
Absolute tolerance. A subinterval is accepted when its error estimate is below
max(atol, rtol * |I|), withIthe integral (see the user guide). Default 1e-5.- rtolfloat
Relative tolerance; see
atol. Default 1e-5.- mesh_inittorch.Tensor or None
Default lower integration bound, shape [T]. None means 0.
- mesh_finaltorch.Tensor or None
Default upper integration bound, shape [T]. None means 1.
- y0torch.Tensor or None
Default value added to the returned integral, shape [D]. None means 0.
- remove_cutfloat
Largest predicted error ratio of a subinterval made by merging two neighbors when the optimal mesh is built; must be below 1. Lower values merge less. Default 0.1 (see the user guide).
- merge_rulestr
How the merged subinterval’s error is predicted when the optimal mesh is built (see the user guide):
"predicted"(default): computed from the integrand values already stored for the two neighbors, by interpolating them onto the merged subinterval’s nodes. Use this one."power_law": the neighbors’ summed error times2**(error_exponent - 1), the merge rule of padaquad 1.3.0 and 1.4.0. It assumes the error shrinks like a power of the width and refuses many safe merges on wide subintervals."sum": the neighbors’ summed error, the merge rule of padaquad 1.2.2. Merged subintervals often fail when evaluated again.
The older two are kept to reproduce meshes of earlier versions.
- max_batchint or None
Default for the largest number of integrand evaluations per call of
f. None (default) sets the batch size from the free memory, measured by a memory benchmark (see the user guide).- total_mem_usagefloat
Fraction of the device’s total memory, in (0, 1], that batches may fill: the batch size leaves
(1 - total_mem_usage)of it free. Used only when nomax_batchis set. Default 0.9.- limit_benchmark_timebool
If True (default), the memory benchmark raises
RuntimeErrorwhen it cannot measure the memory offwithin 60 s; False removes the limit, for anfso slow that the measurement needs longer (see the user guide).- max_adaptive_splitsint or None
Default cap on how many times a subinterval may have been halved since the starting mesh; at the cap it is accepted even if it fails the tolerance. None (default) means no cap (see the user guide).
- use_absolute_error_ratiobool
If True (default), the relative tolerance uses the whole integral; if False, the running integral from
mesh_initthrough each subinterval (see the user guide).- error_normstr or Callable
How the error of a vector-valued integrand becomes one accept-or-split decision:
"2"(default),"max","rms","failure_fraction"or a callable norm (see the user guide).- mesh_failure_tolerancefloat
With
error_norm="failure_fraction", the fraction of output components, in [0, 1], that may fail while a subinterval is still accepted. Default 0.0 (every component must pass).- error_on_nonfinitebool
If True (default), raise
ValueErrornaming the points wherefreturned NaN or Inf. If False, accept those subintervals and let the non-finite value reach the result.- dtypetorch.dtype
torch.float64(default) ortorch.float32;torch.float16is refused.integrateswitches to the dtype of the mesh or the bounds it is given.- devicestr, torch.device or None
"cpu","cuda","cuda:N"or atorch.device. None (default) picks CUDA if it is available, else the CPU.- output_speed_infobool
If True, log the time of each stage of the loop to the file
padaquad_speed.log. Default False.- **distributed_optionsAny
Options for multi-process (multi-GPU) runs only.
- Raises:
- TypeError
If an argument is passed by position, or a keyword is not an option of the solver.
- ValueError
If
remove_cutis not below 1,merge_ruleis not one of"predicted","power_law"and"sum", or another option is invalid.
- integrate(f=None, y0=None, mesh=None, mesh_init=None, mesh_final=None, same_f=False, random_initial_mesh=True, N_init_steps=13, f_args=(), take_gradient=True, total_mem_usage=None, loss_fxn=None, max_batch=None, max_adaptive_splits=None, error_norm=None, error_integral_reference=None, mesh_failure_tolerance=None, error_on_nonfinite=None, conserve_memory=False, result_device='cpu')#
Integrate f over [mesh_init, mesh_final] with adaptive subintervals.
The integrand is called as
f(t, *f_args)with pointstof shape [N, T] and must return values of shape [N, D], or a 2-tuple of those values and the tracked variables (The integrand contract, Tracked variables). The loop evaluates many subintervals in one batch, accepts those whose error ratio is below 1 and splits the others in half, until every subinterval is accepted. It then builds the optimal mesh, which a later call withsame_f=Truestarts from.Every argument left as None falls back to the constructor’s value.
- Parameters:
- fCallable or None
The integrand. None uses the integrand given to the constructor.
- y0torch.Tensor or None
Value added to the returned integral, shape [D]. None uses the constructor’s
y0(0 by default).- meshtorch.Tensor or None
Starting mesh, shape [M, T], increasing; its first and last points are the integration bounds. None builds a fresh starting mesh (see the user guide). Replaced by the stored mesh under
same_f.- mesh_inittorch.Tensor or None
Lower integration bound, shape [T]. If
meshis given, it must equal the mesh’s first point. None usesmesh[0]or the constructor’s value.- mesh_finaltorch.Tensor or None
Upper integration bound, shape [T]. If
meshis given, it must equal the mesh’s last point. None usesmesh[-1]or the constructor’s value.- same_fbool
True when f is the same integrand as in the previous call, or changed only slightly: start from the stored mesh and
max_batchand skip the memory benchmark. Default False (see the user guide).- random_initial_meshbool
If True (default), the points of a fresh starting mesh are placed at random, so the mesh does not line up with evenly spaced features of f; if False, they are evenly spaced (see the user guide).
- N_init_stepsint
Approximate number of subintervals of a fresh starting mesh. The default 13 gives 11 subintervals (see the user guide).
- f_argstuple
Extra positional arguments passed to f; tensors are moved to the solver’s device. Default
().- take_gradientbool
If True (default), backpropagate each batch’s loss right after it, so the whole autograd graph is never held; if False, keep the graph so the returned integral can be differentiated (see the user guide).
- total_mem_usagefloat or None
Fraction of the device’s total memory, in (0, 1], that batches may fill. Used only when no
max_batchis set (see the user guide).- loss_fxnCallable or None
Maps one batch’s
IntegrationResultto a scalar loss, whichtake_gradient=Truebackpropagates;result.lossis the sum over batches. None uses the integral (see the user guide).- max_batchint or None
Largest number of integrand evaluations per call of f. If this and the constructor’s value are None, the memory benchmark sets it (see the user guide). Replaced by the stored value under
same_f.- max_adaptive_splitsint or None
Cap on how many times a subinterval may have been halved since the starting mesh; at the cap it is accepted even if it fails the tolerance (see the user guide).
- error_normstr, Callable or None
How the error of a vector-valued integrand becomes one accept-or-split decision (see the user guide).
- error_integral_referencefloat, torch.Tensor or None
A value close to the integral, used in place of the running integral in the relative tolerance
rtol * |reference|. Only withuse_absolute_error_ratio=True(see the user guide).- mesh_failure_tolerancefloat or None
With
error_norm="failure_fraction", the fraction of output components that may fail while a subinterval is still accepted (see the user guide).- error_on_nonfinitebool or None
If True, raise
ValueErrorwhen f returns NaN or Inf; if False, accept those subintervals and let the value reach the result.- conserve_memorybool
With
take_gradient=False, evaluate one batch ofmax_batchpoints per pass instead of every waiting subinterval at once: less memory, more passes. Default False (see the user guide).- result_devicestr, torch.device or None
Device of the per-subinterval arrays of the result (default
"cpu"); None keeps them on the solver’s device. The integral andmesh_optimalstay on the solver’s device.
- Returns:
- IntegrationResult
The integral (plus
y0), its error estimate, whether itconverged, the optimal mesh, the nodes and integrand values of every subinterval, and split statistics (see the user guide).
- get_max_batch(total_mem_usage=None, default_max_batch=None)#
Return the largest number of integrand evaluations per batch.
Does not run the memory benchmark. The first available of these is used:
default_max_batch, themax_batchgiven at construction, and the number of evaluations that fit in the memory free now, with the memory per call the last benchmark measured. After an out-of-memory error, the result is capped at the reduced batch size chosen then, until the nextintegratecall starts.Passing the result as
max_batchto a later call or solver skips the slow benchmark. See Batch size and the memory benchmark.- Parameters:
- total_mem_usagefloat or None
Fraction of the device’s total memory that may be in use; the rest is kept free. None uses the value given at construction.
- default_max_batchint or None
A batch size that takes precedence over the other sources. None (default) skips it.
- Returns:
- int or None
The batch size, or None when no source is available (no
max_batchgiven and no benchmark run yet).
- set_dtype_by_input(mesh=None, mesh_init=None, mesh_final=None)#
Switch the solver to the dtype of the given mesh or bounds.
integratecalls this, so the solver follows the dtype of the mesh or bounds passed to it. The first ofmesh,mesh_initandmesh_finalthat is not None sets the dtype; if all are None, the dtype is unchanged. The switch persists: later calls keep the new dtype until another input changes it.- Parameters:
- meshtorch.Tensor or None
Starting mesh. Shape:
[M, T].- mesh_inittorch.Tensor or None
Lower bound. Shape:
[T].- mesh_finaltorch.Tensor or None
Upper bound. Shape:
[T].
- Raises:
- ValueError
If that tensor’s dtype is not torch.float64 or torch.float32.
- class padaquad.VariableAdaptiveQuadrature(*, f=None, method=None, atol=1e-05, rtol=1e-05, mesh_init=None, mesh_final=None, y0=None, remove_cut=0.1, merge_rule='predicted', max_batch=None, total_mem_usage=0.9, limit_benchmark_time=True, max_adaptive_splits=None, use_absolute_error_ratio=True, error_norm='2', mesh_failure_tolerance=0.0, error_on_nonfinite=True, dtype=torch.float64, device=None, output_speed_info=False, **distributed_options)#
Adaptive quadrature solver for methods whose weights depend on node positions.
The method computes the weights of each subinterval from where its nodes actually are, instead of using fixed numbers. The integration itself runs as in
UniformAdaptiveQuadrature: the nodes of every subinterval are placed at the method’s node fractions, and when a subinterval fails the tolerance, it is split in half and the integrand is evaluated at fresh nodes in both halves.The method is one of
VARIABLE_METHODS: ‘adaptive_heun’ or ‘interpolatory3_variable’. The constructor takes the options ofAdaptiveQuadrature, all as keyword arguments.Examples
Integrate
exp(t)from 0 to 1; the exact value ise - 1:>>> import torch >>> from padaquad import VariableAdaptiveQuadrature >>> _ = torch.manual_seed(0) >>> solver = VariableAdaptiveQuadrature( ... method="interpolatory3_variable", ... atol=1e-8, ... rtol=1e-8, ... device="cpu", ... max_batch=10_000, ... ) >>> result = solver.integrate( ... torch.exp, ... mesh_init=torch.tensor([0.0], dtype=torch.float64), ... mesh_final=torch.tensor([1.0], dtype=torch.float64), ... ) >>> print(round(float(result.integral), 6)) 1.718282
Create a solver and store the defaults that
integratefalls back on.Every argument is keyword-only.
- Parameters:
- fCallable or None
The integrand, used by
integratecalls that pass none. It takes points of shape [N, T] and returns values of shape [N, D] (see the user guide). Default None.- methodstr or None
Name of the quadrature method, a key of
UNIFORM_METHODS(uniform solver) orVARIABLE_METHODS(variable solver); case does not matter. None (default) means"gk21"(uniform) or"interpolatory3_variable"(variable).- atolfloat
Absolute tolerance. A subinterval is accepted when its error estimate is below
max(atol, rtol * |I|), withIthe integral (see the user guide). Default 1e-5.- rtolfloat
Relative tolerance; see
atol. Default 1e-5.- mesh_inittorch.Tensor or None
Default lower integration bound, shape [T]. None means 0.
- mesh_finaltorch.Tensor or None
Default upper integration bound, shape [T]. None means 1.
- y0torch.Tensor or None
Default value added to the returned integral, shape [D]. None means 0.
- remove_cutfloat
Largest predicted error ratio of a subinterval made by merging two neighbors when the optimal mesh is built; must be below 1. Lower values merge less. Default 0.1 (see the user guide).
- merge_rulestr
How the merged subinterval’s error is predicted when the optimal mesh is built (see the user guide):
"predicted"(default): computed from the integrand values already stored for the two neighbors, by interpolating them onto the merged subinterval’s nodes. Use this one."power_law": the neighbors’ summed error times2**(error_exponent - 1), the merge rule of padaquad 1.3.0 and 1.4.0. It assumes the error shrinks like a power of the width and refuses many safe merges on wide subintervals."sum": the neighbors’ summed error, the merge rule of padaquad 1.2.2. Merged subintervals often fail when evaluated again.
The older two are kept to reproduce meshes of earlier versions.
- max_batchint or None
Default for the largest number of integrand evaluations per call of
f. None (default) sets the batch size from the free memory, measured by a memory benchmark (see the user guide).- total_mem_usagefloat
Fraction of the device’s total memory, in (0, 1], that batches may fill: the batch size leaves
(1 - total_mem_usage)of it free. Used only when nomax_batchis set. Default 0.9.- limit_benchmark_timebool
If True (default), the memory benchmark raises
RuntimeErrorwhen it cannot measure the memory offwithin 60 s; False removes the limit, for anfso slow that the measurement needs longer (see the user guide).- max_adaptive_splitsint or None
Default cap on how many times a subinterval may have been halved since the starting mesh; at the cap it is accepted even if it fails the tolerance. None (default) means no cap (see the user guide).
- use_absolute_error_ratiobool
If True (default), the relative tolerance uses the whole integral; if False, the running integral from
mesh_initthrough each subinterval (see the user guide).- error_normstr or Callable
How the error of a vector-valued integrand becomes one accept-or-split decision:
"2"(default),"max","rms","failure_fraction"or a callable norm (see the user guide).- mesh_failure_tolerancefloat
With
error_norm="failure_fraction", the fraction of output components, in [0, 1], that may fail while a subinterval is still accepted. Default 0.0 (every component must pass).- error_on_nonfinitebool
If True (default), raise
ValueErrornaming the points wherefreturned NaN or Inf. If False, accept those subintervals and let the non-finite value reach the result.- dtypetorch.dtype
torch.float64(default) ortorch.float32;torch.float16is refused.integrateswitches to the dtype of the mesh or the bounds it is given.- devicestr, torch.device or None
"cpu","cuda","cuda:N"or atorch.device. None (default) picks CUDA if it is available, else the CPU.- output_speed_infobool
If True, log the time of each stage of the loop to the file
padaquad_speed.log. Default False.- **distributed_optionsAny
Options for multi-process (multi-GPU) runs only.
- Raises:
- TypeError
If an argument is passed by position, or a keyword is not an option of the solver.
- ValueError
If
remove_cutis not below 1,merge_ruleis not one of"predicted","power_law"and"sum", or another option is invalid.
Takes the same options and has the same methods as
UniformAdaptiveQuadrature.