Quick-Start Guide to Solving Optimization Problems with Geatpy’s Genetic Algorithm
This tutorial walks you through a quick-start example using Geatpy’s solver mode, showing how to define a problem, set up a genetic algorithm with mixed integer encoding, compute objective and constraint values, and execute the optimization to obtain optimal decision variables.
Getting Started Example
First, using the "solver mode" as a quick start to help you master building problems, defining algorithms, and solving them.
Example 1
Use a genetic algorithm with enhanced elite retention strategy to solve the following problem:
s.t.
where the decision variables and their ranges are defined.
<code>import numpy as np
import geatpy as ea
# 构建问题
r = 1 # 目标函数需要用到的额外数据
@ea.Problem.single
def evalVars(Vars): # 定义目标函数(含约束)
f = np.sum((Vars - r) ** 2) # 计算目标函数值
x1 = Vars[0]
x2 = Vars[1]
CV = np.array([(x1 - 0.5)**2 - 0.25,
(x2 - 1)**2 - 1]) # 计算违反约束程度
return f, CV
problem = ea.Problem(name='soea quick start demo',
M=1, # 目标维数
maxormins=[1], # 目标最小最大化标记列表,1:最小化该目标;-1:最大化该目标
Dim=5, # 决策变量维数
varTypes=[0, 0, 1, 1, 1], # 决策变量的类型列表,0:实数;1:整数
lb=[-1, 1, 2, 1, 0], # 决策变量下界
ub=[1, 4, 5, 2, 1], # 决策变量上界
evalVars=evalVars)
# 构建算法
algorithm = ea.soea_SEGA_templet(problem,
ea.Population(Encoding='RI', NIND=20),
MAXGEN=50, # 最大进化代数。
logTras=1, # 表示每隔多少代记录一次日志信息,0表示不记录。
trappedValue=1e-6, # 单目标优化陷入停滞的判断阈值。
maxTrappedCount=10) # 进化停滞计数器最大上限值。
# 求解
res = ea.optimize(algorithm, seed=1, verbose=True, drawing=1, outputMsg=True, drawLog=False)
</code>Analysis
From the code we can see that we first define an objective function, then create the problem, build the algorithm, and finally call optimize() to solve it. The @ea.Problem.single decorator makes the evalVars() function receive a one‑dimensional NumPy ndarray representing an individual’s decision variables. Inside evalVars() we compute the objective value with f = np.sum((Vars - r) ** 2) .
Then we compute the constraint violation values with CV = np.array([(x1 - 0.5)**2 - 0.25, (x2 - 1)**2 - 1]) . If a value is greater than 0, the corresponding constraint is violated; larger values indicate greater violation.
Line 15 calls Geatpy’s Problem constructor, where maxormins records whether each objective is to be minimized (1) or maximized (-1), and varTypes records variable types (0 for continuous, 1 for integer).
Line 24 instantiates a built‑in evolutionary algorithm class; the population encoding Encoding='RI' means “real‑integer mixed” encoding. NIND=20 sets the population size to 20.
Finally, line 31 calls ea.optimize() . seed=1 fixes the random seed; dirName='result' saves results to a folder named “result”. The returned dictionary res contains keys such as ObjV (best objective values) and Vars (corresponding decision variable values).
Alternative Implementation
<code>r = 1 # 模拟该案例问题计算目标函数时需要用到的额外数据
def evalVars(Vars): # 定义目标函数(含约束)
ObjV = np.sum((Vars - r)**2, 1, keepdims=True) # 计算目标函数值
x1 = Vars[:, [0]] # 把Vars的第0列取出来
x2 = Vars[:, [1]] # 把Vars的第1列取出来
CV = np.hstack([(x1 - 0.5)**2 - 0.25, (x2 - 1)**2 - 1]) # 计算违反约束程度
return ObjV, CV # 返回目标函数值矩阵和违反约束程度矩阵
problem = ea.Problem(
name='soea quick start demo',
M=1, # 目标维数
maxormins=[1], # 目标最小最大化标记列表,1:最小化该目标;-1:最大化该目标
Dim=5, # 决策变量维数
varTypes=[0, 0, 1, 1, 1], # 决策变量的类型列表,0:实数;1:整数
lb=[-1, 1, 2, 1, 0], # 决策变量下界
ub=[1, 4, 5, 2, 1], # 决策变量上界
evalVars=evalVars)
# 构建算法
algorithm = ea.soea_SEGA_templet(problem,
ea.Population(Encoding='RI', NIND=20),
MAXGEN=50, # 最大进化代数。
logTras=1, # 表示每隔多少代记录一次日志信息,0表示不记录。
trappedValue=1e-6, # 单目标优化陷入停滞的判断阈值。
maxTrappedCount=10) # 进化停滞计数器最大上限值。
# 求解
res = ea.optimize(algorithm,
verbose=True,
drawing=1,
outputMsg=True,
drawLog=False,
saveFlag=True)
</code>References
http://geatpy.com/index.php/quickstart/
Model Perspective
Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.