本文整理汇总了Python中nlopt.opt方法的典型用法代码示例。如果您正苦于以下问题:Python nlopt.opt方法的具体用法?Python nlopt.opt怎么用?Python nlopt.opt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类nlopt
的用法示例。
在下文中一共展示了nlopt.opt方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: solve_direct
# 需要导入模块: import nlopt [as 别名]
# 或者: from nlopt import opt [as 别名]
def solve_direct(f, bounds):
def objective(x, grad):
"""Objective function in the form required by nlopt."""
if grad.size > 0:
fx, gx = f(x[None], grad=True)
grad[:] = gx[0][:]
else:
fx = f(x[None], grad=False)
return fx[0]
bounds = np.array(bounds, ndmin=2)
opt = nlopt.opt(nlopt.GN_DIRECT_L, bounds.shape[0])
opt.set_lower_bounds(list(bounds[:, 0]))
opt.set_upper_bounds(list(bounds[:, 1]))
opt.set_ftol_rel(1e-6)
opt.set_max_objective(objective)
xmin = bounds[:, 0] + (bounds[:, 1] - bounds[:, 0]) / 2
xmin = opt.optimize(xmin)
fmax = opt.last_optimum_value()
return xmin, fmax
示例2: __init__
# 需要导入模块: import nlopt [as 别名]
# 或者: from nlopt import opt [as 别名]
def __init__(self, nelx, nely, volfrac, penal, rmin, ft, gui, bc):
self.n = nelx * nely
self.opt = nlopt.opt(nlopt.LD_MMA, self.n)
self.passive = bc.get_passive_elements()
self.xPhys = np.ones(self.n)
if self.passive is not None:
self.xPhys[self.passive] = 0
# set bounds
ub = np.ones(self.n, dtype=float)
self.opt.set_upper_bounds(ub)
lb = np.zeros(self.n, dtype=float)
self.opt.set_lower_bounds(lb)
# set stopping criteria
self.opt.set_maxeval(2000)
self.opt.set_ftol_rel(0.001)
# set objective and constraint functions
self.opt.set_min_objective(self.compliance_function)
self.opt.add_inequality_constraint(self.volume_function, 0)
# setup filter
self.ft = ft
self.filtering = Filter(nelx, nely, rmin)
# setup problem def
self.init_problem(nelx, nely, penal, bc)
self.volfrac = volfrac
# set GUI callback
self.init_gui(gui)
示例3: optimize
# 需要导入模块: import nlopt [as 别名]
# 或者: from nlopt import opt [as 别名]
def optimize(self, x):
self.xPhys = x.copy()
x = self.opt.optimize(x)
return x
示例4: _get_optimizer
# 需要导入模块: import nlopt [as 别名]
# 或者: from nlopt import opt [as 别名]
def _get_optimizer(self, D=1, upper_bound=1, iteration_budget=None):
"""Utility function creating an NLOPT optimizer with default
parameters depending on this objects parameters
"""
if iteration_budget == None:
iteration_budget = self.linear_iteration_budget
opt = nlopt.opt(nlopt.GN_DIRECT_L_RAND, D)
# opt.set_stopval(self.acceptance_threshold/10.0)
opt.set_ftol_rel(1e-5)
opt.set_maxeval(iteration_budget)
opt.set_lower_bounds(0)
opt.set_upper_bounds(upper_bound)
return opt
示例5: solve
# 需要导入模块: import nlopt [as 别名]
# 或者: from nlopt import opt [as 别名]
def solve(self, prev_state='', verbose_output=False, maxtime=None):
if prev_state == '':
initSol = self.vars.xopt
else:
initSol = prev_state
if not maxtime == None:
self.opt.set_maxtime(maxtime)
if not self.vars.unconstrained:
for c in self.vars.constraints:
if c.constraintType() == 'ineq':
self.opt.add_inequality_constraint(c.func_nlopt, 0.1)
elif c.constraintType() == 'eq':
self.opt.add_equality_constraint(c.func_nlopt, 0.1)
else:
self.opt.remove_inequality_constraints()
self.opt.remove_equality_constraints()
xopt = self.opt.optimize(initSol)
f_obj = self.opt.last_optimum_value()
if verbose_output:
print bcolors.OKBLUE + str(xopt) + bcolors.ENDC + '\n'
self.vars.update(xopt, f_obj)
return xopt
示例6: fit
# 需要导入模块: import nlopt [as 别名]
# 或者: from nlopt import opt [as 别名]
def fit(self, X, y): # -1 for unlabeled
unlabeledX = X[y==-1, :]
labeledX = X[y!=-1, :]
labeledy = y[y!=-1]
M = unlabeledX.shape[0]
# train on labeled data
self.model.fit(labeledX, labeledy)
unlabeledy = self.predict(unlabeledX)
#re-train, labeling unlabeled instances pessimistically
# pessimistic soft labels ('weights') q for unlabelled points, q=P(k=0|Xu)
f = lambda softlabels, grad=[]: self.discriminative_likelihood_objective(self.model, labeledX, labeledy=labeledy, unlabeledData=unlabeledX, unlabeledWeights=numpy.vstack((softlabels, 1-softlabels)).T, gradient=grad) #- supLL
lblinit = numpy.random.random(len(unlabeledy))
try:
self.it = 0
opt = nlopt.opt(nlopt.GN_DIRECT_L_RAND, M)
opt.set_lower_bounds(numpy.zeros(M))
opt.set_upper_bounds(numpy.ones(M))
opt.set_min_objective(f)
opt.set_maxeval(self.max_iter)
self.bestsoftlbl = opt.optimize(lblinit)
print " max_iter exceeded."
except Exception, e:
print e
self.bestsoftlbl = self.bestlbls
示例7: runOptimization
# 需要导入模块: import nlopt [as 别名]
# 或者: from nlopt import opt [as 别名]
def runOptimization(self):
self.statusBar().showMessage("Optimizing...")
# update GUI to show changes status bar message
QtGui.QApplication.processEvents()
nTurns = float(self.nTurnsLineEdit.text())
innerRadius = float(self.innerRadiusLineEdit.text())
pitch = float(self.pitchLineEdit.text())
spacing = float(self.spacingLineEdit.text())
traceWidth = float(self.traceWidthLineEdit.text())
cuThickness = float(self.cuThicknessLineEdit.text())
pcbThickness = float(self.pcbThicknessLineEdit.text())
targetInd = float(self.desiredIndLineEdit.text())
def errfunc(x, grad):
if grad.size > 0:
grad = Null
self.spacingLineEdit.setText(str(x[0]))
QtGui.QApplication.processEvents() # update GUI
ind = self.simulate()
err = math.fabs(ind - targetInd)
return err
opt = nlopt.opt(nlopt.LN_COBYLA, 1)
minSpacing = float(self.minSpacingLineEdit.text())
opt.set_lower_bounds([minSpacing])
opt.set_min_objective(errfunc)
opt.set_xtol_rel(1e-2)
x = opt.optimize([spacing])
minf = opt.last_optimum_value()
print "optimum at ", x[0]
print "minimum value = ", minf
print "result code = ", opt.last_optimize_result()
self.spacingLineEdit.setText(str(x[0]))
self.statusBar().showMessage("Ready.")
示例8: _minimize
# 需要导入模块: import nlopt [as 别名]
# 或者: from nlopt import opt [as 别名]
def _minimize(self,
name: str,
objective_function: Callable,
variable_bounds: Optional[List[Tuple[float, float]]] = None,
initial_point: Optional[np.ndarray] = None,
max_evals: int = 1000) -> Tuple[float, float, int]:
"""Minimize using objective function
Args:
name: NLopt optimizer name
objective_function: handle to a function that
computes the objective function.
variable_bounds: list of variable
bounds, given as pairs (lower, upper). None means
unbounded.
initial_point: initial point.
max_evals: Maximum evaluations
Returns:
tuple(float, float, int): Solution at minimum found,
value at minimum found, num evaluations performed
"""
threshold = 3 * np.pi
low = [(l if l is not None else -threshold) for (l, u) in variable_bounds]
high = [(u if u is not None else threshold) for (l, u) in variable_bounds]
opt = nlopt.opt(name, len(low))
logger.debug(opt.get_algorithm_name())
opt.set_lower_bounds(low)
opt.set_upper_bounds(high)
eval_count = 0
def wrap_objfunc_global(x, _grad):
nonlocal eval_count
eval_count += 1
return objective_function(x)
opt.set_min_objective(wrap_objfunc_global)
opt.set_maxeval(max_evals)
xopt = opt.optimize(initial_point)
minf = opt.last_optimum_value()
logger.debug('Global minimize found %s eval count %s', minf, eval_count)
return xopt, minf, eval_count
示例9: __init__
# 需要导入模块: import nlopt [as 别名]
# 或者: from nlopt import opt [as 别名]
def __init__(self, vars, solver_name):
try:
import nlopt as N
except:
raise Exception('Error: In order to use an NLopt solver, you must have NLopt installed.')
GrooveType.__init__(self, vars)
self.solver_name = solver_name
if solver_name == 'slsqp':
self.opt = N.opt(N.LD_SLSQP, len(self.vars.init_state))
elif solver_name == 'ccsaq':
self.opt = N.opt(N.LD_CCSAQ, len(self.vars.init_state))
elif solver_name == 'mma':
self.opt = N.opt(N.LD_MMA, len(self.vars.init_state))
elif solver_name == 'bobyqa':
self.opt = N.opt(N.LN_BOBYQA, len(self.vars.init_state))
elif solver_name == 'cobyla':
self.opt = N.opt(N.LN_COBYLA, len(self.vars.init_state))
elif solver_name == 'lbfgs':
self.opt = N.opt(N.LD_LBFGS, len(self.vars.init_state))
elif solver_name == 'mlsl':
self.opt = N.opt(N.GD_MLSL, len(self.vars.init_state))
elif solver_name == 'direct':
self.opt = N.opt(N.GN_DIRECT_L_RAND, len(self.vars.init_state))
elif solver_name == 'newuoa':
self.opt = N.opt(N.LN_NEWUOA_BOUND, len(self.vars.init_state))
else:
raise Exception('Invalid solver_name in subroutine [GrooveType_nlopt]!')
self.opt.set_min_objective(obj.objective_master_nlopt)
self.opt.set_xtol_rel(1e-4)
# self.opt.set_maxtime(.025)
if self.vars.bounds == ():
self.opt.set_lower_bounds(len(self.vars.init_state) * [-50.0])
self.opt.set_upper_bounds(len(self.vars.init_state) * [50.0])
else:
u = []
l = []
for b in self.vars.bounds:
u.append(b[1])
l.append(b[0])
self.opt.set_lower_bounds(l)
self.opt.set_upper_bounds(u)