VeraGridEngine.Utils.NumericalMethods package

Submodules

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_pareto module

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_pareto.MVRSM_mo_pareto(obj_func, x0: ndarray[tuple[Any, ...], dtype[float64]], lb: ndarray[tuple[Any, ...], dtype[float64]], ub: ndarray[tuple[Any, ...], dtype[float64]], num_int: int, max_evals: int, n_objectives: int, rand_evals: int = 0, args=())[source]

MVRSM algorithm for multiple objectives x = [integer vars | float vars] :param obj_func: objective function :param x0: Initial solution [int vars | float vars] :param lb: lower bound :param ub: Upper bound :param num_int: number of integer variables sice x will be split by this amount ([int vars | float vars]) :param max_evals: maximum number of evaluations :param n_objectives: number of objectives expected :param rand_evals: number of random initial evaluations :param args: extra arguments to be passed to obj_func apart from x :return: pareto front y, pareto front x, all y not sorted

class VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_pareto.SurrogateModel[source]

Bases: object

P
W
augmented_Tchebycheff(x, scalarization_weights)[source]

Evaluates the augmented Tchebycheff scalarization of multiple objectives. :param x: the decision variable values :param scalarization_weights: vector of size n_obj

augmented_Tchebycheff_jac(x, scalarization_weights)[source]

Evaluates the Jacobian of the augmented Tchebycheff scalarization of multiple objectives. :param x: the decision variable values :param scalarization_weights: vector of size n_obj

b
bounds
c
g(x)[source]

Evaluates the surrogate model at x. :param x: the decision variable values.

g_jac(x)[source]

Evaluates the Jacobian of the model at x. :param x: the decision variable values.

g_scalarize(x, scalarization_weights: ndarray[tuple[Any, ...], dtype[float64]])[source]

Evaluates the linear scalarization of multiple objectives. :param x: the decision variable values :param scalarization_weights: vector of size n_obj

g_scalarize_jac(x, scalarization_weights)[source]

Evaluates the Jacobian of the linear scalarization of multiple objectives. :param x: the decision variable values :param scalarization_weights: vector of size n_obj

g_scalarize_max(x, scalarization_weights)[source]

Evaluates the maximum or Tchebycheff scalarization of multiple objectives. :param x: the decision variable values :param scalarization_weights: vector of size n_obj

g_scalarize_max_jac(x, scalarization_weights)[source]

Evaluates the Jacobian of the maximum or Tchebycheff scalarization of multiple objectives. :param x: the decision variable values :param scalarization_weights: vector of size n_obj

classmethod init(n_obj: int, d: int, lb: ndarray[tuple[Any, ...], dtype[float64]], ub: ndarray[tuple[Any, ...], dtype[float64]], num_int: int) SurrogateModel[source]

Initializes a surrogate model. :param n_obj: number of objective function dimensions :param d: the number of (discrete and continuous) decision variables. :param lb: the lower bound of the decision variable values. :param ub: the upper bound of the decision variable values. :param num_int: the number of discrete decision variables (0 ≀ num_int ≀ d).

m
minimum(x0: ndarray[tuple[Any, ...], dtype[float64]], scalarization_weights: ndarray[tuple[Any, ...], dtype[float64]]) ndarray[tuple[Any, ...], dtype[float64]][source]

Find a minimum of the surrogate model approximately. :param x0: the initial guess. :param scalarization_weights: weights for the scalarization of multiple objectives :return minimization evaluation and corresponding function values

n_obj
phi(x, out=None)[source]

Evaluates the basis functions at x. :param x: the decision variable values :param out: the vector in which to put the result; None to allocate.

phi_deriv(x, out=None)[source]

Evaluates the derivatives of the basis functions with respect to x. :param x: the decision variable values :param out: the vector in which to put the result; None to allocate.

scratch
update(x, y)[source]

Updates the model upon the observation of a new data point (x, y). :param x: the decision variables values :param y: the objective function value y(x)

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_pareto.get_norm_factors(scaling_values)[source]

Computes the factors used to normalize objective function criteria.. :param scaling_values: Array with all the criteria obtained during random evaluation process. :return: Tuple of arrays where 1st array is maximum values of y and second minimum values.

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_pareto.inv_normalize_md(y_normalized, norm_factors)[source]

Computes the inverse of normalize_md(y_no_normalized, norm_factors). :param y_normalized: The normalized objective function values: np.array.shape[1]=f_obj_dim. :param norm_factors: Tuple of arrays where 1st array is maximum values of y and second minimum values. :return: the value y_no_normalized such that inv_normalize_md(y_normalized, y0) = y_no_normalized.

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_pareto.inv_scale(y_scaled, y0, scale_threshold=1e-08)[source]

Computes the inverse function of scale(y, y0). :param y_scaled: the scaled objective function value. :param y0: the initial objective function value, y(x0). :param scale_threshold: value under which no scaling is done :return: the value y such that scale(y, y0) = y_scaled.

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_pareto.normalize_md(y_no_normalized, norm_factors)[source]

Computes the normalization of y_no_normalized –> y_normalized=(y_no_normalized-y_min)/(y_max-y_min). :param y_no_normalized: The no normalized objective function values: np.array.shape[1]=f_obj_dim. :param norm_factors: Tuple of arrays where 1st array is maximum values of y and second minimum values. :return: the value y_normalized such that normalize_md(y_no_normalized, y0) = y_normalized.

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_pareto.relu(x)[source]

The Rectified Linear Unit (ReLU) function. :param x: the input and output vector

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_pareto.relu_deriv(x)[source]

The derivative of the rectified linear unit function, defined with relu_deriv(0) = 0.5. :param x: the input and output vector

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_pareto.scale(y, y0, scale_threshold=1e-08)[source]

# normalize: do this for every objective so that all objectives are more or less in the same range Scale the objective with respect to the initial objective value, causing the optimum to lie below zero. This helps exploration and prevents the algorithm from getting stuck at the boundary. :param y: the objective function value. :param y0: the initial objective function value, y(x0). :param scale_threshold: value under which no scaling is done

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled module

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.MVRSM_mo_scaled(obj_func, x0: ndarray[tuple[Any, ...], dtype[float64]], lb: ndarray[tuple[Any, ...], dtype[float64]], ub: ndarray[tuple[Any, ...], dtype[float64]], num_int: int, max_evals: int, rand_evals: int = 1, args=(), stop_crit=None, n_objectives=1)[source]

MVRSM algorithm adapted to minimize multi-dimensional functions. After the random evaluations, the normalization factors are obtained (y_max and y_min), then, each objective is normalized –> y_norm=(y-y_min)/(y_max-y_min). The algorithm minimizes the sum of the normalized objectives.

Parameters:
  • obj_func – objective function

  • x0 – Initial solution

  • lb – lower bound

  • ub – Upper bound

  • num_int – number of integer variables

  • max_evals – maximum number of evaluations

  • rand_evals – number of random initial evaluations

  • args – extra arguments to be passed to obj_func appart from x

  • stop_crit

:param n_objectives : if 1 objective function returns single float, otherwise a vector of size = n_objectives :return: all combinations, all y, SurrogateModel

class VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.SurrogateModel[source]

Bases: object

P
W
b
bounds
c
g(x)[source]

Evaluates the surrogate model at x. :param x: the decision variable values.

g_jac(x)[source]

Evaluates the Jacobian of the model at x. :param x: the decision variable values.

classmethod init(d, lb, ub, num_int) SurrogateModel[source]

Initializes a surrogate model. :param d: the number of (discrete and continuous) decision variables. :param lb: the lower bound of the decision variable values. :param ub: the upper bound of the decision variable values. :param num_int: the number of discrete decision variables (0 ≀ num_int ≀ d).

m
minimum(x0)[source]

Find a minimum of the surrogate model approximately. :param x0: the initial guess.

phi(x, out=None)[source]

Evaluates the basis functions at x. :param x: the decision variable values :param out: the vector in which to put the result; None to allocate.

phi_deriv(x, out=None)[source]

Evaluates the derivatives of the basis functions with respect to x. :param x: the decision variable values :param out: the vector in which to put the result; None to allocate.

scratch
update(x, y)[source]

Updates the model upon the observation of a new data point (x, y). :param x: the decision variables values :param y: the objective function value y(x)

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.crowding_distance(front: List[int], population: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]) ndarray[tuple[Any, ...], dtype[float64]][source]
Parameters:
  • front – list of integers representing the positions in the population matrix

  • population – Matrix of function evaluations (Npoints, NObjdim)

Returns:

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.dominates(sol_a: ndarray[tuple[Any, ...], dtype[float64]], sol_b: ndarray[tuple[Any, ...], dtype[float64]])[source]

Check if a solution dominates another in the Pareto sense :param sol_a: Array representing the solution A (row of the population) :param sol_b: Array representing the solution B (row of the population) :return: A dominates B?

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.get_non_dominated_fronts(population: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]) List[List[int]][source]

2D non dominated sorting :param population: matrix (n points, ndim) :return: Fronts ordered by position (front 1, front 2, Front 3, …)

Each front is a list of integers representing the positions in the population matrix

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.get_norm_factors(scaling_values)[source]

Computes the factors used to normalize objective function criteria.. :param scaling_values: Array with all the criteria obtained during random evaluation process. :return: Tuple of arrays where 1st array is maximum values of y and second minimum values.

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.inv_normalize_md(y_normalized, norm_factors)[source]

Computes the inverse of normalize_md(y_no_normalized, norm_factors). :param y_normalized: The normalized objective function values: np.array.shape[1]=n_objectives . :param norm_factors: Tuple of arrays where 1st array is maximum values of y and second minimum values. :return: the value y_no_normalized such that inv_normalize_md(y_normalized, y0) = y_no_normalized.

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.inv_scale(y_scaled, y0, scale_threshold=1e-08)[source]

Computes the inverse function of scale(y, y0). :param y_scaled: the scaled objective function value. :param y0: the initial objective function value, y(x0). :param scale_threshold: value under which no scaling is done :return: the value y such that scale(y, y0) = y_scaled.

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.non_dominated_sorting(y_values: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], x_values: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]])[source]

Use non dominated sorting and crowded sorting to sort the multidimensional objectives :param y_values: Matrix of function evaluations (Npoints, NObjdim) :param x_values: Matrix of values (Npoints, Ndim) :return: Return the pareto y and matching x. The pareto front may have less values than the population

[Sorted population, Sorted input values (X)]

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.normalize_md(y_no_normalized, norm_factors)[source]

Computes the normalization of y_no_normalized –> y_normalized=(y_no_normalized-y_min)/(y_max-y_min). :param y_no_normalized: The no normalized objective function values: np.array.shape[1]=n_objectives . :param norm_factors: Tuple of arrays where 1st array is maximum values of y and second minimum values. :return: the value y_normalized such that normalize_md(y_no_normalized, y0) = y_normalized.

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.relu(x)[source]

The Rectified Linear Unit (ReLU) function. :param x: the input and output vector

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.relu_deriv(x)[source]

The derivative of the rectified linear unit function, defined with relu_deriv(0) = 0.5. :param x: the input and output vector

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.scale(y, y0, scale_threshold=1e-08)[source]

Scale the objective with respect to the initial objective value, causing the optimum to lie below zero. This helps exploration and prevents the algorithm from getting stuck at the boundary. :param y: the objective function value. :param y0: the initial objective function value, y(x0). :param scale_threshold: value under which no scaling is done

VeraGridEngine.Utils.NumericalMethods.MVRSM_mo_scaled.sort_by_crowding(fronts: List[List[int]], population: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]) Tuple[ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], ndarray[tuple[Any, ...], dtype[int64]]][source]
Parameters:
  • fronts – Fronts ordered by position (front 1, front 2, Front 3, …) Each front is a list of integers representing the positions in the population matrix

  • population – Matrix of function evaluations (Npoints, NObjdim)

Returns:

sorted population, array of sorting indices

VeraGridEngine.Utils.NumericalMethods.MVRSM_original module

VeraGridEngine.Utils.NumericalMethods.MVRSM_original.MVRSM_minimize(obj_func, x0, lb, ub, num_int, max_evals, rand_evals=0, obj_threshold=0.0, args=(), stop_crit=None, rand_search_bias=0.5, log_times=False, scale_threshold=1e-08)[source]
Parameters:
  • obj_func – objective function

  • x0 – Initial solution

  • lb – lower bound

  • ub – Upper bound

  • num_int – number of integer variables

  • max_evals – maximum number of evaluations

  • rand_evals – number of random initial evaluations

  • obj_threshold

  • args – extra arguments to be passed to obj_func appart from x

  • stop_crit

  • rand_search_bias

  • log_times

  • scale_threshold – value under which no scaling is done

Returns:

best x, best y, SurrogateModel

class VeraGridEngine.Utils.NumericalMethods.MVRSM_original.SurrogateModel[source]

Bases: object

P
W
b
bounds
c
g(x)[source]

Evaluates the surrogate model at x. :param x: the decision variable values.

g_jac(x)[source]

Evaluates the Jacobian of the model at x. :param x: the decision variable values.

classmethod init(d, lb, ub, num_int) SurrogateModel[source]

Initializes a surrogate model. :param d: the number of (discrete and continuous) decision variables. :param lb: the lower bound of the decision variable values. :param ub: the upper bound of the decision variable values. :param num_int: the number of discrete decision variables (0 ≀ num_int ≀ d).

m
minimum(x0)[source]

Find a minimum of the surrogate model approximately. :param x0: the initial guess.

phi(x, out=None)[source]

Evaluates the basis functions at x. :param x: the decision variable values :param out: the vector in which to put the result; None to allocate.

phi_deriv(x, out=None)[source]

Evaluates the derivatives of the basis functions with respect to x. :param x: the decision variable values :param out: the vector in which to put the result; None to allocate.

scratch
update(x, y)[source]

Updates the model upon the observation of a new data point (x, y). :param x: the decision variables values :param y: the objective function value y(x)

VeraGridEngine.Utils.NumericalMethods.MVRSM_original.get_norm_factors(scaling_values)[source]

Computes the factors used to normalize objective function criteria.. :param scaling_values: Array with all the criteria obtained during random evaluation process. :return: Tuple of arrays where 1st array is maximum values of y and second minimum values.

VeraGridEngine.Utils.NumericalMethods.MVRSM_original.inv_normalize_md(y_normalized, norm_factors)[source]

Computes the inverse of normalize_md(y_no_normalized, norm_factors). :param y_normalized: The normalized objective function values: np.array.shape[1]=n_objectives . :param norm_factors: Tuple of arrays where 1st array is maximum values of y and second minimum values. :return: the value y_no_normalized such that inv_normalize_md(y_normalized, y0) = y_no_normalized.

VeraGridEngine.Utils.NumericalMethods.MVRSM_original.inv_scale(y_scaled, y0, scale_threshold=1e-08)[source]

Computes the inverse function of scale(y, y0). :param y_scaled: the scaled objective function value. :param y0: the initial objective function value, y(x0). :param scale_threshold: value under which no scaling is done :return: the value y such that scale(y, y0) = y_scaled.

VeraGridEngine.Utils.NumericalMethods.MVRSM_original.normalize_md(y_no_normalized, norm_factors)[source]

Computes the normalization of y_no_normalized –> y_normalized=(y_no_normalized-y_min)/(y_max-y_min). :param y_no_normalized: The no normalized objective function values: np.array.shape[1]=n_objectives . :param norm_factors: Tuple of arrays where 1st array is maximum values of y and second minimum values. :return: the value y_normalized such that normalize_md(y_no_normalized, y0) = y_normalized.

VeraGridEngine.Utils.NumericalMethods.MVRSM_original.relu(x)[source]

The Rectified Linear Unit (ReLU) function. :param x: the input and output vector

VeraGridEngine.Utils.NumericalMethods.MVRSM_original.relu_deriv(x)[source]

The derivative of the rectified linear unit function, defined with relu_deriv(0) = 0.5. :param x: the input and output vector

VeraGridEngine.Utils.NumericalMethods.MVRSM_original.scale(y, y0, scale_threshold=1e-08)[source]

Scale the objective with respect to the initial objective value, causing the optimum to lie below zero. This helps exploration and prevents the algorithm from getting stuck at the boundary. :param y: the objective function value. :param y0: the initial objective function value, y(x0). :param scale_threshold: value under which no scaling is done

VeraGridEngine.Utils.NumericalMethods.autodiff module

VeraGridEngine.Utils.NumericalMethods.autodiff.calc_autodiff_hessian(func: Callable[[ndarray[tuple[Any, ...], dtype[float64]], Any], ndarray[tuple[Any, ...], dtype[float64]] | Tuple[ndarray[tuple[Any, ...], dtype[float64]], Any]], x: ndarray[tuple[Any, ...], dtype[float64]], mult: ndarray[tuple[Any, ...], dtype[float64]], arg=(), h=1e-05) csc_matrix[source]

Compute the Hessian matrix of func at x using finite differences.

Parameters:
  • func – function accepting a vector x and args, and returning either a vector or a tuple where the first argument is a vector and the second.

  • x – Point at which to evaluate the Hessian (numpy array).

  • mult – Array of multipliers associated with the functions. The objective function passes value 1 (no action)

  • arg – Tuple of arguments to call func aside from x [func(x, *arg)]

  • h – Small step for finite difference.

Returns:

Hessian matrix as a CSC matrix.

VeraGridEngine.Utils.NumericalMethods.autodiff.calc_autodiff_hessian_f_obj(func: Callable[[ndarray[tuple[Any, ...], dtype[float64]], Any], float], x: ndarray[tuple[Any, ...], dtype[float64]], arg=(), h=1e-05) csc_matrix[source]

Compute the Hessian matrix of func at x using finite differences. This considers that the output is a single value, such as is the case of the objective function f

Parameters:
  • func – objective function accepting x and arg and returning a float.

  • x – Point at which to evaluate the Hessian (numpy array).

  • arg – Tuple of arguments to call func aside from x [func(x, *arg)]

  • h – Small step for finite difference.

Returns:

Hessian matrix as a CSC matrix.

VeraGridEngine.Utils.NumericalMethods.autodiff.calc_autodiff_jacobian(func: Callable[[ndarray[tuple[Any, ...], dtype[float64]], Any], ndarray[tuple[Any, ...], dtype[float64]] | Tuple[ndarray[tuple[Any, ...], dtype[float64]], Any]], x: ndarray[tuple[Any, ...], dtype[float64]], arg=(), h=1e-08) csc_matrix[source]

Compute the Jacobian matrix of func at x using finite differences.

Parameters:
  • func – function accepting a vector x and args, and returning either a vector or a tuple where the first argument is a vector and the second.

  • x – Point at which to evaluate the Jacobian (numpy array).

  • arg – Tuple of arguments to call func aside from x [func(x, *arg)]

  • h – Small step for finite difference.

Returns:

Jacobian matrix as a CSC matrix.

VeraGridEngine.Utils.NumericalMethods.autodiff.calc_autodiff_jacobian_f_obj(func: Callable[[ndarray[tuple[Any, ...], dtype[float64]], ...], float], x: ndarray[tuple[Any, ...], dtype[float64]], arg=(), h=1e-05) ndarray[tuple[Any, ...], dtype[float64]][source]

Compute the Jacobian matrix of func at x using finite differences. This considers that the output is a single value, such as is the case of the objective function f :param func: objective function accepting x and arg and returning a float. :param x: Point at which to evaluate the Jacobian (numpy array). :param arg: Tuple of arguments to call func aside from x [func(x, *arg)] :param h: Small step for finite difference. :return: Jacobian as a vector, because the objective function is a single value.

VeraGridEngine.Utils.NumericalMethods.autodiff.unpack(ret: ndarray[tuple[Any, ...], dtype[float64]] | Tuple[ndarray[tuple[Any, ...], dtype[float64]], ...]) ndarray[tuple[Any, ...], dtype[float64]][source]

Unpack the returning vector depending if ret is the vector or a tuple including the vector :param ret: Tuple with the vector or vector directly :return: Vector

VeraGridEngine.Utils.NumericalMethods.common module

class VeraGridEngine.Utils.NumericalMethods.common.ConvexFunctionResult(f: ndarray[tuple[Any, ...], dtype[float64]], J: csc_matrix)[source]

Bases: object

Result of the convex function evaluated iterativelly for a given method

J: csc_matrix
compute_f_error()[source]

Compute the error of the increments g :return: max(abs(G))

f: ndarray[tuple[Any, ...], dtype[float64]]
class VeraGridEngine.Utils.NumericalMethods.common.ConvexMethodResult(x: ndarray[tuple[Any, ...], dtype[float64]], error: float, converged: bool, iterations: int, elapsed: float, error_evolution: ndarray[tuple[Any, ...], dtype[float64]])[source]

Bases: object

Iterative convex method result

converged: bool
elapsed: float
error: float
error_evolution: ndarray[tuple[Any, ...], dtype[float64]]
iterations: int
plot_error() None[source]

Plot the IPS error

print_info()[source]

Print information about the ConvexMethodResult :return:

x: ndarray[tuple[Any, ...], dtype[float64]]
VeraGridEngine.Utils.NumericalMethods.common.check_function_and_args(func: Callable, args: Tuple, n_used_for_solver: int) bool[source]

Checks if the number of supplied arguments matches the function signature :param func: Function pointer :param args: tuple of arguments to be passed before the mandatory arguments used by the numerical method :param n_used_for_solver: Number of mandatory arguments used by the numerical method :return: ok?

VeraGridEngine.Utils.NumericalMethods.common.compute_L(h, f, J) float[source]

1/2 Β· ||f + J @ h|| :param h: some vector :param f: f vector :param J: Jacobian of f :return:

VeraGridEngine.Utils.NumericalMethods.common.find_closest_number(arr: ndarray[tuple[Any, ...], dtype[float64]], target: float) Tuple[int, float][source]

Find the closest number that exists in array :param arr: Array to be searched (must be sorted from min to max) :param target: Value to search for :return: index in the array, Closes adjusted or truncated value

VeraGridEngine.Utils.NumericalMethods.common.make_complex(r: ndarray[tuple[Any, ...], dtype[float64]], i: ndarray[tuple[Any, ...], dtype[float64]]) ndarray[tuple[Any, ...], dtype[complex128]][source]

Fastest way to create complex arrays :param r: :param i: :return:

VeraGridEngine.Utils.NumericalMethods.common.make_lookup(size: int, indices: ndarray[tuple[Any, ...], dtype[int64]]) ndarray[tuple[Any, ...], dtype[int64]][source]

Create a lookup array :param size: Size of the thing (i.e. number of buses) :param indices: indices to map (i.e. pq indices) :return: lookup array, -1 at the indices that do not match with the β€œindices” input array

VeraGridEngine.Utils.NumericalMethods.common.max_abs(x: ndarray[tuple[Any, ...], dtype[float64]]) float[source]

Compute max abs efficiently :param x: :return:

VeraGridEngine.Utils.NumericalMethods.common.norm(x: ndarray[tuple[Any, ...], dtype[float64]]) float[source]

Compute max abs efficiently :param x: :return:

VeraGridEngine.Utils.NumericalMethods.emt_sparse_solver_loader module

class VeraGridEngine.Utils.NumericalMethods.emt_sparse_solver_loader.SparseSolverPluginManifest(name: str, solver_type: SparseSolver, module_name: str, class_name: str, version: str)[source]

Bases: object

Parsed manifest of one external EMT sparse solver plugin.

get_class_name() str[source]

Return the provider class name.

Returns:

Provider class name.

Return type:

str

get_module_name() str[source]

Return the module name.

Returns:

Module name.

Return type:

str

get_name() str[source]

Return the plugin name.

Returns:

Plugin name.

Return type:

str

get_solver_type() SparseSolver[source]

Return the sparse solver type.

Returns:

Sparse solver type.

Return type:

SparseSolver

get_version() str[source]

Return the plugin version string.

Returns:

Plugin version string.

Return type:

str

VeraGridEngine.Utils.NumericalMethods.emt_sparse_solver_loader.get_default_sparse_solver_plugins_directory() Path[source]

Return the default directory containing EMT sparse solver plugins.

Returns:

Default sparse-solver plugin directory.

Return type:

Path

VeraGridEngine.Utils.NumericalMethods.emt_sparse_solver_loader.load_sparse_solver_backend_provider(plugin_name: str, plugin_directory_override: str) SparseLinearSolverBackendProvider[source]

Load one sparse-solver backend provider by plugin name.

Parameters:
  • plugin_name (str) – Plugin name.

  • plugin_directory_override (str) – Optional plugin-directory override.

Returns:

Sparse solver backend provider.

Return type:

SparseLinearSolverBackendProvider

VeraGridEngine.Utils.NumericalMethods.emt_sparse_solver_loader.load_sparse_solver_backend_provider_from_plugin(plugin_directory: Path, manifest: SparseSolverPluginManifest) SparseLinearSolverBackendProvider[source]

Load a sparse-solver backend provider from one plugin directory.

Parameters:
Returns:

Sparse solver backend provider.

Return type:

SparseLinearSolverBackendProvider

VeraGridEngine.Utils.NumericalMethods.emt_sparse_solver_loader.read_sparse_solver_plugin_manifest(plugin_directory: Path) SparseSolverPluginManifest[source]

Read and validate one sparse-solver plugin manifest.

Parameters:

plugin_directory (Path) – Plugin directory.

Returns:

Parsed manifest.

Return type:

SparseSolverPluginManifest

VeraGridEngine.Utils.NumericalMethods.emt_sparse_solver_loader.resolve_sparse_solver_plugins_directory(custom_directory: str) Path[source]

Resolve the sparse-solver plugin directory.

Parameters:

custom_directory (str) – User-provided plugin directory.

Returns:

Resolved plugin directory.

Return type:

Path

VeraGridEngine.Utils.NumericalMethods.emt_sparse_solver_registry module

VeraGridEngine.Utils.NumericalMethods.emt_sparse_solver_registry.build_internal_sparse_solver_provider_map() Dict[SparseSolver, SparseLinearSolverBackendProvider][source]

Build the map of built-in EMT sparse solver providers.

Returns:

Built-in provider map.

Return type:

Dict[SparseSolver, SparseLinearSolverBackendProvider]

VeraGridEngine.Utils.NumericalMethods.emt_sparse_solver_registry.resolve_emt_sparse_solver_backend_provider(solver_type: SparseSolver, external_plugin_name: str, external_plugin_directory: str, allow_internal_fallback: bool) SparseLinearSolverBackendProvider[source]

Resolve the EMT sparse solver backend provider.

Parameters:
  • solver_type (SparseSolver) – Requested sparse solver type.

  • external_plugin_name (str) – External plugin name.

  • external_plugin_directory (str) – External plugin directory override.

  • allow_internal_fallback (bool) – Whether internal fallback is allowed.

Returns:

Resolved backend provider.

Return type:

SparseLinearSolverBackendProvider

VeraGridEngine.Utils.NumericalMethods.emt_sparse_superlu_backend module

class VeraGridEngine.Utils.NumericalMethods.emt_sparse_superlu_backend.SuperLUFactorizationHandle(lu_obj: SuperLU, active_matrix: csc_matrix, ordered_bundle_active: bool, has_persistent_ordering: bool, inverse_column_perm: ndarray)[source]

Bases: SparseLinearFactorizationHandle

Factorization handle backed by SciPy SuperLU.

get_active_matrix() csc_matrix[source]

Return the sparse matrix associated with the current factorization.

Returns:

Active sparse matrix.

Return type:

csc_matrix

solve_into(rhs: ndarray[tuple[Any, ...], dtype[float64]], out_solution: ndarray[tuple[Any, ...], dtype[float64]]) None[source]

Solve the sparse system into a caller-owned output buffer.

Parameters:
  • rhs (Vec) – Right-hand side vector.

  • out_solution (Vec) – Caller-owned output buffer.

Returns:

None.

Return type:

None

class VeraGridEngine.Utils.NumericalMethods.emt_sparse_superlu_backend.SuperLUSparseBackend(base_matrix: csc_matrix, base_data: ndarray[tuple[Any, ...], dtype[float64]])[source]

Bases: SparseLinearSolverBackend

EMT sparse backend backed by SciPy SuperLU.

factorize(matrix: csc_matrix, analysis_handle: object | None) SparseLinearFactorizationHandle[source]

Factorize the current EMT Jacobian.

Parameters:
  • matrix (csc_matrix) – Sparse matrix in EMT solver order.

  • analysis_handle (object | None) – Optional symbolic-analysis handle.

Returns:

SuperLU factorization handle.

Return type:

SparseLinearFactorizationHandle

get_backend_stats() Dict[str, float][source]

Return backend-specific statistics.

Returns:

Backend-specific statistics.

Return type:

Dict[str, float]

get_name() str[source]

Return the backend name.

Returns:

Backend name.

Return type:

str

get_solver_type() SparseSolver[source]

Return the sparse solver type.

Returns:

Sparse solver type.

Return type:

SparseSolver

is_available() bool[source]

Return whether the backend is available.

Returns:

True.

Return type:

bool

supports_symbolic_analysis_reuse() bool[source]

Return whether this backend supports persistent symbolic reuse.

Returns:

True.

Return type:

bool

class VeraGridEngine.Utils.NumericalMethods.emt_sparse_superlu_backend.SuperLUSparseBackendProvider[source]

Bases: SparseLinearSolverBackendProvider

Provider for the internal SuperLU EMT sparse backend.

create_backend(base_matrix: csc_matrix, base_data: ndarray[tuple[Any, ...], dtype[float64]]) SparseLinearSolverBackend[source]

Create the internal SuperLU sparse backend.

Parameters:
  • base_matrix (csc_matrix) – Reusable EMT Jacobian CSC shell.

  • base_data (Vec) – Reusable EMT Jacobian numeric buffer.

Returns:

Sparse solver backend.

Return type:

SparseLinearSolverBackend

get_name() str[source]

Return the provider name.

Returns:

Provider name.

Return type:

str

get_solver_type() SparseSolver[source]

Return the sparse solver type.

Returns:

Sparse solver type.

Return type:

SparseSolver

is_available() bool[source]

Return whether the provider is available.

Returns:

True.

Return type:

bool

VeraGridEngine.Utils.NumericalMethods.external_sparse_solver_interface module

class VeraGridEngine.Utils.NumericalMethods.external_sparse_solver_interface.SparseLinearFactorizationHandle[source]

Bases: object

Abstract sparse factorization handle used by EMT sparse backends.

The factorization handle owns the solver-specific numeric factorization state and exposes a uniform solve interface to the EMT sparse factorization manager.

get_active_matrix() csc_matrix[source]

Return the sparse matrix associated with the active factorization path.

Returns:

Active sparse matrix.

Return type:

csc_matrix

get_stats() Dict[str, float][source]

Return factorization-handle statistics.

Returns:

Factorization-handle statistics.

Return type:

Dict[str, float]

solve_into(rhs: ndarray[tuple[Any, ...], dtype[float64]], out_solution: ndarray[tuple[Any, ...], dtype[float64]]) None[source]

Solve the factored sparse system into a caller-owned output buffer.

Parameters:
  • rhs (Vec) – Right-hand side vector.

  • out_solution (Vec) – Caller-owned output buffer.

Returns:

None.

Return type:

None

class VeraGridEngine.Utils.NumericalMethods.external_sparse_solver_interface.SparseLinearSolverBackend[source]

Bases: object

Abstract sparse linear solver backend used by EMT solvers.

The backend owns solver-specific symbolic and numeric reuse state. VeraGrid keeps the EMT policy for invalidation and event handling above this layer.

analyze(matrix: csc_matrix) Any | None[source]

Perform reusable symbolic analysis on the sparse matrix if supported.

Parameters:

matrix (csc_matrix) – Sparse matrix in EMT solver order.

Returns:

Symbolic-analysis handle or None.

Return type:

Any | None

factorize(matrix: csc_matrix, analysis_handle: Any | None) SparseLinearFactorizationHandle[source]

Build a sparse factorization handle for the current numeric values.

Parameters:
  • matrix (csc_matrix) – Sparse matrix in EMT solver order.

  • analysis_handle (Any | None) – Optional symbolic-analysis handle.

Returns:

Sparse factorization handle.

Return type:

SparseLinearFactorizationHandle

get_backend_stats() Dict[str, float][source]

Return backend-specific statistics.

Returns:

Backend-specific statistics.

Return type:

Dict[str, float]

get_name() str[source]

Return the human-readable backend name.

Returns:

Backend name.

Return type:

str

get_solver_type() SparseSolver[source]

Return the sparse solver type associated with this backend.

Returns:

Sparse solver type.

Return type:

SparseSolver

is_available() bool[source]

Return whether the backend can be used in the current process.

Returns:

True when the backend is available.

Return type:

bool

refactor_numeric(matrix: csc_matrix, analysis_handle: Any | None, previous_factorization: SparseLinearFactorizationHandle | None) SparseLinearFactorizationHandle | None[source]

Rebuild only the numeric factorization when supported.

Parameters:
  • matrix (csc_matrix) – Sparse matrix in EMT solver order.

  • analysis_handle (Any | None) – Optional symbolic-analysis handle.

  • previous_factorization (SparseLinearFactorizationHandle | None) – Previous factorization handle.

Returns:

New factorization handle or None when unsupported.

Return type:

SparseLinearFactorizationHandle | None

requires_csc() bool[source]

Return whether the backend expects CSC matrices.

Returns:

True when CSC input is required.

Return type:

bool

supports_numeric_refactorization() bool[source]

Return whether the backend supports numeric-only refactorization.

Returns:

True when numeric-only refactorization is supported.

Return type:

bool

supports_symbolic_analysis_reuse() bool[source]

Return whether the backend exposes reusable symbolic analysis.

Returns:

True when symbolic analysis can be reused.

Return type:

bool

class VeraGridEngine.Utils.NumericalMethods.external_sparse_solver_interface.SparseLinearSolverBackendProvider[source]

Bases: object

Factory object that creates EMT sparse solver backends.

create_backend(base_matrix: csc_matrix, base_data: ndarray[tuple[Any, ...], dtype[float64]]) SparseLinearSolverBackend[source]

Create one sparse backend bound to the EMT Jacobian buffers.

Parameters:
  • base_matrix (csc_matrix) – Reusable EMT Jacobian CSC shell.

  • base_data (Vec) – Reusable EMT Jacobian numeric buffer.

Returns:

Sparse solver backend.

Return type:

SparseLinearSolverBackend

get_name() str[source]

Return the provider name.

Returns:

Provider name.

Return type:

str

get_solver_type() SparseSolver[source]

Return the sparse solver type associated with the provider.

Returns:

Sparse solver type.

Return type:

SparseSolver

is_available() bool[source]

Return whether the provider is available.

Returns:

True when the provider is available.

Return type:

bool

VeraGridEngine.Utils.NumericalMethods.ips module

class VeraGridEngine.Utils.NumericalMethods.ips.IpsFunctionReturn(f: float, G: ndarray[tuple[Any, ...], dtype[float64]], H: ndarray[tuple[Any, ...], dtype[float64]], fx: ndarray[tuple[Any, ...], dtype[float64]], Gx: csc_matrix, Hx: csc_matrix, fxx: csc_matrix, Gxx: csc_matrix, Hxx: csc_matrix, S: ndarray[tuple[Any, ...], dtype[complex128]], Sf: ndarray[tuple[Any, ...], dtype[complex128]], St: ndarray[tuple[Any, ...], dtype[complex128]])[source]

Bases: object

Represents the returning value of the interior point evaluation

G: ndarray[tuple[Any, ...], dtype[float64]]
Gx: csc_matrix
Gxx: csc_matrix
H: ndarray[tuple[Any, ...], dtype[float64]]
Hx: csc_matrix
Hxx: csc_matrix
S: ndarray[tuple[Any, ...], dtype[complex128]]
Sf: ndarray[tuple[Any, ...], dtype[complex128]]
St: ndarray[tuple[Any, ...], dtype[complex128]]
compare(other: IpsFunctionReturn, h: float) Dict[str, float | ndarray[tuple[Any, ...], dtype[float64]] | csc_matrix][source]

Returns the comparison between this structure and another structure of this type :param other: IpsFunctionReturn :param h: finite differences step :return: Dictionary with the structure name and the difference

f: float
fx: ndarray[tuple[Any, ...], dtype[float64]]
fxx: csc_matrix
get_data() List[float | ndarray[tuple[Any, ...], dtype[float64]] | csc_matrix][source]

Returns the structures in a list :return: List of float, Vec, and csc

static get_headers() List[str][source]

Returns the structures’ names :return: list of str

class VeraGridEngine.Utils.NumericalMethods.ips.IpsSolution(x: ndarray[tuple[Any, ...], dtype[float64]], error: float, gamma: float, lam: ndarray[tuple[Any, ...], dtype[float64]], dlam: ndarray[tuple[Any, ...], dtype[float64]], mu: ndarray[tuple[Any, ...], dtype[float64]], z: ndarray[tuple[Any, ...], dtype[float64]], residuals: ndarray[tuple[Any, ...], dtype[float64]], structs: IpsFunctionReturn, converged: bool, iterations: int, error_evolution: ndarray[tuple[Any, ...], dtype[float64]])[source]

Bases: object

Represents the returning value of the interior point solution

converged: bool
dlam: ndarray[tuple[Any, ...], dtype[float64]]
error: float
error_evolution: ndarray[tuple[Any, ...], dtype[float64]]
gamma: float
iterations: int
lam: ndarray[tuple[Any, ...], dtype[float64]]
mu: ndarray[tuple[Any, ...], dtype[float64]]
plot_error()[source]

Plot the IPS error

residuals: ndarray[tuple[Any, ...], dtype[float64]]
structs: IpsFunctionReturn
x: ndarray[tuple[Any, ...], dtype[float64]]
z: ndarray[tuple[Any, ...], dtype[float64]]
VeraGridEngine.Utils.NumericalMethods.ips.calc_ccond(mu: ndarray[tuple[Any, ...], dtype[float64]], z: ndarray[tuple[Any, ...], dtype[float64]], x: ndarray[tuple[Any, ...], dtype[float64]])[source]
Parameters:
  • mu – Vector of mu mutipliers

  • z – Vector of z slack variables

  • x – State vector

Returns:

Vector of ccond

VeraGridEngine.Utils.NumericalMethods.ips.calc_error(dx, dz, dmu, dlmbda)[source]

Calculate the error of the process :param dx: x increments array :param dz: z increments array :param dmu: mu increments array :param dlmbda: lambda increments array :return: max abs value of all of the increments

VeraGridEngine.Utils.NumericalMethods.ips.calc_feascond(g: ndarray[tuple[Any, ...], dtype[float64]], h: ndarray[tuple[Any, ...], dtype[float64]], x: ndarray[tuple[Any, ...], dtype[float64]], z: ndarray[tuple[Any, ...], dtype[float64]])[source]

Calculate the feasible conditions :param g: Equality values :param h: Inequality values :param x: State vector :param z: Vector of z slack variables :return: Feasibility condition value

VeraGridEngine.Utils.NumericalMethods.ips.calc_gradcond(lx: ndarray[tuple[Any, ...], dtype[float64]], lam: ndarray[tuple[Any, ...], dtype[float64]], mu: ndarray[tuple[Any, ...], dtype[float64]])[source]

calculate the gradient conditions :param lx: Gradient of the lagrangian :param lam: Vector of lambda multipliers :param mu: Vector of mu multipliers :return: Gradient condition value

VeraGridEngine.Utils.NumericalMethods.ips.calc_ocond(f: float, f_prev: float)[source]
Parameters:
  • f – Value of objective funciton

  • f_prev – Previous value of objective function

Returns:

Variation of the objective function

VeraGridEngine.Utils.NumericalMethods.ips.interior_point_solver(x0: ndarray[tuple[Any, ...], dtype[float64]], n_x: int, n_eq: int, n_ineq: int, func: Callable[[ndarray[tuple[Any, ...], dtype[float64]], ndarray[tuple[Any, ...], dtype[float64]], ndarray[tuple[Any, ...], dtype[float64]], bool, bool, Any], IpsFunctionReturn], arg=(), max_iter=100, tol=1e-06, pf_init=False, trust=0.9, verbose: int = 0, step_control=False) Tuple[IpsSolution, ndarray[tuple[Any, ...], dtype[float64]]][source]

Solve a non-linear problem of the form:

min: f(x) s.t.

G(x) = 0 H(x) <= 0 xmin <= x <= xmax

The problem is specified by a function f_eval This function is called with (x, mu, lmbda) and returns (f, G, H, fx, Gx, Hx, fxx, Gxx, Hxx)

where:

x: array of variables lambda: Lagrange Multiplier associated with the inequality constraints pi: Lagrange Multiplier associated with the equality constraints f: objective function value (float) G: Array of equality mismatches (vec) H: Array of inequality mismatches (vec) fx: jacobian of f(x) (vec) Gx: Jacobian of G(x) (CSC mat) Hx: Jacobian of H(x) (CSC mat) fxx: Hessian of f(x) (CSC mat) Gxx: Hessian of G(x) (CSC mat) Hxx: Hessian of H(x) (CSC mat)

See: On Computational Issues of Market-Based Optimal Power Flow by

Hongye Wang, Carlos E. Murillo-SΓ‘nchez, Ray D. Zimmerman, and Robert J. Thomas IEEE TRANSACTIONS ON POWER SYSTEMS, VOL. 22, NO. 3, AUGUST 2007

Parameters:
  • x0 – Initial solution

  • n_x – Number of variables (size of x)

  • n_eq – Number of equality constraints (rows of H)

  • n_ineq – Number of inequality constraints (rows of G)

  • func – A function pointer called with (x, mu, lmbda, *args) that returns (f, G, H, fx, Gx, Hx, fxx, Gxx, Hxx)

  • arg – Tuple of arguments to call func: func(x, mu, lmbda, *arg)

  • max_iter – Maximum number of iterations

  • tol – Convergence tolerance

  • pf_init – Use the power flow solution as initial values

  • trust – Amount of trust in the initial Newton derivative length estimation

  • verbose – 0 to 3 (the larger, the more verbose)

  • step_control – Use step control to improve the solution process control

Returns:

IpsSolution

VeraGridEngine.Utils.NumericalMethods.ips.max_abs(x: ndarray[tuple[Any, ...], dtype[float64]])[source]

Compute max abs efficiently :param x: State vector :return: Inf-norm of the state vector

VeraGridEngine.Utils.NumericalMethods.ips.split(sol: ndarray[tuple[Any, ...], dtype[float64]], n: int)[source]

Split the solution vector in two :param sol: solution vector :param n: integer position at whic to split the solution :return: A before, B after the splitting point

VeraGridEngine.Utils.NumericalMethods.ips.step_calculation(v: ndarray[tuple[Any, ...], dtype[float64]], dv: ndarray[tuple[Any, ...], dtype[float64]], tau: float = 0.99995)[source]

This function calculates for each Lambda multiplier or its associated Slack variable the maximum allowed step in order to not violate the KKT condition Lambda > 0 and S > 0 :param v: Array of multipliers or slack variables :param dv: Variation calculated in the Newton step :param tau: Factor to be not exactly 1 :return: step size value for the given multipliers

VeraGridEngine.Utils.NumericalMethods.iwamoto module

VeraGridEngine.Utils.NumericalMethods.levenberg_marquadt module

VeraGridEngine.Utils.NumericalMethods.levenberg_marquadt.levenberg_marquardt(func: ~typing.Callable[[~numpy.ndarray[tuple[~typing.Any, ...], ~numpy.dtype[~numpy.float64]], bool, ~typing.Any], ~VeraGridEngine.Utils.NumericalMethods.common.ConvexFunctionResult], func_args: ~typing.Any, x0: ~numpy.ndarray[tuple[~typing.Any, ...], ~numpy.dtype[~numpy.float64]], tol: float = 1e-06, max_iter: int = 10, verbose: int = 0, logger: ~VeraGridEngine.basic_structures.Logger = <VeraGridEngine.basic_structures.Logger object>) ConvexMethodResult[source]

Levenberg-Marquardt to solve:

min: error(f(x)) s.t.

f(x) = 0

From METHODS FOR NON-LINEAR LEAST SQUARES PROBLEMS by K. Madsen, H.B. Nielsen, O. Tingleff

Parameters:
  • func – function to optimize, it may or may not include the Jacobian matrix the function must have x: Vec and calc_jacobian: bool as the first arguments the function must return an instance of ConvexFunctionResult that contains the function vector and optionally the derivative when calc_jacobian=True

  • func_args – Tuple of static arguments to call the evaluation function

  • x0 – Array of initial solutions

  • tol – Error tolerance

  • max_iter – Maximum number of iterations

  • verbose – Display console information

  • logger – Logger instance

Returns:

ConvexMethodResult

VeraGridEngine.Utils.NumericalMethods.newton_raphson module

VeraGridEngine.Utils.NumericalMethods.newton_raphson.newton_raphson(func: ~typing.Callable[[~numpy.ndarray[tuple[~typing.Any, ...], ~numpy.dtype[~numpy.float64]], bool, ~typing.Any], ~VeraGridEngine.Utils.NumericalMethods.common.ConvexFunctionResult], func_args: ~typing.Any, x0: ~numpy.ndarray[tuple[~typing.Any, ...], ~numpy.dtype[~numpy.float64]], tol: float = 1e-06, max_iter: int = 10, trust: float = 1.0, verbose: int = 0, logger: ~VeraGridEngine.basic_structures.Logger = <VeraGridEngine.basic_structures.Logger object>) ConvexMethodResult[source]

Newton-Raphson with Line search to solve:

min: error(g(x)) s.t.

g(x) = 0

Parameters:
  • func – function to optimize, it may or may not include the Jacobian matrix the function must have x: Vec and calc_jacobian: bool as the first arguments the function must return an instance of ConvexFunctionResult that contains the function vector and optionally the derivative when calc_jacobian=True

  • func_args – Tuple of static arguments to call the evaluation function

  • x0 – Array of initial solutions

  • tol – Error tolerance

  • max_iter – Maximum number of iterations

  • trust – trust amount in the derivative length correctness

  • verbose – Display console information

  • logger – Logger instance

Returns:

ConvexMethodResult

VeraGridEngine.Utils.NumericalMethods.newton_raphson_ode module

VeraGridEngine.Utils.NumericalMethods.non_dominated_sorting module

VeraGridEngine.Utils.NumericalMethods.non_dominated_sorting.crowding_distance(front: List[int], population: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]) ndarray[tuple[Any, ...], dtype[float64]][source]
Parameters:
  • front – list of integers representing the positions in the population matrix

  • population – Matrix of function evaluations (Npoints, NObjdim)

Returns:

VeraGridEngine.Utils.NumericalMethods.non_dominated_sorting.dominates(sol_a: ndarray[tuple[Any, ...], dtype[float64]], sol_b: ndarray[tuple[Any, ...], dtype[float64]])[source]

Check if a solution dominates another in the Pareto sense :param sol_a: Array representing the solution A (row of the population) :param sol_b: Array representing the solution B (row of the population) :return: A dominates B?

VeraGridEngine.Utils.NumericalMethods.non_dominated_sorting.get_non_dominated_fronts(population: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]) List[List[int]][source]

2D non dominated sorting :param population: matrix (n points, ndim) :return: Fronts ordered by position (front 1, front 2, Front 3, …)

Each front is a list of integers representing the positions in the population matrix

VeraGridEngine.Utils.NumericalMethods.non_dominated_sorting.non_dominated_sorting(y_values: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], x_values: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]) Tuple[ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], ndarray[tuple[Any, ...], dtype[int64]]][source]

Use non dominated sorting and crowded sorting to sort the multidimensional objectives :param y_values: Matrix of function evaluations (Npoints, NObjdim) :param x_values: Matrix of values (Npoints, Ndim) :return: Return the pareto y and matching x. The pareto front may have less values than the population

[Sorted population, Sorted input values (X)]

VeraGridEngine.Utils.NumericalMethods.non_dominated_sorting.sort_by_crowding(fronts: List[List[int]], population: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]) Tuple[ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], ndarray[tuple[Any, ...], dtype[int64]]][source]
Parameters:
  • fronts – Fronts ordered by position (front 1, front 2, Front 3, …) Each front is a list of integers representing the positions in the population matrix

  • population – Matrix of function evaluations (Npoints, NObjdim)

Returns:

sorted population, array of sorting indices

VeraGridEngine.Utils.NumericalMethods.nsga3 module

VeraGridEngine.Utils.NumericalMethods.nsga3.associate_to_reference_points(front: ndarray, ref_points: ndarray) ndarray[source]
Parameters:
  • front

  • ref_points

Returns:

VeraGridEngine.Utils.NumericalMethods.nsga3.crossover(parent1: ndarray, parent2: ndarray, crossover_rate: float = 0.9) Tuple[ndarray, ndarray][source]
Parameters:
  • parent1

  • parent2

  • crossover_rate

Returns:

VeraGridEngine.Utils.NumericalMethods.nsga3.evaluate_population(population: ndarray) ndarray[source]
Parameters:

population

Returns:

VeraGridEngine.Utils.NumericalMethods.nsga3.generate_recursive(dim: int, left: int, total: int, result: ndarray, current: ndarray, index: int) int[source]
Parameters:
  • dim

  • left

  • total

  • result

  • current

  • index

Returns:

VeraGridEngine.Utils.NumericalMethods.nsga3.generate_reference_points(n_obj: int, n_partitions: int) ndarray[source]
Parameters:
  • n_obj

  • n_partitions

Returns:

VeraGridEngine.Utils.NumericalMethods.nsga3.initialize_population(pop_size: int, bounds: ndarray) ndarray[source]
Parameters:
  • pop_size

  • bounds

Returns:

VeraGridEngine.Utils.NumericalMethods.nsga3.mutation(individual: ndarray, bounds: ndarray, mutation_rate: float = 0.1) ndarray[source]
Parameters:
  • individual

  • bounds

  • mutation_rate

Returns:

VeraGridEngine.Utils.NumericalMethods.nsga3.niching(front: ndarray, ref_points: ndarray, pop_size: int) ndarray[source]
Parameters:
  • front

  • ref_points

  • pop_size

Returns:

VeraGridEngine.Utils.NumericalMethods.nsga3.nsga3(n_obj: int, pop_size: int, generations: int, n_partitions: int, bounds: ndarray)[source]
Parameters:
  • n_obj

  • pop_size

  • generations

  • n_partitions

  • bounds

Returns:

VeraGridEngine.Utils.NumericalMethods.nsga3.objective_1(x: ndarray) float[source]
Parameters:

x

Returns:

VeraGridEngine.Utils.NumericalMethods.nsga3.objective_2(x: ndarray) float[source]
Parameters:

x

Returns:

VeraGridEngine.Utils.NumericalMethods.nsga3.tournament_selection(population: ndarray, objectives: ndarray, k: int = 2) ndarray[source]
Parameters:
  • population

  • objectives

  • k

Returns:

VeraGridEngine.Utils.NumericalMethods.numerical_stability module

VeraGridEngine.Utils.NumericalMethods.numerical_stability.sparse_instability_lu_test(A: csc_matrix, condition_number_thrshold: float = 1e-07)[source]
Parameters:
  • A – The sparse coefficient matrix

  • condition_number_thrshold – small number (ie. 1e-7)

Returns:

condition_number (float): The condition number of the matrix unstable (bool): β€˜stable’ or β€˜unstable’ based on the condition number

VeraGridEngine.Utils.NumericalMethods.numerical_stability.sparse_instability_svd_test(A: csc_matrix, condition_number_thrshold: float = 10000000.0)[source]

Test for numerical instability of a sparse matrix A by calculating its condition number. :param A: The sparse coefficient matrix :param condition_number_thrshold: big number (1e7) :return: condition_number (float): The condition number of the matrix

unstable (bool): β€˜stable’ or β€˜unstable’ based on the condition number

VeraGridEngine.Utils.NumericalMethods.powell module

VeraGridEngine.Utils.NumericalMethods.powell.compute_beta(a: ndarray[tuple[Any, ...], dtype[float64]], b: ndarray[tuple[Any, ...], dtype[float64]], delta)[source]

compute the beta parameter :param a: alpha + hsd :param b: hgn :param delta: :return:

VeraGridEngine.Utils.NumericalMethods.powell.compute_hdl(hgn: ndarray[tuple[Any, ...], dtype[float64]], hsd: ndarray[tuple[Any, ...], dtype[float64]], g: ndarray[tuple[Any, ...], dtype[float64]], alpha: float, delta: float, f_error: float) ndarray[tuple[Any, ...], dtype[float64]][source]

Compute the Hdl vector :param hgn: Hgn vector :param hsd: Hsd vector :param g: g vector :param alpha: alpha parameter :param delta: delta parameter (trust region size) :param f_error: error of the function top optimize :return: Hdl Vector, L(0) - L(hdl)

VeraGridEngine.Utils.NumericalMethods.powell.powell_dog_leg(func: ~typing.Callable[[~numpy.ndarray[tuple[~typing.Any, ...], ~numpy.dtype[~numpy.float64]], bool, ~typing.Any], ~VeraGridEngine.Utils.NumericalMethods.common.ConvexFunctionResult], func_args: ~typing.Any, x0: ~numpy.ndarray[tuple[~typing.Any, ...], ~numpy.dtype[~numpy.float64]], tol: float = 1e-06, max_iter: int = 10, trust_region_radius: float = 10.0, verbose: int = 0, logger: ~VeraGridEngine.basic_structures.Logger = <VeraGridEngine.basic_structures.Logger object>) ConvexMethodResult[source]

Powell’s Dog leg algorithm to solve:

min: error(f(x)) s.t.

f(x) = 0

From METHODS FOR NON-LINEAR LEAST SQUARES PROBLEMS by K. Madsen, H.B. Nielsen, O. Tingleff

Parameters:
  • func – function to optimize, it may or may not include the Jacobian matrix the function must have x: Vec and calc_jacobian: bool as the first arguments the function must return an instance of ConvexFunctionResult that contains the function vector and optionally the derivative when calc_jacobian=True

  • func_args – Tuple of static arguments to call the evaluation function

  • x0 – Array of initial solutions

  • tol – Error tolerance

  • max_iter – Maximum number of iterations

  • trust_region_radius – radius of the trust region (i.e. 1.0)

  • verbose – Display console information

  • logger – Logger instance

Returns:

ConvexMethodResult

VeraGridEngine.Utils.NumericalMethods.sparse_solve module

VeraGridEngine.Utils.NumericalMethods.sparse_solve.get_linear_solver(solver_type: SparseSolver = SuperLU) Callable[[csc_matrix, ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]], ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]][source]

Privide the chosen linear solver_type function pointer to solver_type linear systems of the type A x = b, with x = f(A,b) :param solver_type: SparseSolver option :return: function pointer f(A, b)

VeraGridEngine.Utils.NumericalMethods.sparse_solve.get_sparse_type(solver_type: SparseSolver = SuperLU)[source]

GEt sparse matrix type matching the selected sparse linear systems solver :param solver_type: :return: sparse matrix type

VeraGridEngine.Utils.NumericalMethods.sparse_solve.gmres_linsolve(A: csc_matrix, b: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]) ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]][source]
Parameters:
  • A

  • b

Returns:

VeraGridEngine.Utils.NumericalMethods.sparse_solve.ilu_linsolver(A: csc_matrix, b: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]) ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]][source]

ILU wrapper function for linear system solve A x = b :param A: System matrix :param b: right hand side :return: solution

VeraGridEngine.Utils.NumericalMethods.sparse_solve.klu_linsolve(A: csc_matrix, b: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]) ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]][source]

KLU wrapper function for linear system solve A x = b :param A: System matrix :param b: right hand side :return: solution

VeraGridEngine.Utils.NumericalMethods.sparse_solve.super_lu_linsolver(A: csc_matrix, b: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]]) ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]][source]

SuperLU wrapper function for linear system solve A x = b :param A: System matrix :param b: right hand side :return: solution

VeraGridEngine.Utils.NumericalMethods.weldorf_online_stddev module

class VeraGridEngine.Utils.NumericalMethods.weldorf_online_stddev.WeldorfOnlineStdDevMat(nrow: int, ncol: int)[source]

Bases: object

Weldorf’s algorithm for online computation of the variance

M2
count
finalize() None[source]

Finalize: compute the variance and std dev

mean
sample_variance
std_dev
steps
update(t: int, new_value: ndarray[tuple[Any, ...], dtype[float64]])[source]

For a new value new_value, compute the new count, new mean, the new M2. mean accumulates the mean of the entire dataset M2 aggregates the squared distance from the mean count aggregates the number of samples seen so far :param t: Row index :param new_value: array of column values

variance
VeraGridEngine.Utils.NumericalMethods.weldorf_online_stddev.finalize(count: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], variance: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], M2: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], std_dev: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], sample_variance: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]])[source]
Parameters:
  • count

  • variance

  • M2

  • std_dev

  • sample_variance

Returns:

VeraGridEngine.Utils.NumericalMethods.weldorf_online_stddev.update(i: int, new_value: ndarray[tuple[Any, ...], dtype[float64]], count: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], mean: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]], M2: ndarray[tuple[Any, ...], dtype[float64]] | ndarray[tuple[int, int], dtype[float64]])[source]
Parameters:
  • i

  • new_value

  • count

  • mean

  • M2

Module contents