Solution
Solution class
|
It is the default and unique, constructor builds an empty solution with the worst fitness value (\(best=False\), by default) or the best fitness value (\(best=False\)). |
It obtains the defined variables which constitutes the solution. |
|
It obtains the defined Domain from the solution. |
|
|
Sets the value of a variable in the solution. |
|
Returns the value of a variable in the solution. |
Get the connector used by the Solution. |
|
|
Evaluate the fitness of the Solution using the provided fitness function. |
|
Set the fitness of the Solution to the given value. |
Get the fitness value of the Solution. |
|
|
Get the keys of the solution value dict. |
|
Get the values of the solution value dict. |
|
Checks if a variable is available in the solution. |
Initializes the solution with rs values defined in its domain. |
|
|
Modify a rs subset of the solution's variables calling its mutate method. |
- class Solution(definition: Domain | BaseDefinition, best=False, connector=None)
Base abstract class representing a solution in an optimization problem.
This class provides a generic framework for representing and manipulating solutions in various optimization algorithms. It supports key operations such as fitness evaluation, mutation, crossover, and variable management.
- Parameters:
definition (Domain | BaseDefinition) – The Domain of the solution. If the definition is an instance of Base the connector must be provided.
best (bool) – If True the individual will be built with the best fitness function; otherwise the worst, defaults to False.
connector (BaseConnector) – The connector to be used by the class, if None the definition must be a Domain instance.
- Variables:
connector (BaseConnector) – The connector used by the Solution.
value (Dict[str, BaseType]) – The defined variables which constitutes the solution.
fitness (float) – The fitness value of the Solution.
__definition (BaseDefinition) – The defined Domain from the solution.
Example
>>> from metagen.framework import Domain, Solution >>> domain = Domain() >>> domain.define_integer('example', 0, 10) >>> best_solution = Solution(domain, best=True) >>> best_solution.fitness 0.0 >>> best_solution F = 0 {example = 3} >>> worst_solution = Solution(domain) >>> worst_solution.fitness 1.7976931348623157e+308 >>> worst_solution F = 1.7976931348623157e+308 {example = 5} >>> boosted_solution = Solution(domain) >>> boosted_solution F = 1.7976931348623157e+308 {example = 1}
It is the default and unique, constructor builds an empty solution with the worst fitness value (\(best=False\), by default) or the best fitness value (\(best=False\)). Furthermore, a
Domainobject can be passed to check the variable definitions internally and, therefore boost the Solution fucntionality.- Parameters:
definition (Domain | BaseDefinition) – The Domain of the solution. If the definition is an instance of Base the connector must be provided.
best (bool) – If True the individual will be built with the best fitness function; otherwise the worst, defaults to False.
connector (BaseConnector) – The connector to be used by the class, if None the definition must be a Domain instance.
- get_variables() Dict[str, BaseType]
It obtains the defined variables which constitutes the solution.
- Returns:
The defined variables.
- Return type:
Dict[str, BaseType]
- get_definition() BaseDefinition
It obtains the defined Domain from the solution.
- Returns:
The defined Domain.
- Return type:
- set(variable: str, value: InputValue | types.BaseType) None
Sets the value of a variable in the solution.
- Parameters:
variable (str) – The name of the variable to set.
value (InputValue) – The value to set the variable to.
- Raises:
TypeError – If the value’s type is not supported by the solution.
Note
This method sets the value of a variable in the solution. The type of the value determines how the variable is stored internally. If the value is an integer, it is stored as an integer variable. If it is a float, it is stored as a real variable. If it is a string, it is stored as a categorical variable. If it is a list, it is stored as a vector variable. If it is a dictionary, it is stored as a sub-solution variable. If it is any other type, it must be a pre-defined type for compatibility with previously defined solutions.
See also
- get(variable: str) BaseType
Returns the value of a variable in the solution.
- Parameters:
variable (str) – The name of the variable to get.
- Returns:
The value of the variable.
- Return type:
InputValue
Note
This method returns the value of a variable in the solution. The type of the value depends on how the variable is stored internally. If it is an integer variable, the method returns an integer. If it is a real variable, it returns a float. If it is a categorical variable, it returns a string. If it is a vector variable, it returns a list. If it is a sub-solution variable, it returns a dictionary.
See also
- get_connector() BaseConnector
Get the connector used by the Solution.
- Returns:
The connector object.
- Return type:
- evaluate(fitness_func: Callable[[Solution], float]) None
Evaluate the fitness of the Solution using the provided fitness function.
- Parameters:
fitness_func (Callable[[Solution], float]) – The fitness function to evaluate the object’s fitness.
- Returns:
None
- set_fitness(fitness: float) None
Set the fitness of the Solution to the given value.
- Parameters:
fitness (float) – The fitness value to set.
- Returns:
None
- get_fitness() float
Get the fitness value of the Solution.
- Returns:
The fitness value.
- Return type:
float
- is_available(variable: str) bool
Checks if a variable is available in the solution.
- Parameters:
variable (str) – The name of the variable to check.
- Returns:
True if the variable is available, False otherwise.
- Return type:
bool
Note
This method checks if a variable is available in the solution. It returns True if the variable is present in the solution’s variables, and False otherwise.
See also
- keys() KeysView
Get the keys of the solution value dict.
- Returns:
A KeysView with the keys of the solution
- values() ValuesView
Get the values of the solution value dict.
- Returns:
A ValuesView with the keys of the solution
- initialize()
Initializes the solution with rs values defined in its domain.
Note
This method initializes the solution with rs values within its domain. It iterates through all the variables in the domain and generates a rs value according to their definition. The generated value is then set as the initial value of the variable in the solution.
See also
- mutate(alterations_number: int = None, alteration_limit: Any = None)
Modify a rs subset of the solution’s variables calling its mutate method.
- Parameters:
alterations_number (int, optional) – The number of variables to mutate at the first level. If not specified, a rs number between 1 and the total number of variables will be chosen.
See also
- _set_value(key: str, value: BaseType | Solution)
Sets the value of a variable in the object’s internal dictionary.
- Parameters:
key (str) – The key of the variable to set.
value (types.BaseType) – The value to set the variable to.
- Returns:
None
- Raises:
None
Note
This method is intended for internal use only and should not be called directly from outside the object.
- _set_sub_solution(variable: str, value: SolLayer)
Sets the value of a sub-solution variable.
- Parameters:
variable (str) – The name of the sub-solution variable to set.
value (SolLayer) – A dictionary containing the values of the sub-solution variables.
Note
This method sets the value of a sub-solution variable in the solution. It creates a new Solution object for the sub-solution and iterates through the key-value pairs in the input dictionary to set the values of the sub-solution variables. The sub-solution is then set as the value of the sub-solution variable in the current solution.
See also
- _initialize(variable: str, definition: Base) None
Initializes a variable with depending upon its definition.
- Parameters:
variable (str) – The name of the variable to initialize.
definition (BaseDefinition) – The definition object for the variable.
- Returns:
None
Note
This method initializes a variable with the given definition object. It first converts the definition object into a corresponding variable type object, then calls the
initialize()method of the variable type object to initialize it, and finally sets the value of the variable using theset()method.See also
Types
digraph inheritance2534440ee8 { bgcolor=transparent; rankdir=LR; size="8.0, 12.0"; "BaseType" [URL="#metagen.framework.solution.types.BaseType",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top"]; "Categorical" [URL="#metagen.framework.solution.types.Categorical",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top"]; "BaseType" -> "Categorical" [arrowsize=0.5,style="setlinewidth(0.5)"]; "Integer" [URL="#metagen.framework.solution.types.Integer",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top"]; "BaseType" -> "Integer" [arrowsize=0.5,style="setlinewidth(0.5)"]; "Real" [URL="#metagen.framework.solution.types.Real",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top"]; "BaseType" -> "Real" [arrowsize=0.5,style="setlinewidth(0.5)"]; "Structure" [URL="#metagen.framework.solution.types.Structure",fillcolor=white,fontname="Vera Sans, DejaVu Sans, Liberation Sans, Arial, Helvetica, sans",fontsize=10,height=0.25,shape=box,style="setlinewidth(0.5),filled",target="_top"]; "BaseType" -> "Structure" [arrowsize=0.5,style="setlinewidth(0.5)"]; }BaseType
- class BaseType(definition: Base, connector: BaseConnector = None)
Bases:
ABCThis class represents an abstraction of the types included in a Solution. Note that the class support a Domain or a Base definition and the type is initialized in the constructor.
Attributes: __definition (Base): A definition or domain used to define the variable. value (Any): The value of the variable.
- abstractmethod check(value: Any) None
Checks if the given value is a valid input for the variable. Note this class is intended to be overwritten for a specific type.
- abstractmethod initialize() None
Initializes the value of the variable. Note this class is intended to be overwritten for a specific type.
- abstractmethod mutate(alteration_limit=None) None
Modifies the value of the variable. Note this class is intended to be overwritten for a specific type.
- get() Any
Returns the value of the variable.
- set(value: Any) None
Sets the value of the variable.
Integer
- class Integer(definition: IntegerDefinition, connector=None)
Bases:
BaseTypeThe Integer class inherits from the BaseType class and represents an integer variable.
- Parameters:
definition (IntegerDefinition) – An instance of IntegerDefinition class representing the definition of the categorical variable.
- check(value: Any) None
Check if the input value is a valid Integer value, according to the definition of the Integer instance.
- Parameters:
value – The value to check.
- Raises:
ValueError – if the value does not correspond to the definition.
- initialize() None
Initialize the Integer variable with a rs integer value in the defined ranges considering the step size.
- mutate(alteration_limit: int = None) None
Modify the value of this Integer instance to a rs category from its definition.
- Parameters:
alteration_limit – The determined how much the mutation will alter the current value. If not provided, the mutation can replace the current value with any within the domain.
- set(value: Any) None
Sets the value of the Integer variable, after checking if the value is valid.
- Args:
value (Any): The value to be set for the Integer variable.
Real
- class Real(definition: RealDefinition, connector=None)
Bases:
BaseTypeThe Real class inherits from the BaseType class and represents a Real variable.
- Parameters:
definition (RealDefinition) – An instance of RealDefinition class representing the definition of the categorical variable.
- check(value: Any) None
Check if the input value is a valid Real value, according to the definition of the Real instance.
- Parameters:
value – The value to check.
- Raises:
ValueError – if the value does not correspond to the definition.
- initialize() None
Initialize the Real variable with a rs float value in the defined ranges considering the step size.
- mutate(alteration_limit: float = None) None
Modify the value of this Real instance to a rs value from its definition.
- Parameters:
alteration_limit – The determined how much the mutation will alter the current value. If not provided, the mutation can replace the current value with any within the domain.
- set(value: Any) None
Sets the value of the Real variable, after checking if the value is valid.
- Args:
value (Any): The value to be set for the Real variable.
Categorical
- class Categorical(definition: CategoricalDefinition, connector=None)
Bases:
BaseTypeThe Categorical class inherits from the BaseType class and represents a categorical variable.
- Parameters:
definition (CategoricalDefinition) – An instance of CategoricalDefinition class representing the definition of the categorical variable.
- check(value: Any) None
Check if the input value is a valid Categorical value, according to the definition of the Categorical instance.
- Parameters:
value – The value to check.
- initialize() None
Initialize the categorical variable with a rs category from the available categories.
- mutate(alteration_limit: Any = None) None
Modify the value of this Categorical instance to a rs category from its definition, excluding its current value.
- set(value: Any) None
Sets the value of the categorical variable, after checking if the value is valid.
- Args:
value (Any): The value to be set for the categorical variable.
Structure
- class Structure(definition: BaseStructureDefinition, connector=None)
Bases:
BaseTypeThe Real class inherits from the BaseType class and represents a Real variable.
- Parameters:
definition (BaseStructureDefinition) – An instance of BaseStructureDefinition class representing the definition of the categorical variable.
- check(value: Any) None
Check if the input value is a valid Real value, according to the definition of the Real instance.
- Parameters:
value – The value to check.
- Raises:
ValueError – if the value does not correspond to the definition.
- is_available(index: int) bool
It checks if the index-nh component of the input VECTOR variable has a value in this solution, taking into account the internal solution legacy_domain (by default) or a legacy_domain passed as parameter.
- Parameters:
index (int) – The index of the component to check.
- Returns:
True if the index-nh component has a value, otherwise False.
- Return type:
bool
- initialize() None
Initializes the Structure according to the definition provided. If the definition is of type DynamicStructureDefinition, a rs size is chosen within the min_size and max_size range (inclusive), with an optional step size. If the definition is of type StaticStructureDefinition, the provided size value is used instead.
For each position in the Structure, a new instance of the BaseType class is created based on the base type provided by the definition. The initialize() method is then called on this instance to set a value for it, and the instance is appended to the Structure.
See also
get_definition()
- mutate(alteration_limit: Any = None) None
Modify the Structure by performing an action selected randomly from three options: 1. Resizing: if the Structure definition is dynamic, resizes the vector to a new rs size. 2. Altering: modify the values of the vector. Note this option is the only one allowed for a static structure definition. 3. Resizing and Altering: if the Structure definition is dynamic, resizes the vector by calling and modify a rs set of values of the vector.
See also
- get(index=None) Any
Obtains the builtin value of the Structure or an specific index builtin value.
- _resize() None
Resizes the vector based on the definition provided at initialization. The vector size can increase or decrease, depending on the minimum, maximum, and step size defined in the definition. When increasing, a rs set of values are included from the defined type. When decreasing, a rs set of values are deleted from the structure.
- _alterate(alteration_limit: Any = None) None
Randomly alters a certain number of elements in the vector by calling their mutate method.
- _convert(value: int | float | str | Dict[str, int | float | str] | List[int] | List[float] | List[str] | List[Dict[str, int | float | str]]) BaseType
This method takes an input value which usually represents a builtin type and returns an instance of the corresponding BaseType. For instance:
int builtin type is converted to Integer.
float builtin type is converted to Real.
str builtin type is converted to Categorical.
list builtin type is converted to Structure.
dict builtin type is converted to Solution.
BaseTypes are not converted and returned without change.
- Parameters:
value (InputValue) – An input value to be converted to a BaseType instance.
- Returns:
A BaseType instance created from the input value.
- Raises:
ValueError – If the type of the input value is not supported by the Structure [int, float, str, list, dict, BaseType].
- insert(index: int, value: int | float | str | list | dict | BaseType) None
Inserts the given value at the given index in the Structure.
- Parameters:
index (int) – The index to insert the value at.
value (int | float | str | list | dict | BaseType) – The value to insert.
- Returns:
None