cbx.dynamics.ParticleDynamic#
- class cbx.dynamics.ParticleDynamic(f, f_dim='1D', check_f_dims=True, x=None, M=1, N=20, d=None, max_it=1000, term_criteria=None, track_args=None, verbosity=1, copy=None, norm=None, sampler=None, post_process=None, seed=None)[source]#
Bases:
object
The base particle dynamic class
This class implements the base particle dynamic class. This class does not implement any functionality that is specific to consensus schemes. The only necessary argument is the objective function \(f\). The objective can be given as a simple callable function. It is assumed to be a function \(f:\mathbb{R}^{d}\to\mathbb{R}\). If the objective can handle arrays of shape \((N, d)\), i.e., it can be applied to multiple particles, then you can use the argument
f_dim=2D
, or analogouslyf_dim=3D
, if it can handle arrays of shape \((M, N, d)\). You can also directly provide the objective function as acbx_objective
instance.During the initialization of the class, the dimension of the output is checked using the
check_f_dims()
method. If the check fails, an error is raised. This check can be turned off by setting thecheck_f_dims
parameter toFalse
.The ensemble of particles is modeled as an array of shape \((M, N, d)\) where
\(M\) is the number of runs that should be performed. In many cases, multiple runs can be implmented on the
numpy
array level, which allows for efficient evaluations and computations avoiding for loops.\(N\) is the number of particles in each run.
\(d\) is the dimension of the system.
This means that \(x_{m,n}\in\mathbb{R}^{d}\) denotes the position of the \(n\)-th particle of the \(m\)-th run.
Promoting the objective function \(f\) to the
cbx_objective
instance \(\tilde{f}\) allows for the evaluation on ensembles of the shape \((M, N, d)\), namely,\[\tilde{f}(x)_{m,n} := f(x_{m,n,:})\]The class can not infer the dimension of the problem. Therfore, the dimension must be specified by the parameter
d
or by specifiying an inintial position arrayx
.- Parameters:
f (Callable) – The objective function \(f\) of the system.
f_dim (str, optional) – The dimensionality of the objective function. The default is ‘1D’.
check_f_dims (bool, optional) – If
True
, the dimension of the objective function is checked. The default isTrue
.x (array_like, shape (M, N, d) or None, optional) – The initial positions of the particles. For a system of \(N\) particles
x[m, n, :]
represents the position n-th particle of the m-th run.x_min (float, optional) – The minimum value of the initial positions. The default is -1.
x_max (float, optional) – The maximum value of the initial positions. The default is 1.
M (int, optional) – The number of runs. The default is 1.
N (int, optional) – The number of particles in each run. The default is 20.
d (int or None, optional) – The dimension of the system. The default is None.
term_criteria (list[Callable], optional) – A list of callables that determine the termination of the optimization. Each callable in the list should accept a single argument (the dynamic object) and return a numpy array of size (M,), where term(dyn)[i] specifies, whether the optimization should be terminated for the i-th run.
track_args (dict) –
The arguments for the tracking certain objects in the history. The following keys are possible:
- ’names’list
The names of the objects that should be tracked.
- ’save_int’int
The frequency of the saving of the data. The default is 1.
- ’extra_tracks’list
A list of extra tracks that should be performed. Each object in this list must have init_history and an update method.
post_process (Callable) – A callbale acting on the dynamic that should be performed after each optimization step.
copy (Callable) – A callable that copies an array. The default is
np.copy
.norm (Callable) – A callable that computes the norm of an array. The default is
np.linalg.norm
.sampler (Callable) – A callable that generates an array of random numbers. The default is
np.random.normal
.verbosity (int, optional) – The verbosity level. The default is 1.
- init_x(x, M, N, d)[source]#
Initialize the particle system with the given parameters.
- Parameters:
x – the initial particle system. If x is None, the dimension d must be specified and the particle system is initialized randomly. If x is specified, it is broadcasted to the correct shape (M,N,d).
M – the number of particles in the first dimension
N – the number of particles in the second dimension
d – the dimension of the particle system
x_min – the minimum value for x
x_max – the maximum value for x
- Returns:
None
- check_f_dims(check=True)[source]#
Check the dimensions of the objective function output.
- Parameters:
check (bool) – Flag indicating whether to perform the dimension check. Default is True.
- Returns:
None
- pre_step()[source]#
The pre-step function. This function is used in meth:step before the inner step is performed. This function can be overwritten by subclasses to perform any pre-steps before the inner step.
- Parameters:
None
- Returns:
None
- inner_step()[source]#
This function is used in meth:step to perform the inner step. This function implements the actual update of the dynamic and is therfore the most important function in the dynamics class. This function should be overwritten by subclasses to perform any inner steps.
- Parameters:
None
- Returns:
None
- post_step()[source]#
Execute the post-step operations after each iteration.
This function updates the difference between the current particle position and the previous particle position if the ‘x_old’ attribute exists in the object. The difference is computed using the numpy.linalg.norm function along the specified axes and is divided by the total number of particles.
The function then calls the ‘update_best_cur_particle’ method to update the best current particle position. Next, it calls the ‘update_best_particle’ method to update the best particle position. After that, it calls the ‘track’ method to track the progress of the optimization algorithm. Then, it calls the ‘process_particles’ method to perform any necessary post-processing operations on the particles.
Finally, the function increments the ‘it’ attribute by 1 to keep track of the current iteration.
- Parameters:
None
- Returns:
None
- step()[source]#
Execute a step in the dynamic.
This function performs the following actions: 1. Calls the pre_step method to perform any necessary pre-step operations. 2. Calls the inner_step method to perform the main step operation. 3. Calls the post_step method to perform any necessary post-step operations.
- Parameters:
None
- Returns:
None
- default_sched()[source]#
Returns the default scheduler for a dynamic.
- Parameters:
None
- Returns:
The scheduler object.
- Return type:
- optimize(print_int=None, sched='default')[source]#
Optimize the function using the dynmaic. This function perfoms the iterations as specified by step method and the update in
inner_step()
.- Parameters:
print_int – int, optional The interval at which to print the current state of the optimization. If not provided, the default value is used. Defaults to None.
sched – str The scheduler to use for the optimization. If set to ‘default’, the default scheduler is used. If set to None, a scheduler is created based on the current optimization parameters. Defaults to ‘default’.
- Returns:
The best particle found during the optimization process.
- Return type:
best_particle
- print_post_opt()[source]#
Print the optimization results if the verbosity level is greater than 0.
This function prints the solver’s finishing message, the best energy found during optimization.
- Parameters:
None
- Returns:
None
- reset()[source]#
Reset the state of the object.
This function sets the value of the object’s ‘it’ attribute to 0 and calls the ‘init_history()’ method to re-initialize the history of the object.
- Parameters:
self (object) – The object instance.
- Returns:
None
- init_term(term_criteria, max_it)[source]#
Initialize the termination criteria of the object.
This function sets the value of the object’s ‘it’ attribute to 0 and calls the ‘init_history()’ method to re-initialize the history of the object.
- Parameters:
checks (list)
- select_active_runs()[source]#
Selects the inidices that meet a termination criterion.
- Parameters:
None
- Returns:
True if all checks passed, False otherwise.
- Return type:
bool
- init_history(track_args)[source]#
Initialize the history dictionary and initialize the specified tracking keys.
- Parameters:
None
- Returns:
None
- update_best_cur_particle()[source]#
Updates the best current particle and its energy based on the minimum energy found in the energy matrix.
- Parameters:
None
- Returns:
None