A pymoo Problem class defines an optimization problem’s decision variables, objectives, constraints, bounds, variable type, and evaluation behavior. Algorithms pass a population of candidate solutions to _evaluate, which writes objective values to out["F"] and constraint values to out["H"]. This population-oriented interface distinguishes Problem from ElementwiseProblem, which evaluates one solution at a time. section 8.8 section 7.4
A custom class typically specifies:
- n_var for the number of decision variables, n_obj for objectives, and constraint counts where required. section 8.8
- xl and xu for lower and upper bounds, plus vtype for integer, floating-point, or other variable representations. section 8.8 section 7.4
- _evaluate(self, x, out, ...) to translate candidate solutions into objective and constraint values. section 8.8 section 7.4
Ticket pricing
A TicketPrice class models one price variable bounded from 75 to 235, one objective, and no constraints. Its _evaluate method computes 20*x*x - 6200*x + 350000 for each candidate. Passing the class to GA and minimize produces an optimal ticket price of 155 and a profit of 130500 after reversing the minimization objective’s sign. section 7.4
Constrained districting
A PoliticalDistricting subclass represents each neighborhood’s district assignment as an integer variable. It defines one objective, three equality constraints, bounds from 0 to num_dist - 1, and evaluation logic for population balance, neighborhood adjacency, and district connectivity. section 8.8
from pymoo.core.problem import Problem
class PoliticalDistricting(Problem):
def __init__(self,
num_dist,
neighbor,
populations,
margin
): #1
self.populations = populations #2
self.average = np.mean(populations) #3
super().__init__(n_var=len(self.populations), n_obj=1, n_eq_constr=3,
xl=0, xu=num_dist-1, vtype=int) #4
self.n_var = len(self.populations)
self.n_dist = num_dist
self.margin = margin
self.neighbor = neighbor
self.func = self._evaluate #5
#1 Define a constructor with specific parameters.
#2 Hold the population data.
#3 Store the mean population of all districts.
#4 Call the constructor of the parent class with specific parameters.
#5 Evaluate the solution against the objective function and constraints.
Inspect the constructor pattern for storing problem data and passing n_var, n_obj, constraints, bounds, and variable type to the parent Problem class. section 8.8
