desolver.utilities package¶
Submodules¶
desolver.utilities.interpolation module¶
- class desolver.utilities.interpolation.CubicHermiteInterp(t0, t1, p0, p1, m0, m1)¶
Bases:
objectCubic Hermite Polynomial Interpolation Class
Constructs a cubic Hermite polynomial interpolant for a function with values p0 and p1, and gradients m0 and m1 at t0 and t1 respectively.
- Parameters:
t0 (float) – Evaluation points
t1 (float) – Evaluation points
p0 (float or array-type) – Function values at t0 and t1
p1 (float or array-type) – Function values at t0 and t1
m0 (float or array-type) – Function gradients wrt. t and t0 and t1
m1 (float or array-type) – Function gradients wrt. t and t0 and t1
- grad(t_eval)¶
- property trange¶
- property tshift¶
desolver.utilities.optimizer module¶
- desolver.utilities.optimizer.brentsroot(f, bounds, tol=None, verbose=False, return_interval=False)¶
Brent’s algorithm for finding root of a bracketed function.
- Parameters:
f (callable) – callable that evaluates the function whose roots are to be found
bounds (tuple of float, shape (2,)) – lower and upper bound of interval to find root in
tol (float-type) – numerical tolerance for the precision of the root
verbose (bool) – set to true to print useful information
- Returns:
returns the location of the root if found and a bool indicating a root was found
- Return type:
tuple(float-type, bool)
Examples
>>> def ft(x): return x**2 - (1 - x)**5 >>> xl, xu = 0.1, 1.0 >>> x0, success = brentsroot(ft, xl, xu, verbose=True) >>> success, x0, ft(x0) (True, 0.34595481584824206, 6.938893903907228e-17)
- desolver.utilities.optimizer.brentsrootvec(f, bounds, tol=None, verbose=False, return_interval=False, accepts_mask=False)¶
Vectorised Brent’s algorithm for finding root of bracketed functions.
- Parameters:
f (list of callables) – list of callables each of which evaluates the function to find the root of
bounds (tuple of float, shape (2,)) – lower and upper bound of interval to find root in
tol (float-type) – numerical tolerance for the precision of the roots
verbose (bool) – set to true to print useful information
accepts_mask (bool) – set to true to pass a mask array to the function, for certain situations, this avoids redundant computation for converged roots
- Returns:
returns a list of the locations of roots and a list of bools indicating whether or not a root was found in the interval
- Return type:
tuple(list(float-type), list(bool))
Examples
>>> f = lambda x: lambda y: x * y - y**2 + x >>> xl, xu = 0.1, 1.0 >>> funcs = [f(i*0.5) for i in range(3)] >>> x0, success = brentsrootvec(funcs, xl, xu, verbose=True) >>> success, x0, [funcs[i](x0[i]) for i in range(len(funcs))] (array([ True, True, True]), array([0. , 1. , 1.61803399]), [0.0, 0.0, 0.0])
- desolver.utilities.optimizer.newtontrustregion(f, x0, jac=None, tol=None, verbose=False, maxiter=200, jac_update_rate=20, initial_trust_region=None, var_bounds=None)¶
- desolver.utilities.optimizer.nonlinear_roots(f, x0, jac=None, tol=None, verbose=False, maxiter=200, use_scipy=True, additional_args=(), additional_kwargs={}, var_bounds=None)¶
- desolver.utilities.optimizer.transform_to_bounded_fn(fn, lower_bound, upper_bound)¶
- desolver.utilities.optimizer.transform_to_bounded_jac(jac, lower_bound, upper_bound)¶
- desolver.utilities.optimizer.transform_to_bounded_x(x, lower_bound, upper_bound)¶
- desolver.utilities.optimizer.transform_to_unbounded_x(x, lower_bound, upper_bound)¶
desolver.utilities.utilities module¶
- class desolver.utilities.utilities.BlockTimer(section_label=None, start_now=True, suppress_print=False)¶
Bases:
objectTiming Class
Takes advantage of the with syntax in order to time a block of code.
- Parameters:
section_label (str) – name given to section of code
start_now (bool) – if True the timer is started upon construction, otherwise start() must be called.
suppress_print (bool) – if True a message will be printed upon destruction with the section_label and the code time.
- elapsed()¶
Method to get the elapsed time.
- Returns:
Returns the elapsed time since timer start if stop() was not called, otherwise returns the elapsed time between timer start and when elapsed() is called.
- Return type:
float
- end()¶
Method to stop the timer
- restart_timer()¶
Method to restart the timer.
Sets the start time to now and resets the end time.
- start()¶
Method to start the timer
- class desolver.utilities.utilities.JacobianWrapper(rhs, base_order=2, richardson_iter=None, adaptive=True, flat=False, atol=None, rtol=None, sample_input=None)¶
Bases:
objectA wrapper class that uses Richardson Extrapolation and 4th order finite differences to compute the jacobian of a given callable function.
The Jacobian is computed using up to 16 richardson iterations which translates to a maximum order of 4+16 for the gradients with respect to Δx as Δx->0. The evalaution is adaptive so within the given tolerances, the evaluation will exit early in order to minimise computation so gradients can be calculated with controllable precision.
- rhs¶
A callable function that
- Type:
Callable of the form f(x)->D.array of arbitrary shape
- base_order¶
The order of the underlying finite difference gradient estimate, this can be evaluated at different step sizes using the estimate method.
- Type:
int
- richardson_iter¶
The maximum number of richardson iterations to use for estimating gradients. In most cases, less than 16 should be enough, and if you start needing more than 16, it might be worth considering that finite differences are inappropriate.
- Type:
int
- order¶
Maximum order of the gradient estimate
- Type:
int
- adaptive¶
Whether to use adaptive evaluation of the richardson extrapolation or to run for the full 16 iterations.
- Type:
bool
- atol, rtol
Absolute and relative tolerances for the adaptive gradient extrapolation
- Type:
float
- flat¶
If set to True, the gradients will be returned as a ravelled array (ie. jacobian.shape = (-1,)) If set to False, the shape will be (*x.shape, *f(x).shape). When x and f(x) are vector valued of length n and m respectively, the gradient will have the shape (n,m) as expected of the Jacobian of f(x).
- Type:
bool
- adaptive_richardson(y, *args, dy=0.5, factor=4, **kwargs)¶
- check_converged(initial_state, diff, prev_error)¶
- estimate(y, *args, dy=None, **kwargs)¶
- richardson(y, *args, dy=0.5, factor=4.0, **kwargs)¶
- desolver.utilities.utilities.convert_suffix(value, suffixes=('d', 'h', 'm', 's'), ratios=(24, 60, 60), delimiter=':')¶
Converts a base value into a human readable format with the given suffixes and ratios.
- Parameters:
value (int or float) – value to be converted
suffixes (list of str) – suffixes for each subdivision (eg. [‘days’, ‘hours’, ‘minutes’, ‘seconds’])
ratios (list of int) – the relative period of each subdivision (eg. 24 hours in 1 day, 60 minutes in 1 hour, 60 seconds in 1 minute -> [24, 60, 60])
delimiter (str) – string to use between each subdivision
- Returns:
returns string with the subdivision values and suffixes joined together
- Return type:
str
Examples
>>> convert_suffix(3661, suffixes=['d', 'h', 'm', 's'], ratios=[24, 60, 60], delimiter=':') '0d:1h:1m1.00s'
- desolver.utilities.utilities.search_bisection(array, val)¶
Finds the index of the nearest value to val in array. Uses the bisection method.
- Parameters:
array (list of numeric values) – list to search, assumes the list is sorted (will not work if it isn’t sorted!)
val (numeric) – numeric value to find the nearest value in the array.
- Returns:
returns the index of the position in the array with the value closest to val
- Return type:
int
Examples
>>> list_to_search = [1,2,3,4,5] >>> val_to_find = 2.5 >>> idx = search_bisection(list_to_search, val_to_find) >>> idx, list_to_search[idx] (1, 2)
- desolver.utilities.utilities.search_bisection_vec(array, val)¶
Finds the indices of the nearest values in array to each val. Uses the bisection method.
- Parameters:
array (array of numeric values) – list to search, assumes the list is sorted (will not work if it isn’t sorted!)
val (array of numeric values) – numeric values to find the nearest value in array.
- Returns:
returns the indices of the positions in the array with the value closest to val
- Return type:
array(int)
Examples
>>> list_to_search = [1,2,3,4,5] >>> val_to_find = [1.5,3.5] >>> idx = search_bisection(list_to_search, val_to_find) >>> idx, list_to_search[idx] ([0,2], [1,3])
- desolver.utilities.utilities.warning(message, category=<class 'Warning'>)¶
Convenience function for printing to sys.stderr.
- Parameters:
message (str) – warning message
category (warning category) – type of warning message. eg. DeprecationWarning
Examples
>>> warning("Things have failed...", warning.Warning) Things have failed...