eckity.multi_objective_evolution.nsga2_fitness

  1from typing import List
  2
  3from overrides import overrides
  4
  5from eckity.fitness.fitness import Fitness
  6from eckity.individual import Individual
  7import random as rd
  8
  9
 10class NSGA2Fitness(Fitness):
 11    def __init__(
 12        self,
 13        fitness: List[float] = None,
 14        higher_is_better=False,
 15        cache: bool = False,
 16        is_relative_fitness: bool = False,
 17    ):
 18        is_evaluated = fitness is not None
 19        super().__init__(
 20            higher_is_better=higher_is_better,
 21            is_evaluated=is_evaluated,
 22            cache=cache,
 23            is_relative_fitness=is_relative_fitness,
 24        )
 25        self.fitness: List[float] = fitness  # list of objectives
 26        self.crowding = 0
 27        self.front_rank = float("inf")
 28        if self.fitness is not None and type(self.higher_is_better) is bool:
 29            self.higher_is_better = [self.higher_is_better] * len(fitness)
 30
 31    def set_fitness(self, fitness):
 32        if self._is_evaluated:
 33            raise AttributeError("fitness already evaluated and set to", self.fitness)
 34        self.fitness = fitness
 35        self._is_evaluated = True
 36        if type(self.higher_is_better) is bool:
 37            self.higher_is_better = [self.higher_is_better] * len(fitness)
 38
 39    @overrides
 40    def get_pure_fitness(self):
 41        if not self._is_evaluated:
 42            raise ValueError("Fitness not evaluated yet")
 43        return self.fitness
 44
 45    @overrides
 46    def set_not_evaluated(self):
 47        self._is_evaluated = False
 48        self.fitness = None
 49        self.crowding = 0
 50        self.front_rank = float("inf")
 51
 52    def check_comparable_fitnesses(
 53        self, other_fitness: Fitness, ind: Individual, other_ind: Individual
 54    ):
 55        if not isinstance(other_fitness, NSGA2Fitness):
 56            raise TypeError(
 57                "Expected NSGA2Fitness object in better_than, got", type(other_fitness)
 58            )
 59        if not self.is_fitness_evaluated() or not other_fitness.is_fitness_evaluated():
 60            raise ValueError("Fitnesses must be evaluated before comparison")
 61        if len(other_fitness.get_augmented_fitness(other_ind)) != len(
 62            self.get_augmented_fitness(ind)
 63        ):
 64            raise ValueError("Fitnesses must be of the same lngth")
 65
 66    def better_than(self, ind, other_fitness, other_ind):
 67        """
 68
 69        Parameters
 70        ----------
 71        ind:Individual
 72        other_fitness:NSGA2Fitness
 73        other_ind:Individual
 74
 75        Returns : True ind has lower rank or equal rank and bigger crwoding value
 76        -------
 77
 78        """
 79        if self.front_rank == float("inf"):  # first iteration
 80            return bool(rd.getrandbits(1))  # random true false
 81        else:
 82            self.check_comparable_fitnesses(other_fitness, ind, other_ind)
 83            if self.front_rank == other_ind.fitness.front_rank:
 84                return self.crowding > other_ind.fitness.crowding
 85            return self.front_rank > other_ind.fitness.front_rank
 86
 87    def equal_to(self, ind, other_fitness, other_ind):
 88        return (
 89            self.front_rank == other_ind.fitness.front_rank
 90            and self.crowding == other_ind.fitness.crowding
 91        )
 92
 93    def dominate(self, ind, other_fitness, other_ind):
 94        self.check_comparable_fitnesses(other_fitness, ind, other_ind)
 95        self_fit = self.get_augmented_fitness(ind)
 96        other_fit = other_fitness.get_augmented_fitness(other_ind)
 97        return all(
 98            [
 99                self._o1_at_least_o2(o1, o2, h_is_b)
100                for h_is_b, o1, o2 in zip(self.higher_is_better, self_fit, other_fit)
101            ]
102        ) and any(
103            [
104                self._o1_better_then_o2(o1, o2, h_is_b)
105                for h_is_b, o1, o2 in zip(self.higher_is_better, self_fit, other_fit)
106            ]
107        )
108
109    def _o1_at_least_o2(self, o1, o2, higher_is_better):
110        """
111
112        Parameters
113        ----------
114        o1: objective i of individual 1
115        o2: objective i of individual 2
116        higher_is_better :boolean - is higher better for objective i of he fitness ?
117
118        Returns :x1 >= x2 or x1 <= x2 according to higher is better
119        -------
120
121        """
122        if higher_is_better:
123            return o1 >= o2
124        else:
125            return o1 <= o2
126
127    def _o1_better_then_o2(self, o1, o2, higher_is_better):
128        """
129
130        Parameters
131        ----------
132        o1: objective i of individual 1
133        o2: objective i of individual 2
134        higher_is_better :boolean - is higher better for objective i of he fitness ?
135
136        Returns :x1 > x2 or x1 < x2 according to higher is better
137        -------
138
139        """
140        if higher_is_better:
141            return o1 > o2
142        else:
143            return o1 < o2
144
145    # def equal_to(self, ind, other_fitness, other_ind):
146    #     self.check_comparable_fitnesses(other_fitness,ind,other_ind)
147    #     self_fit = self.get_augmented_fitness(ind)
148    #     other_fit = other_fitness.get_augmented_fitness(other_ind)
149    #     all([x1 == x2 for x1, x2 in zip(self_fit, other_fit)])
150
151    def __getstate__(self):
152        state = self.__dict__.copy()
153        if not self.cache:
154            state["_is_evaluated"] = False
155            state["fitness"] = None
156        return state
class NSGA2Fitness(eckity.fitness.fitness.Fitness):
 11class NSGA2Fitness(Fitness):
 12    def __init__(
 13        self,
 14        fitness: List[float] = None,
 15        higher_is_better=False,
 16        cache: bool = False,
 17        is_relative_fitness: bool = False,
 18    ):
 19        is_evaluated = fitness is not None
 20        super().__init__(
 21            higher_is_better=higher_is_better,
 22            is_evaluated=is_evaluated,
 23            cache=cache,
 24            is_relative_fitness=is_relative_fitness,
 25        )
 26        self.fitness: List[float] = fitness  # list of objectives
 27        self.crowding = 0
 28        self.front_rank = float("inf")
 29        if self.fitness is not None and type(self.higher_is_better) is bool:
 30            self.higher_is_better = [self.higher_is_better] * len(fitness)
 31
 32    def set_fitness(self, fitness):
 33        if self._is_evaluated:
 34            raise AttributeError("fitness already evaluated and set to", self.fitness)
 35        self.fitness = fitness
 36        self._is_evaluated = True
 37        if type(self.higher_is_better) is bool:
 38            self.higher_is_better = [self.higher_is_better] * len(fitness)
 39
 40    @overrides
 41    def get_pure_fitness(self):
 42        if not self._is_evaluated:
 43            raise ValueError("Fitness not evaluated yet")
 44        return self.fitness
 45
 46    @overrides
 47    def set_not_evaluated(self):
 48        self._is_evaluated = False
 49        self.fitness = None
 50        self.crowding = 0
 51        self.front_rank = float("inf")
 52
 53    def check_comparable_fitnesses(
 54        self, other_fitness: Fitness, ind: Individual, other_ind: Individual
 55    ):
 56        if not isinstance(other_fitness, NSGA2Fitness):
 57            raise TypeError(
 58                "Expected NSGA2Fitness object in better_than, got", type(other_fitness)
 59            )
 60        if not self.is_fitness_evaluated() or not other_fitness.is_fitness_evaluated():
 61            raise ValueError("Fitnesses must be evaluated before comparison")
 62        if len(other_fitness.get_augmented_fitness(other_ind)) != len(
 63            self.get_augmented_fitness(ind)
 64        ):
 65            raise ValueError("Fitnesses must be of the same lngth")
 66
 67    def better_than(self, ind, other_fitness, other_ind):
 68        """
 69
 70        Parameters
 71        ----------
 72        ind:Individual
 73        other_fitness:NSGA2Fitness
 74        other_ind:Individual
 75
 76        Returns : True ind has lower rank or equal rank and bigger crwoding value
 77        -------
 78
 79        """
 80        if self.front_rank == float("inf"):  # first iteration
 81            return bool(rd.getrandbits(1))  # random true false
 82        else:
 83            self.check_comparable_fitnesses(other_fitness, ind, other_ind)
 84            if self.front_rank == other_ind.fitness.front_rank:
 85                return self.crowding > other_ind.fitness.crowding
 86            return self.front_rank > other_ind.fitness.front_rank
 87
 88    def equal_to(self, ind, other_fitness, other_ind):
 89        return (
 90            self.front_rank == other_ind.fitness.front_rank
 91            and self.crowding == other_ind.fitness.crowding
 92        )
 93
 94    def dominate(self, ind, other_fitness, other_ind):
 95        self.check_comparable_fitnesses(other_fitness, ind, other_ind)
 96        self_fit = self.get_augmented_fitness(ind)
 97        other_fit = other_fitness.get_augmented_fitness(other_ind)
 98        return all(
 99            [
100                self._o1_at_least_o2(o1, o2, h_is_b)
101                for h_is_b, o1, o2 in zip(self.higher_is_better, self_fit, other_fit)
102            ]
103        ) and any(
104            [
105                self._o1_better_then_o2(o1, o2, h_is_b)
106                for h_is_b, o1, o2 in zip(self.higher_is_better, self_fit, other_fit)
107            ]
108        )
109
110    def _o1_at_least_o2(self, o1, o2, higher_is_better):
111        """
112
113        Parameters
114        ----------
115        o1: objective i of individual 1
116        o2: objective i of individual 2
117        higher_is_better :boolean - is higher better for objective i of he fitness ?
118
119        Returns :x1 >= x2 or x1 <= x2 according to higher is better
120        -------
121
122        """
123        if higher_is_better:
124            return o1 >= o2
125        else:
126            return o1 <= o2
127
128    def _o1_better_then_o2(self, o1, o2, higher_is_better):
129        """
130
131        Parameters
132        ----------
133        o1: objective i of individual 1
134        o2: objective i of individual 2
135        higher_is_better :boolean - is higher better for objective i of he fitness ?
136
137        Returns :x1 > x2 or x1 < x2 according to higher is better
138        -------
139
140        """
141        if higher_is_better:
142            return o1 > o2
143        else:
144            return o1 < o2
145
146    # def equal_to(self, ind, other_fitness, other_ind):
147    #     self.check_comparable_fitnesses(other_fitness,ind,other_ind)
148    #     self_fit = self.get_augmented_fitness(ind)
149    #     other_fit = other_fitness.get_augmented_fitness(other_ind)
150    #     all([x1 == x2 for x1, x2 in zip(self_fit, other_fit)])
151
152    def __getstate__(self):
153        state = self.__dict__.copy()
154        if not self.cache:
155            state["_is_evaluated"] = False
156            state["fitness"] = None
157        return state

This class is responsible for handling the fitness score of some Individual (checking if fitness is evaluated, comparing fitness scores with other individuals etc.)

is_evaluated: bool declares if fitness score is evaluated and updated in the current generation

higher_is_better: bool declares the fitness direction. i.e., if it should be minimized or maximized

cache: bool declares whether the fitness score should reset at the end of each generation

is_relative_fitness: bool declares whether the fitness score is absolute or relative

NSGA2Fitness( fitness: List[float] = None, higher_is_better=False, cache: bool = False, is_relative_fitness: bool = False)
12    def __init__(
13        self,
14        fitness: List[float] = None,
15        higher_is_better=False,
16        cache: bool = False,
17        is_relative_fitness: bool = False,
18    ):
19        is_evaluated = fitness is not None
20        super().__init__(
21            higher_is_better=higher_is_better,
22            is_evaluated=is_evaluated,
23            cache=cache,
24            is_relative_fitness=is_relative_fitness,
25        )
26        self.fitness: List[float] = fitness  # list of objectives
27        self.crowding = 0
28        self.front_rank = float("inf")
29        if self.fitness is not None and type(self.higher_is_better) is bool:
30            self.higher_is_better = [self.higher_is_better] * len(fitness)
fitness: List[float]
crowding
front_rank
def set_fitness(self, fitness):
32    def set_fitness(self, fitness):
33        if self._is_evaluated:
34            raise AttributeError("fitness already evaluated and set to", self.fitness)
35        self.fitness = fitness
36        self._is_evaluated = True
37        if type(self.higher_is_better) is bool:
38            self.higher_is_better = [self.higher_is_better] * len(fitness)
@overrides
def get_pure_fitness(self):
40    @overrides
41    def get_pure_fitness(self):
42        if not self._is_evaluated:
43            raise ValueError("Fitness not evaluated yet")
44        return self.fitness

Returns the pure fitness score of the individual (before applying balancing methods like bloat control)

@overrides
def set_not_evaluated(self):
46    @overrides
47    def set_not_evaluated(self):
48        self._is_evaluated = False
49        self.fitness = None
50        self.crowding = 0
51        self.front_rank = float("inf")

Set this fitness score status to be not evaluated

def check_comparable_fitnesses( self, other_fitness: eckity.fitness.fitness.Fitness, ind: eckity.individual.Individual, other_ind: eckity.individual.Individual):
53    def check_comparable_fitnesses(
54        self, other_fitness: Fitness, ind: Individual, other_ind: Individual
55    ):
56        if not isinstance(other_fitness, NSGA2Fitness):
57            raise TypeError(
58                "Expected NSGA2Fitness object in better_than, got", type(other_fitness)
59            )
60        if not self.is_fitness_evaluated() or not other_fitness.is_fitness_evaluated():
61            raise ValueError("Fitnesses must be evaluated before comparison")
62        if len(other_fitness.get_augmented_fitness(other_ind)) != len(
63            self.get_augmented_fitness(ind)
64        ):
65            raise ValueError("Fitnesses must be of the same lngth")
def better_than(self, ind, other_fitness, other_ind):
67    def better_than(self, ind, other_fitness, other_ind):
68        """
69
70        Parameters
71        ----------
72        ind:Individual
73        other_fitness:NSGA2Fitness
74        other_ind:Individual
75
76        Returns : True ind has lower rank or equal rank and bigger crwoding value
77        -------
78
79        """
80        if self.front_rank == float("inf"):  # first iteration
81            return bool(rd.getrandbits(1))  # random true false
82        else:
83            self.check_comparable_fitnesses(other_fitness, ind, other_ind)
84            if self.front_rank == other_ind.fitness.front_rank:
85                return self.crowding > other_ind.fitness.crowding
86            return self.front_rank > other_ind.fitness.front_rank
Parameters
  • ind (Individual):

  • other_fitness (NSGA2Fitness):

  • other_ind (Individual):

  • Returns (True ind has lower rank or equal rank and bigger crwoding value):

  • -------

def equal_to(self, ind, other_fitness, other_ind):
88    def equal_to(self, ind, other_fitness, other_ind):
89        return (
90            self.front_rank == other_ind.fitness.front_rank
91            and self.crowding == other_ind.fitness.crowding
92        )

Compares between the current fitness of the individual ind to the fitness score other_fitness of other_ind

Parameters
  • ind (Individual): the individual instance that holds this Fitness instance
  • other_fitness (Fitness): the Fitness instance of the other individual
  • other_ind (Individual): the other individual instance which is being compared to the individual ind
Returns
  • bool: True if this fitness is equal to the other fitness, False otherwise
def dominate(self, ind, other_fitness, other_ind):
 94    def dominate(self, ind, other_fitness, other_ind):
 95        self.check_comparable_fitnesses(other_fitness, ind, other_ind)
 96        self_fit = self.get_augmented_fitness(ind)
 97        other_fit = other_fitness.get_augmented_fitness(other_ind)
 98        return all(
 99            [
100                self._o1_at_least_o2(o1, o2, h_is_b)
101                for h_is_b, o1, o2 in zip(self.higher_is_better, self_fit, other_fit)
102            ]
103        ) and any(
104            [
105                self._o1_better_then_o2(o1, o2, h_is_b)
106                for h_is_b, o1, o2 in zip(self.higher_is_better, self_fit, other_fit)
107            ]
108        )