Exemplo n.º 1
0
def solve_conic():

    m = pmo.block()

    m.x = pmo.variable(lb=0)
    m.y = pmo.variable(lb=0)
    m.z = pmo.variable(lb=0)

    m.p = pmo.variable()
    m.q = pmo.variable()
    m.r = pmo.variable(lb=0)

    m.k = pmo.block_tuple([
        pmo.conic.primal_power.as_domain(r1=m.x, r2=m.y, x=[None], alpha=0.2),
        pmo.conic.primal_power.as_domain(r1=m.z, r2=1, x=[None], alpha=0.4)
    ])

    m.c = pmo.constraint(body=m.x + m.y + 0.5 * m.z, rhs=2)

    m.o = pmo.objective(m.k[0].x[0] + m.k[1].x[0] - m.x, sense=pmo.maximize)

    mosek = pmo.SolverFactory("mosek")
    result = mosek.solve(m)
    assert str(result.solver.termination_condition) == "optimal"
    print("conic solution:")
    print("x: {0:.4f}, y: {1:.4f}, z: {2:.4f}".\
          format(m.x(), m.y(), m.z()))
    print("objective: {0: .5f}".\
          format(m.o()))
    print("")
Exemplo n.º 2
0
    def __init__(self, xL, xU, yL, yU):
        assert xL <= xU
        assert yL <= yU
        self._model = pmo.block()
        x = self._model.x = pmo.variable(lb=xL, ub=xU)
        y = self._model.y = pmo.variable(lb=yL, ub=yU)
        x2 = self._model.x2 = pmo.variable(lb=-pybnb.inf, ub=pybnb.inf)
        x2y = self._model.x2y = pmo.variable(lb=-pybnb.inf, ub=pybnb.inf)
        self._model.x2_c = SquaredEnvelope(x, x2)
        # Temporarily provide bounds to the x2 variable so
        # they can be used to build the McCormick
        # constraints for x2y. After that, they are no
        # longer needed as they are enforced by the
        # McCormickEnvelope constraints.
        x2.bounds = self._model.x2_c.derived_output_bounds()
        self._model.x2y_c = McCormickEnvelope(x2, y, x2y)
        x2.bounds = (-pybnb.inf, pybnb.inf)

        # original objective
        self._model.f = pmo.expression(
            (x**4 - 2 * (x**2) * y + 0.5 * (x**2) - x + (y**2) + 0.5))
        # convex relaxation
        self._model.f_convex = pmo.expression(
            (x**4 - 2 * x2y + 0.5 * (x**2) - x + (y**2) + 0.5))
        self._model.objective = pmo.objective(sense=pmo.minimize)
        self._ipopt = pmo.SolverFactory("ipopt")
        self._ipopt.options["tol"] = 1e-9
        self._last_bound_was_feasible = False

        # make sure the PyomoProblem initializer is called
        # after the model is built
        super(Rosenbrock2D, self).__init__()
Exemplo n.º 3
0
def solve_nonlinear(Aw, Af, alpha, beta, gamma, delta):

    m = pmo.block()

    m.h = pmo.variable(lb=0)
    m.w = pmo.variable(lb=0)
    m.d = pmo.variable(lb=0)

    m.c = pmo.constraint_tuple([
        pmo.constraint(body=2 * (m.h * m.w + m.h * m.d), ub=Aw),
        pmo.constraint(body=m.w * m.d, ub=Af),
        pmo.constraint(lb=alpha, body=m.h / m.w, ub=beta),
        pmo.constraint(lb=gamma, body=m.d / m.w, ub=delta)
    ])

    m.o = pmo.objective(m.h * m.w * m.d, sense=pmo.maximize)

    m.h.value, m.w.value, m.d.value = (1, 1, 1)
    ipopt = pmo.SolverFactory("ipopt")
    result = ipopt.solve(m)
    assert str(result.solver.termination_condition) == "optimal"
    print("nonlinear solution:")
    print("h: {0:.4f}, w: {1:.4f}, d: {2:.4f}".\
          format(m.h(), m.w(), m.d()))
    print("volume: {0: .5f}".\
          format(m.o()))
    print("")
Exemplo n.º 4
0
    def testMethod(obj):

        if not testing_solvers[solver, writer]:
            obj.skipTest("Solver %s (interface=%s) is not available"
                         % (solver, writer))

        m = pyutilib.misc.import_file(os.path.join(thisDir,
                                                   'kernel_problems',
                                                   problem),
                                      clear_cache=True)

        model = m.define_model(**kwds)

        opt = pmo.SolverFactory(solver, solver_io=writer)
        results = opt.solve(model)

        # non-recursive
        new_results = ((var.name, var.value)
                       for var in model.components(ctype=pmo.variable.ctype,
                                                   active=True,
                                                   descend_into=False))
        baseline_results = getattr(obj,problem+'_results')
        for name, value in new_results:
            if abs(baseline_results[name]-value) > 0.00001:
                raise IOError("Difference in baseline solution values and "
                              "current solution values using:\n" + \
                "Solver: "+solver+"\n" + \
                "Writer: "+writer+"\n" + \
                "Variable: "+name+"\n" + \
                "Solution: "+str(value)+"\n" + \
                "Baseline: "+str(baseline_results[name])+"\n")
Exemplo n.º 5
0
def solve_nonlinear():

    m = pmo.block()

    m.x = pmo.variable()
    m.y = pmo.variable()
    m.z = pmo.variable()

    m.c = pmo.constraint_tuple([
        pmo.constraint(body=0.1 * pmo.sqrt(m.x) + (2.0 / m.y), ub=1),
        pmo.constraint(body=(1.0 / m.z) + (m.y / (m.x**2)), ub=1)
    ])

    m.o = pmo.objective(m.x + (m.y**2) * m.z, sense=pmo.minimize)

    m.x.value, m.y.value, m.z.value = (1, 1, 1)
    ipopt = pmo.SolverFactory("ipopt")
    result = ipopt.solve(m)
    assert str(result.solver.termination_condition) == "optimal"
    print("nonlinear solution:")
    print("x: {0:.4f}, y: {1:.4f}, z: {2:.4f}".\
          format(m.x(), m.y(), m.z()))
    print("objective: {0: .5f}".\
          format(m.o()))
    print("")
Exemplo n.º 6
0
    def test_constraint_removal_2(self):
        m = pmo.block()
        m.x = pmo.variable()
        m.y = pmo.variable()
        m.z = pmo.variable()
        m.c1 = pmo.conic.rotated_quadratic.as_domain(2, m.x, [m.y])
        m.c2 = pmo.conic.quadratic(m.x, [m.y, m.z])
        m.c3 = pmo.constraint(m.z >= 0)
        m.c4 = pmo.constraint(m.x + m.y >= 0)
        opt = pmo.SolverFactory('mosek_persistent')
        opt.set_instance(m)

        self.assertEqual(opt._solver_model.getnumcon(), 5)
        self.assertEqual(opt._solver_model.getnumcone(), 2)

        opt.remove_block(m.c1)
        self.assertEqual(opt._solver_model.getnumcon(), 2)
        self.assertEqual(opt._solver_model.getnumcone(), 1)

        opt.remove_constraints(m.c2, m.c3)
        self.assertEqual(opt._solver_model.getnumcon(), 1)
        self.assertEqual(opt._solver_model.getnumcone(), 0)

        self.assertRaises(ValueError, opt.remove_constraint, m.c2)
        opt.add_constraint(m.c2)
        opt.add_block(m.c1)
        self.assertEqual(opt._solver_model.getnumcone(), 2)
Exemplo n.º 7
0
def solve_conic():

    m = pmo.block()

    m.t = pmo.variable()
    m.u = pmo.variable()
    m.v = pmo.variable()
    m.w = pmo.variable()

    m.k = pmo.block_tuple([
        # exp(u-t) + exp(2v + w - t) <= 1
        pmo.conic.primal_exponential.\
            as_domain(r=None,
                      x1=1,
                      x2=m.u - m.t),
        pmo.conic.primal_exponential.\
            as_domain(r=None,
                      x1=1,
                      x2=2*m.v + m.w - m.t),
        # exp(0.5u + log(0.1)) + exp(-v + log(2)) <= 1
        pmo.conic.primal_exponential.\
            as_domain(r=None,
                      x1=1,
                      x2=0.5*m.u + pmo.log(0.1)),
        pmo.conic.primal_exponential.\
            as_domain(r=None,
                      x1=1,
                      x2=-m.v + pmo.log(2)),
        # exp(-w) + exp(v-2u) <= 1
        pmo.conic.primal_exponential.\
            as_domain(r=None,
                      x1=1,
                      x2=-m.w),
        pmo.conic.primal_exponential.\
            as_domain(r=None,
                      x1=1,
                      x2=m.v - 2*m.u)])

    m.c = pmo.constraint_tuple([
        pmo.constraint(body=m.k[0].r + m.k[1].r, ub=1),
        pmo.constraint(body=m.k[2].r + m.k[3].r, ub=1),
        pmo.constraint(body=m.k[4].r + m.k[5].r, ub=1)
    ])

    m.o = pmo.objective(m.t, sense=pmo.minimize)

    mosek = pmo.SolverFactory("mosek")
    result = mosek.solve(m)
    assert str(result.solver.termination_condition) == "optimal"
    x, y, z = pmo.exp(m.u()), pmo.exp(m.v()), pmo.exp(m.w())
    print("conic solution:")
    print("x: {0:.4f}, y: {1:.4f}, z: {2:.4f}".\
          format(x, y, z))
    print("objective: {0: .5f}".\
          format(x + (y**2)*z))
    print("")
    def __init__(
        self,
        solver: str = "cbc",
        solver_params: dict = None,
    ):
        self.optimizer = aml.SolverFactory(solver)

        if solver_params:
            for param, value in solver_params:
                self.optimizer.options[param] = value
Exemplo n.º 9
0
def bounding_box(A, b, solver_name="gurobi"):
    """
    Find upper and lower bounds for each variable.

    Parameters
    ----------
    A : np.ndarray
        e.g. lhs of polytope for N-X secured network 
    b : np.ndarray
        e.g. rhs of polytope for N-X secured network 
    solver_name : str, default "gurobi"
        Solver

    Returns
    -------
    np.ndarray
        lower bounds
    np.ndarray
        upper bounds
    """
    dim = A.shape[1]

    model = pmo.block()

    variables = []
    for i in range(dim):
        setattr(model, f"x{i}", pmo.variable())
        variables.append(getattr(model, f"x{i}"))

    model.A = pmo.matrix_constraint(A, ub=b, x=variables, sparse=True)

    opt = pmo.SolverFactory(solver_name)

    lower_upper_bounds = []
    for sense in [pmo.minimize, pmo.maximize]:

        bounds = []
        for i in range(dim):
            model.objective = pmo.objective(getattr(model, f"x{i}"),
                                            sense=sense)
            result = opt.solve(model)
            assert str(result.solver.termination_condition) == "optimal"
            bounds.append(result["Problem"][0]["Lower bound"])
            del model.objective

        bounds = np.array(bounds).reshape(len(bounds), 1)
        lower_upper_bounds.append(bounds)

    return tuple(lower_upper_bounds)
Exemplo n.º 10
0
    def __init__(self, V, W,
                 pyomo_solver="ipopt",
                 pyomo_solver_io="nl",
                 integer_tolerance=1e-4):
        assert V > 0
        assert integer_tolerance > 0
        self.V = V
        self.W = W
        self._integer_tolerance = integer_tolerance
        N = range(len(self.W))
        m = self.model = pmo.block()
        x = m.x = pmo.variable_dict()
        y = m.y = pmo.variable_dict()
        for i in N:
            y[i] = pmo.variable(domain=pmo.Binary)
            for j in N:
                x[i,j] = pmo.variable(domain=pmo.Binary)

        m.B = pmo.expression(sum(y.values()))
        m.objective = pmo.objective(m.B, sense=pmo.minimize)

        m.B_nontrivial = pmo.constraint(m.B >= 1)

        m.capacity = pmo.constraint_dict()
        for i in N:
            m.capacity[i] = pmo.constraint(
                sum(x[i,j]*self.W[j] for j in N) <= self.V*y[i])

        m.assign_1 = pmo.constraint_dict()
        for j in N:
            m.assign_1[j] = pmo.constraint(
                sum(x[i,j] for i in N) == 1)

        # relax everything for the bound solves,
        # since the objective uses a simple heuristic
        self.true_domain_type = pmo.ComponentMap()
        for xij in self.model.x.components():
            self.true_domain_type[xij] = xij.domain_type
            xij.domain_type = pmo.RealSet
        for yi in self.model.y.components():
            self.true_domain_type[yi] = yi.domain_type
            yi.domain_type = pmo.RealSet

        self.opt = pmo.SolverFactory(
            pyomo_solver,
            solver_io=pyomo_solver_io)
Exemplo n.º 11
0
def solve_nonlinear():

    m = pmo.block()

    m.x = pmo.variable(lb=0)
    m.y = pmo.variable(lb=0)
    m.z = pmo.variable(lb=0)

    m.c = pmo.constraint(body=m.x + m.y + 0.5 * m.z, rhs=2)

    m.o = pmo.objective((m.x**0.2) * (m.y**0.8) + (m.z**0.4) - m.x,
                        sense=pmo.maximize)

    m.x.value, m.y.value, m.z.value = (1, 1, 1)
    ipopt = pmo.SolverFactory("ipopt")
    result = ipopt.solve(m)
    assert str(result.solver.termination_condition) == "optimal"
    print("nonlinear solution:")
    print("x: {0:.4f}, y: {1:.4f}, z: {2:.4f}".\
          format(m.x(), m.y(), m.z()))
    print("objective: {0: .5f}".\
          format(m.o()))
    print("")
Exemplo n.º 12
0
def solve_conic(Aw, Af, alpha, beta, gamma, delta):

    m = pmo.block()

    m.x = pmo.variable()
    m.y = pmo.variable()
    m.z = pmo.variable()

    m.k = pmo.block_tuple([
        pmo.conic.primal_exponential.\
            as_domain(r=None,
                      x1=1,
                      x2=m.x + m.y + pmo.log(2.0/Aw)),
        pmo.conic.primal_exponential.\
            as_domain(r=None,
                      x1=1,
                      x2=m.x + m.z + pmo.log(2.0/Aw))])

    m.c = pmo.constraint_tuple([
        pmo.constraint(body=m.k[0].r + m.k[1].r, ub=1),
        pmo.constraint(body=m.y + m.z, ub=pmo.log(Af)),
        pmo.constraint(lb=pmo.log(alpha), body=m.x - m.y, ub=pmo.log(beta)),
        pmo.constraint(lb=pmo.log(gamma), body=m.z - m.y, ub=pmo.log(delta))
    ])

    m.o = pmo.objective(m.x + m.y + m.z, sense=pmo.maximize)

    mosek = pmo.SolverFactory("mosek_direct")
    result = mosek.solve(m)
    assert str(result.solver.termination_condition) == "optimal"
    h, w, d = pmo.exp(m.x()), pmo.exp(m.y()), pmo.exp(m.z())
    print("conic solution:")
    print("h: {0:.4f}, w: {1:.4f}, d: {2:.4f}".\
          format(h, w, d))
    print("volume: {0: .5f}".\
          format(h*w*d))
    print("")
Exemplo n.º 13
0
    def test_conic(self):

        model = pmo.block()
        model.o = pmo.objective(0.0)
        model.c = pmo.constraint(body=0.0, rhs=1)

        b = model.quadratic = pmo.block()
        b.x = pmo.variable_tuple((pmo.variable(), pmo.variable()))
        b.r = pmo.variable(lb=0)
        b.c = pmo.conic.quadratic(x=b.x, r=b.r)
        model.o.expr += b.r
        model.c.body += b.r
        del b

        b = model.rotated_quadratic = pmo.block()
        b.x = pmo.variable_tuple((pmo.variable(), pmo.variable()))
        b.r1 = pmo.variable(lb=0)
        b.r2 = pmo.variable(lb=0)
        b.c = pmo.conic.rotated_quadratic(x=b.x, r1=b.r1, r2=b.r2)
        model.o.expr += b.r1 + b.r2
        model.c.body += b.r1 + b.r2
        del b

        import mosek
        if mosek.Env().getversion() >= (9, 0, 0):
            b = model.primal_exponential = pmo.block()
            b.x1 = pmo.variable(lb=0)
            b.x2 = pmo.variable()
            b.r = pmo.variable(lb=0)
            b.c = pmo.conic.primal_exponential(x1=b.x1, x2=b.x2, r=b.r)
            model.o.expr += b.r
            model.c.body += b.r
            del b

            b = model.primal_power = pmo.block()
            b.x = pmo.variable_tuple((pmo.variable(), pmo.variable()))
            b.r1 = pmo.variable(lb=0)
            b.r2 = pmo.variable(lb=0)
            b.c = pmo.conic.primal_power(x=b.x, r1=b.r1, r2=b.r2, alpha=0.6)
            model.o.expr += b.r1 + b.r2
            model.c.body += b.r1 + b.r2
            del b

            b = model.dual_exponential = pmo.block()
            b.x1 = pmo.variable()
            b.x2 = pmo.variable(ub=0)
            b.r = pmo.variable(lb=0)
            b.c = pmo.conic.dual_exponential(x1=b.x1, x2=b.x2, r=b.r)
            model.o.expr += b.r
            model.c.body += b.r
            del b

            b = model.dual_power = pmo.block()
            b.x = pmo.variable_tuple((pmo.variable(), pmo.variable()))
            b.r1 = pmo.variable(lb=0)
            b.r2 = pmo.variable(lb=0)
            b.c = pmo.conic.dual_power(x=b.x, r1=b.r1, r2=b.r2, alpha=0.4)
            model.o.expr += b.r1 + b.r2
            model.c.body += b.r1 + b.r2

        opt = pmo.SolverFactory("mosek_direct")
        results = opt.solve(model)

        self.assertEqual(results.solution.status, SolutionStatus.optimal)
Exemplo n.º 14
0
fvals = f(pw_xarray, pw_yarray, package=np)
pw_f = pmo.piecewise_nd(tri, fvals, input=[m.x, m.y], output=m.z, bound='lb')
m.approx.pw_f = pw_f

gvals = g(pw_xarray, pw_yarray, package=np)
pw_g = pmo.piecewise_nd(tri, gvals, input=[m.x, m.y], output=m.z, bound='eq')
m.approx.pw_g = pw_g

#
# Solve the approximate model to generate a warmstart for
# the real model
#

m.real.deactivate()
m.approx.activate()
glpk = pmo.SolverFactory("glpk")
status = glpk.solve(m)
assert str(status.solver.status) == "ok"
assert str(status.solver.termination_condition) == "optimal"

print("Approximate f value at MIP solution: %s" % (pw_f(
    (m.x.value, m.y.value))))
print("Approximate g value at MIP solution: %s" % (pw_g(
    (m.x.value, m.y.value))))
print("Real f value at MIP solution: %s" % (f(m.x.value, m.y.value)))
print("Real g value at MIP solution: %s" % (g(m.x.value, m.y.value)))

#
# Solve the real nonlinear model using a local solver
#
Exemplo n.º 15
0
 def get_solver(self, solverName):
     solver = pmo.SolverFactory(solverName)
     if solverName == "cbc":
         solver.options["threads"] = 4
         solver.options["sec"] = 300
     return solver
Exemplo n.º 16
0
## Each task is assigned to exactly 1 worker
model.con_task = pmo.constraint_list()
for _task in model.set_tasks:
    model.con_task.append(
        pmo.constraint(
            sum(model.var_x[(_worker, _task)]
                for _worker in model.set_workers) == 1))

# Create the objective
expr = pmo.expression_list()
for _worker in model.set_workers:
    for _task in model.set_tasks:
        expr.append(
            pmo.expression(model.param_cost[(_worker, _task)] *
                           model.var_x[(_worker, _task)]))
model.obj = pmo.objective(sum(expr), sense=pmo.minimize)

# Solve
opt = pmo.SolverFactory('cplex')
result = opt.solve(model)

# Print the solution
if result.solver.termination_condition == TerminationCondition.optimal or result.solver.status == SolverStatus.ok:
    print('Total cost = ', pmo.value(model.obj), '\n')
    for i in range(NUM_WORKERS):
        for j in range(NUM_TASKS):
            # Test if x[i,j] is 1 (with tolerance for floating point arithmetic).
            if model.var_x[(i, j)].value > 0.5:
                print('Worker %d assigned to task %d.  Cost = %d' %
                      (i, j, costs[i][j]))
Exemplo n.º 17
0
import pyomo.kernel as pmo

model = pmo.block()
model.x = pmo.variable()
model.c = pmo.constraint(model.x >= 1)
model.o = pmo.objective(model.x)

opt = pmo.SolverFactory("ipopt")

result = opt.solve(model)
assert str(result.solver.termination_condition) == "optimal"