Пример #1
0
    def _generate_model(self):
        self.model = ConcreteModel()
        model = self.model
        model._name = self.description

        model.f = Var()
        model.x = Var(bounds=(1,3))
        model.fi = Param([1,2,3],mutable=True)
        model.fi[1] = 1.0
        model.fi[2] = 2.0
        model.fi[3] = 0.0
        model.xi = Param([1,2,3],mutable=True)
        model.xi[1] = 1.0
        model.xi[2] = 2.0
        model.xi[3] = 3.0
        model.p = Var(within=NonNegativeReals)
        model.n = Var(within=NonNegativeReals)
        model.lmbda = Var([1,2,3])
        model.obj = Objective(expr=model.p+model.n)
        model.c1 = ConstraintList()
        model.c1.add((0.0, model.lmbda[1], 1.0))
        model.c1.add((0.0, model.lmbda[2], 1.0))
        model.c1.add(0.0 <= model.lmbda[3])
        model.c2 = SOSConstraint(var=model.lmbda, index=[1,2,3], sos=2)
        model.c3 = Constraint(expr=sum_product(model.lmbda) == 1)
        model.c4 = Constraint(expr=model.f==sum_product(model.fi,model.lmbda))
        model.c5 = Constraint(expr=model.x==sum_product(model.xi,model.lmbda))
        model.x = 2.75
        model.x.fixed = True

        # Make an empty SOSConstraint
        model.c6 = SOSConstraint(var=model.lmbda, index=[1,2,3], sos=2)
        model.c6.set_items([],[])
        assert len(list(model.c6.get_items())) == 0
Пример #2
0
    def test_EXPORT_suffixes_no_datatype(self):
        model = ConcreteModel()
        model.sosno = Suffix(direction=Suffix.EXPORT,datatype=None)
        model.y = Var([1,2,3])
        model.obj = Objective(expr=sum_product(model.y))

        # The NL writer will convert this constraint to ref and sosno
        # suffixes on model.y
        model.sos_con = SOSConstraint(var=model.y, index=[1,2,3], sos=1)

        for i in [1,2,3]:
            model.sosno.set_value(model.y[i],-1)
        
        try:
            model.write(filename=join(currdir,"junk.nl"),
                        format=ProblemFormat.nl,
                        io_options={"symbolic_solver_labels" : False})
        except RuntimeError:
            pass
        else:
            os.remove(join(currdir,"junk.nl"))
            self.fail("The NL writer should have thrown an exception "\
                      "when using an EXPORT suffix with datatype=None")
        try:
            os.remove(join(currdir,"junk.nl"))
        except:
            pass
Пример #3
0
    def test_EXPORT_suffixes_with_SOSConstraint_duplicateref(self):
        model = ConcreteModel()
        model.ref = Suffix(direction=Suffix.EXPORT,datatype=Suffix.INT)
        model.y = Var([1,2,3])
        model.obj = Objective(expr=sum_product(model.y))

        # The NL writer will convert this constraint to ref and sosno
        # suffixes on model.y
        model.sos_con = SOSConstraint(var=model.y, index=[1,2,3], sos=1)

        for i,val in zip([1,2,3],[11,12,13]):
            model.ref.set_value(model.y[i],val)
        
        try:
            model.write(filename=join(currdir,"junk.nl"),
                        format=ProblemFormat.nl,
                        io_options={"symbolic_solver_labels" : False})
        except RuntimeError:
            pass
        else:
            os.remove(join(currdir,"junk.nl"))
            self.fail("The NL writer should have thrown an exception "\
                      "when overlap of SOSConstraint generated suffixes "\
                      "and user declared suffixes occurs.")
        
        try:
            os.remove(join(currdir,"junk.nl"))
        except:
            pass
Пример #4
0
    def _generate_model(self):
        self.model = None
        self.model = ConcreteModel()
        model = self.model
        model._name = self.description

        n = 7
        m = 7
        model.N = RangeSet(1,n)
        model.M = RangeSet(1,m)

        model.c = Param(model.N, rule=c_rule)

        model.b = Param(model.M, rule=b_rule)

        model.A = Param(model.M, model.N, rule=A_rule)

        model.x = Var(model.N, within=NonNegativeReals)
        model.y = Var(model.M, within=NonNegativeReals)

        model.cost = Objective(expr=sum_product(model.c, model.x))

        model.primalcon = Constraint(model.M, rule=primalcon_rule)

        #model.dual = Suffix(direction=Suffix.IMPORT)
        #model.rc = Suffix(direction=Suffix.IMPORT)
        model.slack = Suffix(direction=Suffix.IMPORT)
        model.urc = Suffix(direction=Suffix.IMPORT)
        model.lrc = Suffix(direction=Suffix.IMPORT)
Пример #5
0
def define_model(**kwds):

    model = ConcreteModel()

    model.x = Var(INDEX_SET, bounds=(-5, 4))  # domain variable
    model.Fx = Var(INDEX_SET)  # range variable
    model.p = Param(INDEX_SET, initialize=1.0)

    model.obj = Objective(expr=sum_product(model.Fx),
                          sense=kwds.pop('sense', maximize))

    model.piecewise = Piecewise(INDEX_SET,
                                model.Fx,
                                model.x,
                                pw_pts=DOMAIN_PTS,
                                f_rule=F,
                                **kwds)

    #Fix the answer for testing purposes
    model.set_answer_constraint1 = Constraint(expr=model.x[1] == -5.0)
    model.set_answer_constraint2 = Constraint(expr=model.x[2] == -3.0)
    model.set_answer_constraint3 = Constraint(expr=model.x[3] == -2.5)
    model.set_answer_constraint4 = Constraint(expr=model.x[4] == -1.5)
    model.set_answer_constraint5 = Constraint(expr=model.x[5] == 2.0)
    model.set_answer_constraint6 = Constraint(expr=model.x[6] == 3.5)
    model.set_answer_constraint7 = Constraint(expr=model.x[7] == 4.0)

    return model
Пример #6
0
def create_instance(scenario_name):
    cnt = d[scenario_name]

    model = ConcreteModel()
    # first stage
    model.x = Var(bounds=(0, 10))
    # first stage derived
    model.y = Expression(expr=model.x + 1)
    model.fx = Var()
    # second stage
    model.z = Var(bounds=(-10, 10))
    # second stage derived
    model.q = Expression(expr=model.z**2)
    model.fz = Var()
    model.r = Var()
    # stage costs
    model.StageCost = Expression([1, 2])
    model.StageCost.add(1, model.fx)
    model.StageCost.add(2, -model.fz + model.r - cnt)
    model.o = Objective(expr=sum_product(model.StageCost))

    model.ZERO = Param(initialize=0, mutable=True)
    if cnt == 0:
        cnt = model.ZERO

    model.c_first_stage = Constraint(expr=model.x >= 0)

    # test our handling of intermediate variables that
    # are created by Piecewise but can not necessarily
    # be declared on the scenario tree
    model.p_first_stage = Piecewise(model.fx,
                                    model.x,
                                    pw_pts=[0., 2., 5., 7., 10.],
                                    pw_constr_type='EQ',
                                    pw_repn='INC',
                                    f_rule=[10., 10., 9., 10., 10.],
                                    force_pw=True)

    model.c_second_stage = Constraint(expr=model.x + model.r * cnt >= -100)
    model.r_second_stage = Constraint(expr=inequality(-cnt, model.r, 0))
    # exercise more of the code by making this an indexed
    # block
    model.p_second_stage = Piecewise([1],
                                     model.fz,
                                     model.z,
                                     pw_pts=[-10, -5., 0., 5., 10.],
                                     pw_constr_type='EQ',
                                     pw_repn='INC',
                                     f_rule=[0., 0., -1., 2. + cnt, 1.],
                                     force_pw=True)

    return model
Пример #7
0
def define_model(**kwds):

    model = ConcreteModel()

    model.x = Var(INDEX) # domain variable
    
    model.Fx = Var(INDEX) # range variable

    model.obj = Objective(expr=sum_product(model.Fx)+sum_product(model.x), sense=kwds.pop('sense',maximize))

    model.piecewise = Piecewise(INDEX,model.Fx,model.x,
                                  pw_pts=DOMAIN_PTS,
                                  f_rule=F,
                                  unbounded_domain_var=True,
                                  **kwds)

    #Fix the answer for testing purposes
    model.set_answer_constraint1 = Constraint(expr= model.x[1] == 0.5) # Fx1 should solve to 0
    model.set_answer_constraint2 = Constraint(expr= model.x[2] == 1.0)  # 
    model.set_answer_constraint3 = Constraint(expr= model.Fx[2] == 0.5) # 
    model.set_answer_constraint4 = Constraint(expr= model.x[3] == 1.5) # Fx3 should solve to 1
    model.set_answer_constraint5 = Constraint(expr= model.x[4] == 2.5) # Fx4 should solve to 1.5
    
    return model
Пример #8
0
    def add_cut(self, first=False):
        self._iter += 1
        model = self._model

        self._wprod[self._iter] = self._compute_weight_weight_inner_product()
        if first is True:
            self._alphas[self._iter] = -(
                self._compute_objective_term() +
                (self._ph._rho / 2.0) * self._wprod[self._iter])
        else:
            self._alphas[self._iter] = -(self._compute_objective_term(
            )) + self._compute_xbar_weight_inner_product()

        if self._solved is True:
            if self._compute_convergence() is True:
                return True

        model.del_component('cuts')
        model.cuts = Set(initialize=sorted(self._alphas.keys()))
        model.del_component('beta')
        model.beta = Var(model.cuts, within=NonNegativeReals)
        model.del_component('beta_sum_one')
        model.beta_sum_one = Constraint(expr=sum_product(model.beta) == 1)
        model.del_component('obj')
        model.obj = Objective(expr=sum(self._alphas[i] * model.beta[i]
                                       for i in model.cuts))

        self._wbars[self._iter] = {}
        for stage in self._ph._scenario_tree._stages[:
                                                     -1]:  # all blended stages
            for tree_node in stage._tree_nodes:
                self._wbars[self._iter][tree_node._name] = copy.deepcopy(
                    tree_node._wbars)
                block = getattr(model, tree_node._name)

                def _c_rule(block, i):
                    lhs = sum(model.beta[k] * self._wbars[k][tree_node._name][
                        block.id_to_var[i][0]][block.id_to_var[i][1]]
                              for k in model.beta.index_set())
                    if not isinstance(lhs, ExpressionBase):
                        return Constraint.Skip
                    return lhs == 0

                block.del_component('con')
                block.con = Constraint(block.var_index, rule=_c_rule)
        return False
Пример #9
0
def pysp_instance_creation_callback(scenario_name, node_names):
    global cnt

    model = ConcreteModel()
    model.x = Var(bounds=(0,10))
    model.y = Expression(expr=model.x + 1)
    model.z = Var(bounds=(-10, 10))
    model.q = Expression(expr=model.z**2)
    model.StageCost = Expression([1,2])
    model.StageCost.add(1, model.x)
    model.StageCost.add(2, -model.z)
    model.o = Objective(expr=sum_product(model.StageCost))
    model.c = ConstraintList()
    model.c.add(model.x >= cnt)
    model.c.add(model.z <= cnt**2)

    cnt += 1

    return model
Пример #10
0
    def _generate_model(self):
        self.model = ConcreteModel()
        model = self.model
        model._name = self.description

        model.a = Param(initialize=0.1)
        model.x = Var(within=NonNegativeReals)
        model.y = Var([1, 2], within=NonNegativeReals)

        model.obj = Objective(expr=model.x + model.y[1] + 2 * model.y[2])
        model.c1 = Constraint(expr=model.a <= model.y[2])
        model.c2 = Constraint(expr=(2.0, model.x, 10.0))
        model.c3 = SOSConstraint(var=model.y, index=[1, 2], sos=1)
        model.c4 = Constraint(expr=sum_product(model.y) == 1)

        # Make an empty SOSConstraint
        model.c5 = SOSConstraint(var=model.y, index=[1, 2], sos=1)
        model.c5.set_items([], [])
        assert len(list(model.c5.get_items())) == 0
Пример #11
0
    def _generate_model(self):
        self.model = ConcreteModel()
        model = self.model
        model._name = self.description

        model.a = Param(initialize=0.1)
        model.x = Var(within=NonNegativeReals)
        model.y = Var([1,2],within=NonNegativeReals)

        model.obj = Objective(expr=model.x + model.y[1]+2*model.y[2])
        model.c1 = Constraint(expr=model.a <= model.y[2])
        model.c2 = Constraint(expr=(2.0, model.x, 10.0))
        model.c3 = SOSConstraint(var=model.y, index=[1,2], sos=1)
        model.c4 = Constraint(expr=sum_product(model.y) == 1)

        # Make an empty SOSConstraint
        model.c5 = SOSConstraint(var=model.y, index=[1,2], sos=1)
        model.c5.set_items([],[])
        assert len(list(model.c5.get_items())) == 0
Пример #12
0
def define_model(**kwds):

    model = ConcreteModel()

    model.x = Var(INDEX_SET1, INDEX_SET2, bounds=(0,6)) # domain variable
    model.Fx = Var(INDEX_SET1, INDEX_SET2) # range variable
    model.p = Param(INDEX_SET1, INDEX_SET2, initialize=1.0)

    model.obj = Objective(expr=sum_product(model.Fx), sense=kwds.pop('sense',maximize))

    model.piecewise = Piecewise(INDEX_SET1,INDEX_SET2,model.Fx,model.x,
                                  pw_pts=DOMAIN_PTS,
                                  f_rule=F, **kwds)

    #Fix the answer for testing purposes
    model.set_answer_constraint1 = Constraint(INDEX_SET2,rule= lambda model,t2,t3: model.x['1',t2,t3] == 0.0)
    model.set_answer_constraint2 = Constraint(INDEX_SET2,rule= lambda model,t2,t3: model.x['2',t2,t3] == 3.0)
    model.set_answer_constraint3 = Constraint(INDEX_SET2,rule= lambda model,t2,t3: model.x['3',t2,t3] == 5.5)
    model.set_answer_constraint4 = Constraint(INDEX_SET2,rule= lambda model,t2,t3: model.x['40',t2,t3] == 6.0)

    return model
Пример #13
0
    def test_EXPORT_suffixes_float(self):
        model = ConcreteModel()
        model.junk = Suffix(direction=Suffix.EXPORT, datatype=Suffix.FLOAT)
        model.junk_inactive = Suffix(direction=Suffix.EXPORT,
                                     datatype=Suffix.FLOAT)

        model.x = Var()
        model.junk.set_value(model.x, 1)
        model.junk_inactive.set_value(model.x, 1)

        model.y = Var([1, 2], dense=True)
        model.junk.set_value(model.y, 2)
        model.junk_inactive.set_value(model.y, 2)

        model.obj = Objective(expr=model.x + sum_product(model.y))
        model.junk.set_value(model.obj, 3)
        model.junk_inactive.set_value(model.obj, 3)

        model.conx = Constraint(expr=model.x >= 1)
        model.junk.set_value(model.conx, 4)
        model.junk_inactive.set_value(model.conx, 4)

        model.cony = Constraint([1, 2], rule=lambda model, i: model.y[i] >= 1)
        model.junk.set_value(model.cony, 5)
        model.junk_inactive.set_value(model.cony, 5)

        model.junk.set_value(model, 6)
        model.junk_inactive.set_value(model, 6)

        # This one should NOT end up in the NL file
        model.junk_inactive.deactivate()

        model.write(filename=join(currdir, "EXPORT_suffixes.test.nl"),
                    format=ProblemFormat.nl,
                    io_options={"symbolic_solver_labels": False})

        _test, _base = join(currdir, "EXPORT_suffixes.test.nl"), join(
            currdir, "EXPORT_suffixes_float.baseline.nl")
        self.assertTrue(cmp(_test, _base),
                        msg="Files %s and %s differ" % (_test, _base))
Пример #14
0
model.b = Param(model.M)


def A_rule(model, i, j):
    if i == 4:
        i = 5
    elif i == 5:
        i = 4
    return 2 if i == j else 1


model.A = Param(model.M, model.N)

model.x = Var(model.N, within=NonNegativeReals)
model.y = Var(model.M, within=NonNegativeReals)

model.cost = Objective(expr=sum_product(model.c, model.x))


def primalcon_rule(model, i):
    return sum(model.A[i, j] * model.x[j] for j in model.N) >= model.b[i]


model.primalcon = Constraint(model.M)

model.dual = Suffix(direction=Suffix.IMPORT)
model.rc = Suffix(direction=Suffix.IMPORT)
model.slack = Suffix(direction=Suffix.IMPORT)
model.urc = Suffix(direction=Suffix.IMPORT)
model.lrc = Suffix(direction=Suffix.IMPORT)
Пример #15
0
    return model.x[t1, t2] == sum(model.y[t1, t2, i] * PIECEWISE_PTS[t1, t2][i]
                                  for i in xrange(len(PIECEWISE_PTS[t1, t2])))


def constraint2_rule(model, t1, t2):
    return model.Fx[t1,
                    t2] == sum(model.y[t1, t2, i] * F(PIECEWISE_PTS[t1, t2][i])
                               for i in xrange(len(PIECEWISE_PTS[t1, t2])))


def constraint3_rule(model, t1, t2):
    return sum(model.y[t1, t2, j]
               for j in xrange(len(PIECEWISE_PTS[t1, t2]))) == 1


model.obj = Objective(expr=sum_product(model.Fx), sense=maximize)
model.constraint1 = Constraint(INDEX_SET1, INDEX_SET2, rule=constraint1_rule)
model.constraint2 = Constraint(INDEX_SET1, INDEX_SET2, rule=constraint2_rule)
model.constraint3 = Constraint(INDEX_SET1, INDEX_SET2, rule=constraint3_rule)
model.SOS_set_constraint = SOSConstraint(INDEX_SET1,
                                         INDEX_SET2,
                                         var=model.y,
                                         index=model.SOS_indices,
                                         sos=2)

#Fix the answer for testing purposes
model.set_answer_constraint1 = Constraint(expr=model.x[1, 1] == 2.5)
model.set_answer_constraint2 = Constraint(expr=model.x[2, 1] == 1.5)
model.set_answer_constraint3 = Constraint(expr=model.x[1, 2] == 2.5)
model.set_answer_constraint4 = Constraint(expr=model.x[2, 2] == 1.5)
model.set_answer_constraint5 = Constraint(expr=model.x[1, 3] == 2.5)
Пример #16
0
def ComputeFirstStageCost_rule(model):
    return sum_product(model.PlantingCostPerAcre, model.DevotedAcreage)
Пример #17
0
    def _generate_model(self):
        self.model = ConcreteModel()
        model = self.model
        model._name = self.description

        model.s = Set(initialize=[1, 2])

        model.x_unused = Var(within=Integers)
        model.x_unused.stale = False

        model.x_unused_initialy_stale = Var(within=Integers)
        model.x_unused_initialy_stale.stale = True

        model.X_unused = Var(model.s, within=Integers)
        model.X_unused_initialy_stale = Var(model.s, within=Integers)
        for i in model.s:
            model.X_unused[i].stale = False
            model.X_unused_initialy_stale[i].stale = True

        model.x = Var(within=RangeSet(None, None))
        model.x.stale = False

        model.x_initialy_stale = Var(within=Integers)
        model.x_initialy_stale.stale = True

        model.X = Var(model.s, within=Integers)
        model.X_initialy_stale = Var(model.s, within=Integers)
        for i in model.s:
            model.X[i].stale = False
            model.X_initialy_stale[i].stale = True

        model.obj = Objective(expr= model.x + \
                                    model.x_initialy_stale + \
                                    sum_product(model.X) + \
                                    sum_product(model.X_initialy_stale))

        model.c = ConstraintList()
        model.c.add(model.x >= 1)
        model.c.add(model.x_initialy_stale >= 1)
        model.c.add(model.X[1] >= 0)
        model.c.add(model.X[2] >= 1)
        model.c.add(model.X_initialy_stale[1] >= 0)
        model.c.add(model.X_initialy_stale[2] >= 1)

        # Test that stale flags get set
        # on inactive blocks (where "inactive blocks" mean blocks
        # that do NOT follow a path of all active parent blocks
        # up to the top-level model)
        flat_model = model.clone()
        model.b = Block()
        model.B = Block(model.s)
        model.b.b = flat_model.clone()
        model.B[1].b = flat_model.clone()
        model.B[2].b = flat_model.clone()

        model.b.deactivate()
        model.B.deactivate()
        model.b.b.activate()
        model.B[1].b.activate()
        model.B[2].b.deactivate()
        assert model.b.active is False
        assert model.B[1].active is False
        assert model.B[1].active is False
        assert model.b.b.active is True
        assert model.B[1].b.active is True
        assert model.B[2].b.active is False
Пример #18
0
def ComputeSecondStageCost_rule(model):
    expr = sum_product(model.PurchasePrice, model.QuantityPurchased)
    expr -= sum_product(model.SubQuotaSellingPrice, model.QuantitySubQuotaSold)
    expr -= sum_product(model.SuperQuotaSellingPrice,
                        model.QuantitySuperQuotaSold)
    return expr
Пример #19
0
def ConstrainTotalAcreage_rule(model):
    return sum_product(model.DevotedAcreage) <= model.TOTAL_ACREAGE
Пример #20
0
    def _generate_model(self):
        self.model = None
        self.model = ConcreteModel()
        model = self.model
        model._name = self.description

        model.s = Set(initialize=[1,2])

        model.x_unused = Var()
        model.x_unused.stale = False

        model.x_unused_initialy_stale = Var()
        model.x_unused_initialy_stale.stale = True

        model.X_unused = Var(model.s)
        model.X_unused_initialy_stale = Var(model.s)
        for i in model.s:
            model.X_unused[i].stale = False
            model.X_unused_initialy_stale[i].stale = True

        model.x = Var()
        model.x.stale = False

        model.x_initialy_stale = Var()
        model.x_initialy_stale.stale = True

        model.X = Var(model.s)
        model.X_initialy_stale = Var(model.s)
        for i in model.s:
            model.X[i].stale = False
            model.X_initialy_stale[i].stale = True

        model.obj = Objective(expr= model.x + \
                                    model.x_initialy_stale + \
                                    sum_product(model.X) + \
                                    sum_product(model.X_initialy_stale))

        model.c = ConstraintList()
        model.c.add( model.x          >= 1 )
        model.c.add( model.x_initialy_stale    >= 1 )
        model.c.add( model.X[1]       >= 0 )
        model.c.add( model.X[2]       >= 1 )
        model.c.add( model.X_initialy_stale[1] >= 0 )
        model.c.add( model.X_initialy_stale[2] >= 1 )

        # Test that stale flags do not get updated
        # on inactive blocks (where "inactive blocks" mean blocks
        # that do NOT follow a path of all active parent blocks
        # up to the top-level model)
        flat_model = model.clone()
        model.b = Block()
        model.B = Block(model.s)
        model.b.b = flat_model.clone()
        model.B[1].b = flat_model.clone()
        model.B[2].b = flat_model.clone()

        model.b.deactivate()
        model.B.deactivate()
        model.b.b.activate()
        model.B[1].b.activate()
        model.B[2].b.deactivate()
        assert model.b.active is False
        assert model.B[1].active is False
        assert model.B[1].active is False
        assert model.b.b.active is True
        assert model.B[1].b.active is True
        assert model.B[2].b.active is False