Skip to content

Instantly share code, notes, and snippets.

@gugarosa
Created June 14, 2021 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gugarosa/7ac59320e1308f43250ddedf475273c9 to your computer and use it in GitHub Desktop.
Save gugarosa/7ac59320e1308f43250ddedf475273c9 to your computer and use it in GitHub Desktop.
Penalizes an Opytimizer objective function with a more complex constraint.
import numpy as np
from opytimizer import Opytimizer
from opytimizer.functions import ConstrainedFunction
from opytimizer.optimizers.swarm import PSO
from opytimizer.spaces import SearchSpace
# Defines a customized objective function
def spfunc(x):
# Just a mock-up objective to emulate the problem
y = x[0][0] + x[1][0] + x[2][0]
return y
# Defines a constraint function that returns a boolean
# whether the constraint is valid or not
def c_1(x):
# Defines every value that is allowed
allowed_values = [0.1, 9, 19, 24, 29, 60.5, 99, 199]
# Defines a boolean array that defines whether constraint is valid
valid_constraint = np.zeros(x.shape[0])
# Iterates through every possible variables
for i in range(valid_constraint.shape[0]):
# Checks if variable is valid
if x[i][0] in allowed_values:
# Turns on the boolean array on corresponding position
valid_constraint[i] = 1
# If all variables are valid return the constraint as `True`
if len(np.argwhere(valid_constraint == 0)) == 0:
return True
# Otherwise, we need to return the constraint as `False`
return False
# Random seed for experimental consistency
np.random.seed(1)
# Number of agents and decision variables
n_agents = 20
n_variables = 3
# Lower and upper bounds (has to be the same size as `n_variables`)
lower_bound = [0.1, 0.1, 0.1]
upper_bound = [199, 199, 199]
# Creates the space, optimizer and function
space = SearchSpace(n_agents, n_variables, lower_bound, upper_bound)
optimizer = PSO()
function = ConstrainedFunction(spfunc, [c_1], penalty=10000.0)
# Bundles every piece into Opytimizer class
opt = Opytimizer(space, optimizer, function, save_agents=False)
# Runs the optimization task
opt.start(n_iterations=100)
# Prints out best position
print(opt.space.best_agent.position)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment