mealpy.utils package¶
mealpy.utils.agent module¶
- class mealpy.utils.agent.Agent(solution: Optional[numpy.ndarray] = None, target: Optional[mealpy.utils.target.Target] = None, **kwargs)[source]¶
Bases:
object
- ID = 0¶
- compare_duplicate(compared_agent: mealpy.utils.agent.Agent) bool [source]¶
- get_better_solution(compared_agent: mealpy.utils.agent.Agent, minmax: str = 'min') mealpy.utils.agent.Agent [source]¶
- is_better_than(compared_agent: mealpy.utils.agent.Agent, minmax: str = 'min') bool [source]¶
- is_duplicate(compared_agent: mealpy.utils.agent.Agent) bool [source]¶
- update_agent(solution: numpy.ndarray, target: mealpy.utils.target.Target) None [source]¶
mealpy.utils.history module¶
- class mealpy.utils.history.History(**kwargs)[source]¶
Bases:
object
A History class is responsible for saving each iteration’s output.
Notes
- Access to variables in this class:
list_global_best: List of global best SOLUTION found so far in all previous generations
list_current_best: List of current best SOLUTION in each previous generations
list_epoch_time: List of runtime for each generation
list_global_best_fit: List of global best FITNESS found so far in all previous generations
list_current_best_fit: List of current best FITNESS in each previous generations
list_diversity: List of DIVERSITY of swarm in all generations
list_exploitation: List of EXPLOITATION percentages for all generations
list_exploration: List of EXPLORATION percentages for all generations
list_global_worst: List of global worst SOLUTION found so far in all previous generations
list_current_worst: List of current worst SOLUTION in each previous generations
list_population: List of POPULATION in each generations
- Warning, the last variable ‘list_population’ can cause the error related to ‘memory’ when saving model.
Better to set parameter ‘save_population’ to False in the input problem dictionary to not using it.
- There are 8 methods to draw available in this class:
save_global_best_fitness_chart()
save_local_best_fitness_chart()
save_global_objectives_chart()
save_local_objectives_chart()
save_exploration_exploitation_chart()
save_diversity_chart()
save_runtime_chart()
save_trajectory_chart()
Examples
>>> import numpy as np >>> from mealpy import FloatVar, BBO >>> >>> def objective_function(solution): >>> return np.sum(solution**2) >>> >>> p1 = { >>> "bounds": FloatVar(n_vars=30, lb=(-10.,) * 30, ub=(10.,) * 30, name="delta"), >>> "minmax": "min", >>> "obj_func": objective_function, >>> "save_population": True, # To be able to draw the trajectory figure >>> "name": "Test Function" >>> } >>> model = BBO.OriginalBBO(epoch=1000, pop_size=50) >>> model.solve(p1) >>> >>> model.history.save_global_objectives_chart(filename="hello/goc") >>> model.history.save_local_objectives_chart(filename="hello/loc") >>> model.history.save_global_best_fitness_chart(filename="hello/gbfc") >>> model.history.save_local_best_fitness_chart(filename="hello/lbfc") >>> model.history.save_runtime_chart(filename="hello/rtc") >>> model.history.save_exploration_exploitation_chart(filename="hello/eec") >>> model.history.save_diversity_chart(filename="hello/dc") >>> model.history.save_trajectory_chart(list_agent_idx=[3, 5], selected_dimensions=[3], filename="hello/tc") >>> >>> ## Get list of global best solution after all generations >>> print(model.history.list_global_best)
- save_diversity_chart(title='Diversity Measurement Chart', algorithm_name='Algorithm', filename='diversity-chart', verbose=True)[source]¶
- save_exploration_exploitation_chart(title='Exploration vs Exploitation Percentages', list_colors=('blue', 'orange'), filename='exploration-exploitation-chart', verbose=True)[source]¶
- save_global_best_fitness_chart(title='Global Best Fitness', legend=None, linestyle='-', color='b', x_label='#Iteration', y_label='Function Value', filename='global-best-fitness-chart', exts=('.png', '.pdf'), verbose=True)[source]¶
- save_global_objectives_chart(title='Global Objectives Chart', x_label='#Iteration', y_labels=None, filename='global-objectives-chart', verbose=True)[source]¶
- save_local_best_fitness_chart(title='Local Best Fitness', legend=None, linestyle='-', color='b', x_label='#Iteration', y_label='Function Value', filename='local-best-fitness-chart', exts=('.png', '.pdf'), verbose=True)[source]¶
- save_local_objectives_chart(title='Local Objectives Chart', x_label='#Iteration', y_labels=None, filename='local-objectives-chart', verbose=True)[source]¶
- save_runtime_chart(title='Runtime chart', legend=None, linestyle='-', color='b', x_label='#Iteration', y_label='Second', filename='runtime-chart', exts=('.png', '.pdf'), verbose=True)[source]¶
- save_trajectory_chart(title='Trajectory of some agents', list_agent_idx=(1, 2, 3, 4, 5), selected_dimensions=(1, 2), filename='trajectory-chart', verbose=True)[source]¶
- store_initial_best_worst(best_agent: mealpy.utils.agent.Agent, worst_agent: mealpy.utils.agent.Agent) None [source]¶
mealpy.utils.io module¶
mealpy.utils.logger module¶
mealpy.utils.problem module¶
- class mealpy.utils.problem.Problem(bounds: Union[List, Tuple, numpy.ndarray, mealpy.utils.space.BaseVar], minmax: str = 'min', **kwargs)[source]¶
Bases:
object
- SUPPORTED_ARRAYS = (<class 'list'>, <class 'tuple'>, <class 'numpy.ndarray'>)¶
- SUPPORTED_VARS = (<class 'mealpy.utils.space.IntegerVar'>, <class 'mealpy.utils.space.FloatVar'>, <class 'mealpy.utils.space.PermutationVar'>, <class 'mealpy.utils.space.StringVar'>, <class 'mealpy.utils.space.BinaryVar'>, <class 'mealpy.utils.space.BoolVar'>, <class 'mealpy.utils.space.MixedSetVar'>)¶
- property bounds¶
- correct_solution(x: numpy.ndarray) numpy.ndarray [source]¶
Correct the solution to valid bounds
- Parameters
x (np.ndarray) – The real-value solution
- Returns
The corrected solution
- static correct_solution_with_bounds(x: Union[List, Tuple, numpy.ndarray], bounds: List) numpy.ndarray [source]¶
- decode_solution(x: numpy.ndarray) Dict [source]¶
Decode the encoded solution to real-world solution
- Parameters
x (np.ndarray) – The real-value solution
- Returns
The real-world (decoded) solution
- encode_solution(x: Union[List, tuple, numpy.ndarray]) numpy.ndarray [source]¶
Encode the real-world solution to optimized solution (real-value solution)
- Parameters
x (Union[List, tuple, np.ndarray]) – The real-world solution
- Returns
The real-value solution
- generate_solution(encoded: bool = True) Union[List, numpy.ndarray] [source]¶
Generate the solution.
- Parameters
encoded (bool) – Encode the solution or not
- Returns
the encoded/non-encoded solution for the problem
- static generate_solution_with_bounds(bounds: Union[List, Tuple, numpy.ndarray], encoded: bool = True) Union[List, numpy.ndarray] [source]¶
- get_target(solution: numpy.ndarray) mealpy.utils.target.Target [source]¶
- Parameters
solution – The real-value solution
- Returns
The target object
mealpy.utils.space module¶
- class mealpy.utils.space.BaseVar(name='variable')[source]¶
Bases:
abc.ABC
- SUPPORTED_ARRAY = [<class 'tuple'>, <class 'list'>, <class 'numpy.ndarray'>]¶
- property seed¶
- class mealpy.utils.space.BinaryVar(n_vars=1, name='binary')[source]¶
Bases:
mealpy.utils.space.BaseVar
- class mealpy.utils.space.BoolVar(n_vars=1, name='boolean')[source]¶
Bases:
mealpy.utils.space.BaseVar
- class mealpy.utils.space.FloatVar(lb=- 10.0, ub=10.0, name='float')[source]¶
Bases:
mealpy.utils.space.BaseVar
- class mealpy.utils.space.IntegerVar(lb=- 10, ub=10, name='integer')[source]¶
Bases:
mealpy.utils.space.BaseVar
- class mealpy.utils.space.LabelEncoder[source]¶
Bases:
object
Encode categorical features as integer labels. Especially, it can encode a list of mixed types include integer, float, and string. Better than scikit-learn module.
- fit_transform(y)[source]¶
Fit label encoder and return encoded labels.
- Parameters
y (list, tuple) – Target values.
- Returns
y – Encoded labels.
- Return type
list
- class mealpy.utils.space.MixedSetVar(valid_sets=(('',),), name='mixed-set-var')[source]¶
Bases:
mealpy.utils.space.StringVar
- class mealpy.utils.space.PermutationVar(valid_set=(1, 2), name='permutation')[source]¶
Bases:
mealpy.utils.space.BaseVar
- class mealpy.utils.space.StringVar(valid_sets=(('',),), name='string')[source]¶
Bases:
mealpy.utils.space.BaseVar
- class mealpy.utils.space.TransferBinaryVar(n_vars=1, name='tf-binary', tf_func='vstf_01', lb=- 8.0, ub=8.0, all_zeros=True)[source]¶
Bases:
mealpy.utils.space.BinaryVar
- SUPPORTED_TF_FUNCS = ['vstf_01', 'vstf_02', 'vstf_03', 'vstf_04', 'sstf_01', 'sstf_02', 'sstf_03', 'sstf_04']¶
mealpy.utils.target module¶
- class mealpy.utils.target.Target(objectives: Optional[Union[List, Tuple, numpy.ndarray, int, float]] = None, weights: Optional[Union[List, Tuple, numpy.ndarray]] = None)[source]¶
Bases:
object
- SUPPORTED_ARRAY = [<class 'tuple'>, <class 'list'>, <class 'numpy.ndarray'>]¶
- calculate_fitness(weights: Union[List, Tuple, numpy.ndarray]) None [source]¶
Calculates the fitness value of the solution based on the provided weights.
- Parameters
weights (list) – The weights for the objectives.
- Returns
The fitness value of the solution.
- Return type
float
- property fitness¶
Returns the fitness value.
- property objectives¶
Returns the list of objective values.
- property weights¶
Returns the list of weight values.
mealpy.utils.termination module¶
- class mealpy.utils.termination.Termination(max_epoch=None, max_fe=None, max_time=None, max_early_stop=None, **kwargs)[source]¶
Bases:
object
Define custom single/multiple Stopping Conditions (termination criteria) for the Optimizer.
Notes
By default, the stopping condition in the Optimizer class is based on the maximum number of generations (epochs/iterations).
Using this class allows you to override the default termination criteria. If multiple stopping conditions are specified, the first one that occurs will be used.
- In general, there are four types of termination criteria: FE, MG, TB, and ES.
MG: Maximum Generations / Epochs / Iterations
FE: Maximum Number of Function Evaluations
TB: Time Bound - If you want your algorithm to run for a fixed amount of time (e.g., K seconds), especially when comparing different algorithms.
ES: Early Stopping - Similar to the idea in training neural networks (stop the program if the global best solution has not improved by epsilon after K epochs).
- Parameters for Termination class, set it to None if you don’t want to use it
max_epoch (int): Indicates the maximum number of generations for the MG type.
max_fe (int): Indicates the maximum number of function evaluations for the FE type.
max_time (float): Indicates the maximum amount of time for the TB type.
- max_early_stop (int): Indicates the maximum number of epochs for the ES type.
epsilon (float): (Optional) This is used for the ES termination type (default value: 1e-10).
termination (dict): (Optional) A dictionary of termination criteria.
Examples
>>> import numpy as np >>> from mealpy import FloatVar, BBO >>> >>> def objective_function(solution): >>> return np.sum(solution**2) >>> >>> p1 = { >>> "bounds": FloatVar(n_vars=30, lb=(-10.,) * 30, ub=(10.,) * 30, name="C-params"), >>> "minmax": "min", >>> "obj_func": objective_function, >>> "name": "Test Function" >>> } >>> >>> term_dict = { >>> "max_epoch": 1000, >>> "max_fe": 100000, # 100000 number of function evaluation >>> "max_time": 10, # 10 seconds to run the program >>> "max_early_stop": 15 # 15 epochs if the best fitness is not getting better we stop the program >>> } >>> model1 = BBO.OriginalBBO(epoch=1000, pop_size=50) >>> model1.solve(p1, termination=term_dict)