Пример #1
0
    def __init__(self):

        # Initialize Model
        self.model = pyo.AbstractModel()
        self.model.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT)

        # Declare Parameters
        self.model.users = pyo.Param(within=pyo.NonNegativeIntegers)
        self.model.nodes = pyo.Param(within=pyo.NonNegativeIntegers)
        self.model.links = pyo.Param(within=pyo.NonNegativeIntegers)
        self.model.nodes_idx = pyo.Param(within=pyo.NonNegativeIntegers)
        self.model.operators = pyo.Param(within=pyo.NonNegativeIntegers)

        # Set initialization
        self.model.u = pyo.RangeSet(1, self.model.users)
        self.model.n = pyo.RangeSet(1, self.model.nodes)
        self.model.l = pyo.RangeSet(1, self.model.links)
        self.model.i = pyo.RangeSet(1, self.model.nodes_idx)
        self.model.o = pyo.RangeSet(1, self.model.operators)

        # Parameters
        self.model.origin = pyo.Param(self.model.l)
        self.model.destination = pyo.Param(self.model.l)
        self.model.t = pyo.Param(self.model.l)
        self.model.c = pyo.Param(self.model.l)
        self.model.w = pyo.Param(self.model.l)
        self.model.link_oper = pyo.Param(self.model.l)
        self.model.d = pyo.Param(self.model.u)
        self.model.O = pyo.Param(self.model.u)
        self.model.D = pyo.Param(self.model.u)
        self.model.utility = pyo.Param(self.model.u)
        self.model.N = pyo.Param(self.model.n)
        self.model.heads = pyo.Param(self.model.i, self.model.i, default=0)
        self.model.tails = pyo.Param(self.model.i, self.model.i, default=0)
    def setUp(self):
        ##### Creating a Pyomo Model from the data in Chan et al. Example 1 #####
        A = np.array([[2, 5], [2, -3], [2, 1], [-2, -1]])
        #b = np.array([[10],[-6],[4],[-10]])
        x0 = np.array([[2.5], [3]])

        test_model = pyo.ConcreteModel()
        test_model.varindex = pyo.RangeSet(2)
        test_model.numvars = pyo.Param(initialize=2)
        test_model.eqindex = pyo.RangeSet(4)
        test_model.numeqs = pyo.Param(initialize=4)
        test_model.x = pyo.Var(test_model.varindex)

        ##### Importing the A and b as param objects #####
        def A_mat_func(model, i, j):
            return A[i - 1, j - 1]

        test_model.Amat = pyo.Param(test_model.eqindex,
                                    test_model.varindex,
                                    rule=A_mat_func)
        test_model.bvec = pyo.Param(test_model.eqindex,
                                    initialize={
                                        1: 10,
                                        2: -6,
                                        3: 4,
                                        4: -10
                                    })

        ##### Creating the GIO Objects #####
        self.example1Chan = GIO(test_model.Amat,test_model.bvec,x0,\
                                4,2,'T')
        self.ex1Chan_testingGIOallmethod = GIO(test_model.Amat,test_model.bvec,x0,\
                                               4,2,'T')
Пример #3
0
def max_sum_rate_opt(H):
    """
    Single-cell sum rate maximization, as an example to show that the
    analytical expression
    w_mmse_k =              + ∑_{i≠k} q_i h_i h_i^H)^{-1} h_k
                \sqrt{p_k} ---------------------------------------
                          ||(I + ∑_{i≠k} q_i h_i h_i^H)^{-1} h_k||
    H:
    complex CSI, shape is (K, M)


    Returns
    -------

    """
    model = pe.ConcreteModel()
    K, M = H.shape[0], H.shape[1]
    users = pe.RangeSet(K)
    antennas = pe.RangeSet(M)
    complex = pe.RangeSet(2)
    model.w = pe.Var(users, antennas, complex, domain=pe.Reals)  # (K, M,

    # 2) real-value

    def comp_norm(x, y):
        return x * x + y * y

    def cons_norm(model, u):
        norm_u = pe.quicksum(
            comp_norm(model.w[u][a][0], model.w[u][a][1]) for a in antennas)
        return norm_u <= 1

    model.cons_norm = pe.Constraint(users, rule=cons_norm)
Пример #4
0
def create_model9():

    # clplatea OXR2-MN-V-0
    model = aml.ConcreteModel()

    p = 71
    wght = -0.1
    hp2 = 0.5 * p**2

    model.x = aml.Var(aml.RangeSet(1, p), aml.RangeSet(1, p), initialize=0.0)

    def f(model):
        return sum(0.5 * (model.x[i, j] - model.x[i, j - 1]) ** 2 + \
                   0.5 * (model.x[i, j] - model.x[i - 1, j]) ** 2 + \
                   hp2 * (model.x[i, j] - model.x[i, j - 1]) ** 4 + \
                   hp2 * (model.x[i, j] - model.x[i - 1, j]) ** 4 \
                   for i in range(2, p + 1) for j in range(2, p + 1)) + (wght * model.x[p, p])

    model.f = aml.Objective(rule=f)

    for j in range(1, p + 1):
        model.x[1, j] = 0.0
        model.x[1, j].fixed = True

    return model
Пример #5
0
def run():
    model = pyo.ConcreteModel()

    #Parameter and Sets
    model.T = pyo.Param(initialize=10)
    model.M = pyo.Param(initialize=4)
    model.LimProd = pyo.Param(initialize=10)

    model.setT = pyo.RangeSet(1, model.T)
    model.setM = pyo.RangeSet(1, model.M)

    #variables
    model.x = pyo.Var(model.setM, model.setT, within=pyo.Integers)

    #obj function
    model.obj = pyo.Objective(expr=pyo.summation(model.x), sense=pyo.maximize)

    #constraints
    model.C1 = pyo.Constraint(model.setT, rule=firstRule)
    model.C2 = pyo.Constraint(range(3, model.T + 1), rule=secondRule)
    model.C3 = pyo.Constraint(model.setT, rule=thirdRule)
    model.C4 = pyo.Constraint(range(2, model.T + 1), rule=fourthRule)
    model.C5 = pyo.Constraint(model.setM, model.setT, rule=fifthRule)

    #solve
    opt = SolverFactory('gurobi')
    opt.options['MIPgap'] = 0
    opt.options['TimeLimit'] = 10
    results = opt.solve(model, tee=True)

    print(pyo.value(model.obj))
Пример #6
0
def model():
    m = pyo.ConcreteModel()
    m.fs = FlowsheetBlock(default={"dynamic": False})
    m.fs.prop_water = iapws95.Iapws95ParameterBlock()
    n_waterwalls = 10
    m.fs.ww_zones = pyo.RangeSet(n_waterwalls)
    m.fs.Waterwalls = WaterwallSection(
        m.fs.ww_zones,
        default={
            "dynamic": False,
            "has_holdup": False,
            "property_package": m.fs.prop_water,
            "has_heat_transfer": True,
            "has_pressure_change": True,
        },
    )

    def arc_rule(b, i):
        return {
            "source": m.fs.Waterwalls[i].outlet,
            "destination": m.fs.Waterwalls[i + 1].inlet
        }

    m.arc = Arc(pyo.RangeSet(n_waterwalls - 1), rule=arc_rule)

    # Pyomo expands arcs writing constraints outlet unit 1 = inlet unit 2
    pyo.TransformationFactory("network.expand_arcs").apply_to(m)

    return m
def multiclass_SVM(weights, SVM_regularization_parameter, label_to_train,
                   new_label_values, data_to_train, number_of_renewable_energy,
                   correspondence_time_period_line_all_samples,
                   sample_to_train, sample_by_line):

    model = pe.ConcreteModel('multiclass_SVM')

    model.label_to_train = label_to_train
    model.data_to_train = data_to_train
    model.SVM_regularization_parameter = SVM_regularization_parameter
    model.weights = pd.concat([weights] * (1 + number_of_renewable_energy))
    model.correspondence_time_period_line_all_samples = correspondence_time_period_line_all_samples
    model.sample_to_train = sample_to_train
    model.sample_by_line = sample_by_line

    number_of_labels = max(new_label_values)
    number_of_time_periods = len(label_to_train)

    model.indexes_labels = pe.RangeSet(number_of_labels)
    model.indexes_time_periods = pe.RangeSet(number_of_time_periods)

    model.alpha_variables = pe.Var(model.indexes_labels,
                                   model.indexes_time_periods,
                                   within=pe.NonNegativeReals)

    model.constraint_sum_variables_equal_one = pe.Constraint(
        model.indexes_time_periods, rule=constraint_sum_variables_equal_one)

    model.objective_function = pe.Objective(rule=objective_function,
                                            sense=pe.minimize)

    return model
    def _prepare_pyomo_get_inverse_cost_vector_model(self):
        model2 = pyo.AbstractModel()

        model2.m = pyo.Param(
            within=pyo.NonNegativeIntegers)  # количество ограничений
        model2.n = pyo.Param(
            within=pyo.NonNegativeIntegers)  # количество переменных
        model2.nx = pyo.Param(
            within=pyo.NonNegativeIntegers)  # количество обычных переменных
        model2.nbin = pyo.Param(
            within=pyo.NonNegativeIntegers)  # количество бинарных переменных

        model2.I = pyo.RangeSet(1, model2.m)  # индексы ограничений
        model2.J = pyo.RangeSet(1, model2.n)  # индексы переменных
        model2.Jx = pyo.RangeSet(1, model2.nx)  # индексы обычных переменных
        model2.Jbin = pyo.RangeSet(1,
                                   model2.nbin)  # индексы бинарных переменных

        model2.Ax = pyo.Param(model2.I,
                              model2.Jx)  # объявляем матрицу ограничений для x
        model2.Abin = pyo.Param(
            model2.I, model2.Jbin)  # объявляем матрицу ограничений для bin
        model2.b = pyo.Param(model2.I)  # правые части
        model2.c = pyo.Param(model2.Jx)  # коэффициенты цф
        model2.bounds = pyo.Param(model2.J)  # границы
        model2.sense = pyo.Param(model2.I)  # знаки в ограничениях

        # the next line declares a variable indexed by the set J
        model2.x = pyo.Var(model2.Jx, domain=pyo.Reals)
        model2.bin = pyo.Var(model2.Jbin, domain=pyo.Binary)

        def obj_expression(m):
            return pyo.summation(m.c, m.x)

        model2.OBJ = pyo.Objective(rule=obj_expression)

        def ax_constraint_rule(m, i):
            if m.sense[i] == -1:
                return sum(m.Ax[i, j] * m.x[j]
                           for j in m.Jx) + sum(m.Abin[i, j] * m.bin[j]
                                                for j in m.Jbin) <= m.b[i]
            if m.sense[i] == 0:
                return sum(m.Ax[i, j] * m.x[j]
                           for j in m.Jx) + sum(m.Abin[i, j] * m.bin[j]
                                                for j in m.Jbin) == m.b[i]
            if m.sense[i] == 1:
                return sum(m.Ax[i, j] * m.x[j]
                           for j in m.Jx) + sum(m.Abin[i, j] * m.bin[j]
                                                for j in m.Jbin) >= m.b[i]

        # the next line creates one constraint for each member of the set model.I
        model2.AxbConstraint = pyo.Constraint(model2.I,
                                              rule=ax_constraint_rule)

        def bounds_rule(m, j):
            return (m.bounds[j][0], m.x[j], m.bounds[j][1])

        model2.boundx = pyo.Constraint(model2.Jx, rule=bounds_rule)
        self._solve_tool_inverse_MPEC_model = model2
Пример #9
0
    def __setup_model(self):
        # Number of timestamps
        self.model.n_timestamps = pyo.Param(domain=pyo.PositiveIntegers)
        # Number of Pods
        self.model.n_pods = pyo.Param(domain=pyo.PositiveIntegers)

        self.model.T = pyo.RangeSet(0, self.model.n_timestamps - 1)  # 0..95
        self.model.N = pyo.RangeSet(0, self.model.n_pods - 1)  # 0..n - 1
Пример #10
0
def create_sudoku_model(board):

    model = pyo.ConcreteModel()

    # store the starting board for the model
    model.board = board

    # create sets for rows columns and squares
    model.ROWS = pyo.RangeSet(1, 9)
    model.COLS = pyo.RangeSet(1, 9)
    model.SUBSQUARES = pyo.RangeSet(1, 9)
    model.VALUES = pyo.RangeSet(1, 9)

    # create the binary variables to define the values
    model.y = pyo.Var(model.ROWS, model.COLS, model.VALUES, within=pyo.Binary)

    # fix variables based on the current board
    for (r, c, v) in board:
        model.y[r, c, v].fix(1)

    # create the objective - this is a feasibility problem
    # so we just make it a constant
    model.obj = pyo.Objective(expr=1.0)

    # @row_col_cons:
    # exactly one number in each row
    def _RowCon(model, r, v):
        return sum(model.y[r, c, v] for c in model.COLS) == 1

    model.RowCon = pyo.Constraint(model.ROWS, model.VALUES, rule=_RowCon)

    # exactly one number in each column
    def _ColCon(model, c, v):
        return sum(model.y[r, c, v] for r in model.ROWS) == 1

    model.ColCon = pyo.Constraint(model.COLS, model.VALUES, rule=_ColCon)

    # @:row_col_cons

    # @subsq_con:
    # exactly one number in each subsquare
    def _SqCon(model, s, v):
        return sum(model.y[r, c, v] for (r, c) in subsq_to_row_col[s]) == 1

    model.SqCon = pyo.Constraint(model.SUBSQUARES, model.VALUES, rule=_SqCon)

    # @:subsq_con

    # @num_con:
    # exactly one number in each cell
    def _ValueCon(model, r, c):
        return sum(model.y[r, c, v] for v in model.VALUES) == 1

    model.ValueCon = pyo.Constraint(model.ROWS, model.COLS, rule=_ValueCon)
    # @:num_con

    return model
Пример #11
0
    def __init__(
        self,
        demand,
        t_max=30,
        a_max=3,
        initial_inventory={
            1: 0,
            2: 36
        },
        fixed_order_cost=225,
        variable_order_cost=650,
        holding_cost=130,
        emergency_procurement_cost=3250,
        wastage_cost=650,
        M=100,
        additional_fifo_constraints=True,
        weekly_policy=False,
        shelf_life_at_arrival_dist=[0, 0, 1],
    ):

        self.model = pyo.ConcreteModel()

        # Check that `shelf_life_at_arrival_dist` sums to 1 and had right
        # number of elements
        assert (
            len(shelf_life_at_arrival_dist) == a_max
        ), "`shelf_life_at_arrival_dist` must have number of elements equal to `a_max`"
        assert (np.sum(shelf_life_at_arrival_dist) == 1
                ), "`shelf_life_at_arrival_dist` must sum to 1"
        self.shelf_life_at_arrival_dist = shelf_life_at_arrival_dist

        self.model.T = pyo.RangeSet(1, t_max)
        self.model.A = pyo.RangeSet(1, a_max)

        self.weekly_policy = weekly_policy
        if self.weekly_policy:
            self.model.Wd = pyo.RangeSet(0, 6)

        self.model.M = M

        # Hydra doesn't support integer keys so convert here if needed
        self.model.initial_inventory = {
            int(k): v
            for k, v in initial_inventory.items()
        }

        self.additional_fifo_constraints = additional_fifo_constraints

        self.model.demand = demand

        self.model.CssF = fixed_order_cost
        self.model.CssP = variable_order_cost
        self.model.CssH = holding_cost
        self.model.CssE = emergency_procurement_cost
        self.model.CssW = wastage_cost

        self.model.cons = pyo.ConstraintList()
Пример #12
0
def create_master_problem(params: Parameter) -> pyo.ConcreteModel:
    """
    This function creates a master problem.
    :param params: Parameter object containing all relevant parameters.
    :return: master problem
    """

    master = pyo.ConcreteModel()

    # Save parameters as a model instance to access parameters in constraint
    # functions.
    master.params = params

    # Hour sets
    master.H = pyo.RangeSet(1, len(params.HOURS) - 1)
    master.H_all = pyo.RangeSet(0, len(params.HOURS) - 1)

    # Variables
    # Unit commitment for generator
    master.u = pyo.Var(master.H_all, within=pyo.Binary)

    # Initialization for u
    master.u[0].fix(0)

    # Electricity purchased with the forward contract
    master.p1 = pyo.Var(master.H_all, within=pyo.NonNegativeReals)

    # Initialization for p1
    master.p1[0].fix(0)

    # Value function for second stage problem
    master.alpha = pyo.Var(master.H_all)

    # Initialization for p1
    master.alpha[0].fix(0)

    def master_obj(model):
        return sum(params.c1 * model.u[h] + params.l1 * model.p1[h] +
                   model.alpha[h] for h in model.H)

    master.OBJ = pyo.Objective(rule=master_obj)

    # Constraints
    # Alpha down (-500) is an arbitrary selected bound.
    def alphacon1(model, hour):
        return model.alpha[hour] >= -500

    master.alphacon1 = pyo.Constraint(master.H, rule=alphacon1)

    master.min_uptime = pyo.Constraint(master.H, rule=__min_uptime)

    master.min_downtime = pyo.Constraint(master.H, rule=__min_downtime)

    return master
    def _prepare_pyomo_function3(self):
        model3 = pyo.AbstractModel()

        model3.m = pyo.Param(
            within=pyo.NonNegativeIntegers)  # количество ограничений
        model3.n = pyo.Param(
            within=pyo.NonNegativeIntegers)  # количество переменных всего
        model3.nx = pyo.Param(
            within=pyo.NonNegativeIntegers)  # количество обычных переменных
        model3.nz = pyo.Param(
            within=pyo.NonNegativeIntegers)  # количество бинарных переменных

        model3.I = pyo.RangeSet(1, model3.m)  # индексы ограничений
        model3.J = pyo.RangeSet(1, model3.n)  # индексы переменных
        model3.Jx = pyo.RangeSet(1, model3.nx)  # индексы обычных переменных
        model3.Jz = pyo.RangeSet(1, model3.nz)  # индексы бинарных переменных
        model3.two = pyo.RangeSet(1, 2)

        model3.Ax = pyo.Param(model3.I,
                              model3.Jx)  # объявляем матрицу ограничений для x
        model3.Az = pyo.Param(model3.I,
                              model3.Jz)  # объявляем матрицу ограничений для z
        model3.rhs = pyo.Param(model3.I, model3.two)  # rhs

        # variables
        model3.x = pyo.Var(model3.Jx, domain=pyo.Reals)
        model3.z = pyo.Var(model3.Jz, domain=pyo.Binary)

        def obj_expression(m):
            return sum(m.x[i] * m.x[i + m.nz] for i in m.Jz)

        model3.OBJ = pyo.Objective(rule=obj_expression)

        def ax_constraint_rule(m, i):
            if m.rhs[i, 2] == -1:
                return sum(m.Ax[i, j] * m.x[j]
                           for j in m.Jx) + sum(m.Az[i, j] * m.z[j]
                                                for j in m.Jz) <= m.rhs[i, 1]
            if m.rhs[i, 2] == 0:
                return sum(m.Ax[i, j] * m.x[j]
                           for j in m.Jx) + sum(m.Az[i, j] * m.z[j]
                                                for j in m.Jz) == m.rhs[i, 1]
            if m.rhs[i, 2] == 1:
                return sum(m.Ax[i, j] * m.x[j]
                           for j in m.Jx) + sum(m.Az[i, j] * m.z[j]
                                                for j in m.Jz) >= m.rhs[i, 1]

        # the next line creates one constraint for each member of the set model.I
        model3.AxbConstraint = pyo.Constraint(model3.I,
                                              rule=ax_constraint_rule)
        self._solve_tool_partial_inverse_model = model3
Пример #14
0
 def _genModelConstraints(self, model, prepared_constraints):
     for iType, iConstraint in prepared_constraints.items():
         if iType=="Box":
             model.lb = pyo.Param(model.N)
             model.ub = pyo.Param(model.N)
             model.BoxConstraint = pyo.Constraint(model.N, rule=BoxConstraint)
         elif iType=="LinearIn":
             model.m1 = pyo.Param(within=pyo.PositiveIntegers)
             model.M1 = pyo.RangeSet(0, model.m1-1)
             model.A = pyo.Param(model.M1, model.N)
             model.b = pyo.Param(model.M1)
             model.LinearInConstraint = pyo.Constraint(model.M1, rule=LinearInConstraint)
         elif iType=="LinearEq":
             model.m2 = pyo.Param(within=pyo.PositiveIntegers)
             model.M2 = pyo.RangeSet(0, model.m2-1)
             model.Aeq = pyo.Param(model.M2, model.N)
             model.beq = pyo.Param(model.M2)
             model.LinearEqConstraint = pyo.Constraint(model.M2, rule=LinearEqConstraint)
         elif iType=="Quadratic":
             for j, jSubConstraint in enumerate(iConstraint):
                 j = str(j)
                 setattr(model, "Sigma"+j, pyo.Param(model.N, model.N))
                 setattr(model, "Mu"+j, pyo.Param(model.N))
                 setattr(model, "q"+j, pyo.Param(within=pyo.Reals))
                 setattr(model, "QuadraticConstraint"+j, pyo.Constraint(rule=lambda m: QuadraticConstraint(m, j)))
         elif iType=="L1":
             for j, jSubConstraint in enumerate(iConstraint):
                 j = str(j)
                 setattr(model, "l"+j, pyo.Param(within=pyo.Reals))
                 setattr(model, "c"+j, pyo.Param(model.N))
                 setattr(model, "L1Constraint"+j, pyo.Constraint(rule=lambda m: L1Constraint(m, j)))
         elif iType=="Pos":
             for j, jSubConstraint in enumerate(iConstraint):
                 j = str(j)
                 setattr(model, "l_pos"+j, pyo.Param(within=pyo.Reals))
                 setattr(model, "c_pos"+j, pyo.Param(model.N))
                 setattr(model, "PosConstraint"+j, pyo.Constraint(rule=lambda m: PosConstraint(m, j)))
         elif iType=="Neg":
             for j, jSubConstraint in enumerate(iConstraint):
                 j = str(j)
                 setattr(model, "l_neg"+j, pyo.Param(within=pyo.Reals))
                 setattr(model, "c_neg"+j, pyo.Param(model.N))
                 setattr(model, "NegConstraint"+j, pyo.Constraint(rule=lambda m: NegConstraint(m, j)))
         elif iType=="NonZeroNum":
             for j, jSubConstraint in enumerate(iConstraint):
                 j = str(j)
                 setattr(model, "b"+j, pyo.Param(within=model.N))
                 setattr(model, "N"+j, pyo.Param(within=pyo.PositiveIntegers))
                 setattr(model, "NonZeroNumConstraint"+j, pyo.Constraint(rule=lambda m: NonZeroNumConstraint(m, j)))
     return model
Пример #15
0
def perturb_point(model, gen_pert, delta):
    model.c = gen_multi.randint(1, model.n)
    print(model.c.value)
    model.p.value = model.n.value - model.c.value
    model.C = pe.RangeSet(1, model.c)
    model.P = pe.RangeSet(model.c + 1, model.n)
    print(model.P.value)
    print(model.C.value)
    print("C value ", model.c.value)

    for i in model.N:
        model.x[i] = model.x[i].value * (1 + gen_pert.uniform(-1, 1) * delta)
        model.x[i] = max(model.lb, min(model.x[i].value, model.ub))
        model.y[i] = model.y[i].value * (1 + gen_pert.uniform(-1, 1) * delta)
        model.y[i] = max(model.lb, min(model.y[i].value, model.ub))
Пример #16
0
def optimization_problem_second_step(
        alpha_variables, number_of_nodes, new_label_values, label_to_train,
        SVM_regularization_parameter, data_to_train,
        correspondence_time_period_line_all_samples, sample_by_line,
        sample_to_train, sample_alpha_variables, number_of_renewable_energy,
        initial_variables_multistart, label_alpha_variables,
        data_alpha_variables):
    model = pe.ConcreteModel('optimization_problem_second_step')
    model.label_to_train = label_to_train
    model.SVM_regularization_parameter = SVM_regularization_parameter
    model.data_to_train = data_to_train
    model.correspondence_time_period_line_all_samples = correspondence_time_period_line_all_samples
    model.sample_by_line = sample_by_line
    model.sample_to_train = sample_to_train
    model.sample_alpha_variables = sample_alpha_variables
    model.number_of_renewable_energy = number_of_renewable_energy
    model.number_of_nodes = number_of_nodes
    model.label_alpha_variables = label_alpha_variables
    model.data_alpha_variables = data_alpha_variables

    number_of_labels = max(new_label_values)
    number_of_time_periods = len(label_to_train)
    number_of_time_periods_first_sample = alpha_variables.shape[1]

    model.alpha_variables = alpha_variables

    model.indexes_nodes = pe.RangeSet(model.number_of_nodes)
    model.indexes_time_periods = pe.RangeSet(number_of_time_periods)
    model.indexes_labels = pe.RangeSet(number_of_labels)
    model.indexes_time_periods_first_sample = pe.RangeSet(
        number_of_time_periods_first_sample)

    initial_variables_multistart.index = model.indexes_nodes

    model.weights_variables = pe.Var(
        model.indexes_nodes,
        within=pe.NonNegativeReals,
        initialize=initial_variables_multistart.iloc[:, 0].to_dict())
    model.epigraph_variables = pe.Var(model.indexes_time_periods,
                                      within=pe.Reals)

    model.constraint_epigraph = pe.Constraint(model.indexes_time_periods,
                                              model.indexes_labels,
                                              rule=constraint_epigraph)
    model.objective_function = pe.Objective(rule=objective_function,
                                            sense=pe.minimize)

    return model
Пример #17
0
def runBackpackAlgorithm():
    # LOCAL FUNCTIONS
    # Objective Function
    def obj_func(model):
        return sum(model.X[t] * model.w[t] for t in model.T)

    # Constraint Generation
    def humanContactConstraint(model, T):
        # Human Contact Limit
        V = 20
        return sum(model.X[t] * model.c[t] for t in model.T) <= V

    schedules = [
    ]  # array of schedules, _ is an invisible variable for iterations
    print("Please be patient while possible schedules are generated...")
    for _ in range(1, 100):
        # generate some integers for weighting
        value1 = randint(0, 10000)
        value2 = randint(0, 10000)
        value3 = randint(0, 10000)
        value4 = randint(0, 10000)

        seed(value1)

        factors = {1: 7, 2: 7, 3: 10, 4: 10}
        weight = {1: value1, 2: value2, 3: value3, 4: value4}

        # Model intialization
        model = pyo.ConcreteModel()

        # Indexes for timeslots t
        # Number of time slots
        t = 4
        model.T = pyo.RangeSet(t)

        # Parameter variable xt
        model.X = pyo.Var(model.T, within=pyo.Binary)

        # Item sizes matrix ct
        model.c = pyo.Param(model.T, initialize=factors, default=0)

        # Item weights matrix
        model.w = pyo.Param(model.T, initialize=weight, default=0)

        model.objective = pyo.Objective(rule=obj_func, sense=pyo.maximize)

        model.const1 = pyo.Constraint(model.T, rule=humanContactConstraint)

        # Solves knapsack using Gurobi
        solver = pyo.SolverFactory('gurobi')
        solver.solve(model, tee=False)

        options = []
        for i in list(model.X.keys()):
            if model.X[i]() != 0:
                options.append(i)

        schedules.append(options)

    return schedules  # These are the feabile schedules used later on
Пример #18
0
def xyb_rule(b, t):
    b.x = pyo.Var()
    b.I = pyo.RangeSet(t)
    b.y = pyo.Var(b.I, initialize=1.0)
    def _b_c_rule(_b):
        return _b.x == 1.0 - sum(_b.y[i] for i in _b.I)
    b.c = pyo.Constraint(rule=_b_c_rule)
Пример #19
0
    def declare_parameters(self):
        # style - set of all beer styles
        self.model.styles = pyo.Set(initialize = self.beer_styles)

        self.multiplier = 8

        # num - range for each style
        self.model.num_range = pyo.RangeSet(1,self.multiplier)

        # B_{i, n}
        # Marginal change in value for style i tap n
        self.model.marginal_profit_set = pyo.Set(dimen=2, initialize = {(style, num) for style in self.model.styles for num in self.model.num_range})
        def marginal_profit_init(model, style, num):
            if style in self.beer_promo_dict:
                if self.beer_promo_dict[style] != 0:
                    self.beer_promo_dict[style] = self.beer_promo_dict[style] - 1
                    self.mandate_list_volume[(style,num)] = self.marginal_values[(style,num)]["Promo"][1]
                    return self.marginal_values[(style,num)]["Promo"][0]
                else:
                    self.mandate_list_volume[(style,num)] = self.marginal_values[(style,num)]["No_Promo"][1]
                    return self.marginal_values[(style,num)]["No_Promo"][0]
            else:
                self.mandate_list_volume[(style,num)] = self.marginal_values[(style,num)]["No_Promo"][1]
                return self.marginal_values[(style,num)]["No_Promo"][0]
        self.model.marginal_profit = pyo.Param(self.model.marginal_profit_set, initialize = marginal_profit_init)
Пример #20
0
    def __init__(self, model, E_price, solar_cf, ASM_price):

        self.model = model
        self.model.IDX = pyo.RangeSet(0, 8759)
        self.model.E_price = E_price
        self.model.ASM_price = ASM_price
        self.model.solar_cf = solar_cf
Пример #21
0
    def generate_cut_gen_problem(self):
        if not hasattr(self, 'equip_exists'):
            pass
        elif abs(self.equip_exists.value) <= 1E-3:
            # Do not solve cut generation problem for inactive units
            return None

        if not hasattr(self, 'apply_NLP'):
            return None

        self.apply_NLP()
        num_vars = count_vars(self)
        if num_vars < 1:
            return None

        b = pe.ConcreteModel(name=self.local_name)
        # self.cg_prob = b
        var_set = b.var_set = pe.RangeSet(num_vars)
        b.lbda = pe.Var(b.var_set,
                        domain=pe.NonNegativeReals,
                        bounds=(0, 1),
                        initialize=0)
        b.lbda_sum = pe.Constraint(expr=sum(b.lbda[vs]
                                            for vs in b.var_set) == 1)

        clone_block(self, b, var_set, b.lbda)

        sum_sq_diff = get_sum_sq_diff(self, b)
        b.obj = pe.Objective(expr=sum_sq_diff, sense=pe.minimize)
        return b
Пример #22
0
 def _genMeanVarianceModel(self, nvar, prepared_objective, prepared_constraints):
     Model = pyo.AbstractModel()
     Model.n = pyo.Param(within=pyo.PositiveIntegers)
     Model.N = pyo.RangeSet(0, Model.n-1)
     Model.x = pyo.Var(Model.N, domain=pyo.Reals)
     if "f" in prepared_objective: Model.f = pyo.Param(Model.N)
     if "lambda1" in prepared_objective:
         Model.lambda1 = pyo.Param(within=pyo.Reals)
         Model.c = pyo.Param(Model.N)
     if "lambda2" in prepared_objective:
         Model.lambda2 = pyo.Param(within=pyo.Reals)
         Model.c_pos = pyo.Param(Model.N)
     if "lambda3" in prepared_objective:
         Model.lambda3 = pyo.Param(within=pyo.Reals)
         Model.c_neg = pyo.Param(Model.N)
     if ("X" in prepared_objective) or ("Sigma" in prepared_objective): Model.Sigma = pyo.Param(Model.N, Model.N)
     if "Mu" in prepared_objective: Model.Mu = pyo.Param(Model.N)
     if prepared_objective["type"]=="Linear":
         Model.OBJ = pyo.Objective(rule=LinearObjective, sense=pyo.minimize)
     elif prepared_objective["type"]=="L1_Linear":
         Model.OBJ = pyo.Objective(rule=L1_LinearObjective, sense=pyo.minimize)
     elif prepared_objective["type"]=="Quadratic":
         Model.OBJ = pyo.Objective(rule=QuadraticObjective, sense=pyo.minimize)
     elif prepared_objective["type"]=="L1_Quadratic":
         Model.OBJ = pyo.Objective(rule=L1_QuadraticObjective, sense=pyo.minimize)
     return self._genModelConstraints(Model, prepared_constraints)
Пример #23
0
def access_obj_values():
    import pyomo.environ as pyo
    from pyomo.opt import SolverFactory
    # Create a solver
    opt = SolverFactory('glpk')
    # A simple model with binary variables and
    # an empty constraint list.
    model = pyo.ConcreteModel()
    model.n = pyo.Param(default=4)
    model.x = pyo.Var(pyo.RangeSet(model.n), within=pyo.Binary)
    # Note: model.x creates an interable using rangeset and returns
    # 4 values of x indexed using the vals created in the rangeset funct.
    [print(model.x[i]) for i in range(1,5)]
    def o_rule(model):
        return summation(model.x)
    model.o = pyo.Objective(rule=o_rule)
    model.c = pyo.ConstraintList()
    results = opt.solve(model)

    # Print All Variables
    for v in model.component_objects(pyo.Var, active=True):
        print("Variable",v)
        # Print All Values Assigned to variables
        for index in v:
            print ("   ",index, pyo.value(v[index]))

    # Print All Parameters
    for parmobject in model.component_objects(pyo.Param, active=True):
        nametoprint = str(str(parmobject.name))
        print ("Parameter ", nametoprint)  # doctest: +SKIP
        for index in parmobject:
            vtoprint = pyo.value(parmobject[index])
            print ("   ",index, vtoprint)  # doctest: +SKIP
Пример #24
0
def create_model(m):
    """Create unit models"""

    m.fs.ww_zones = pyo.RangeSet(10)

    m.fs.drum = Drum(
        default={
            "property_package": m.fs.prop_water,
            "has_holdup": False,
            "has_heat_transfer": True,
            "has_pressure_change": True,
        })
    m.fs.downcomer = Downcomer(
        default={
            "property_package": m.fs.prop_water,
            "has_holdup": False,
            "has_heat_transfer": True,
        })
    m.fs.Waterwalls = WaterwallSection(
        m.fs.ww_zones,
        default={
            "dynamic": False,
            "has_holdup": False,
            "property_package": m.fs.prop_water,
            "has_heat_transfer": True,
            "has_pressure_change": True,
        },
    )

    m.fs.stream_drum_out = Arc(source=m.fs.drum.liquid_outlet,
                               destination=m.fs.downcomer.inlet)
    m.fs.stream_dcmr_out = Arc(source=m.fs.downcomer.outlet,
                               destination=m.fs.Waterwalls[1].inlet)

    def arc_rule(b, i):
        return {
            "source": m.fs.Waterwalls[i].outlet,
            "destination": m.fs.Waterwalls[i + 1].inlet
        }

    m.arc = Arc(pyo.RangeSet(9), rule=arc_rule)

    m.fs.stream_ww14 = Arc(source=m.fs.Waterwalls[10].outlet,
                           destination=m.fs.drum.water_steam_inlet)
    # pyomo arcs expand constraints for inlet = outlet ports
    pyo.TransformationFactory("network.expand_arcs").apply_to(m)
Пример #25
0
    def _build_model_objects(self, model):
        model.Epitopes = aml.RangeSet(0,
                                      len(self._params.epitope_immunogen) - 1)
        model.Aminoacids = aml.RangeSet(0, len(self._params.pcm_matrix) - 1)
        model.EpitopePositions = aml.RangeSet(0,
                                              self._params.vaccine_length - 1)
        model.SpacerPositions = aml.RangeSet(0,
                                             self._params.vaccine_length - 2)
        model.AminoacidPositions = aml.RangeSet(
            0, self._params.max_spacer_length - 1)
        model.PcmIdx = aml.RangeSet(-4, 1)
        model.SequenceLength = aml.Param(initialize=(
            self._params.vaccine_length * self._params.epitope_length +
            (self._params.vaccine_length - 1) *
            self._params.max_spacer_length - 1))
        model.SequencePositions = aml.RangeSet(0, model.SequenceLength)
        model.PositionInsideEpitope = aml.RangeSet(
            0, self._params.epitope_length - 1)

        model.MinSpacerLength = aml.Param(
            initialize=self._params.min_spacer_length)
        model.MaxSpacerLength = aml.Param(
            initialize=self._params.max_spacer_length)
        model.VaccineLength = aml.Param(initialize=self._params.vaccine_length)
        model.EpitopeLength = aml.Param(initialize=self._params.epitope_length)
        model.PssmMatrix = aml.Param(
            model.Aminoacids * model.PcmIdx,
            initialize=lambda model, i, j: self._params.pcm_matrix[i][j])
        model.EpitopeImmunogen = aml.Param(
            model.Epitopes,
            initialize=lambda model, i: self._params.epitope_immunogen[i])
        model.EpitopeSequences = aml.Param(
            model.Epitopes * model.PositionInsideEpitope,
            initialize=lambda model, i, j: self._params.all_epitopes[i][j])

        # x(ij) = 1 iff epitope i is in position j
        model.x = aml.Var(model.Epitopes * model.EpitopePositions,
                          domain=aml.Binary,
                          initialize=0)

        # y(ijk) = 1 iff aminoacid k is in position j of spacer i
        model.y = aml.Var(model.SpacerPositions * model.AminoacidPositions *
                          model.Aminoacids,
                          domain=aml.Binary,
                          initialize=0)

        # a(ij) = 1 iff aminoacid j is in position i of the *whole* sequence (epitopes + spacers)
        model.a = aml.Var(model.SequencePositions * model.Aminoacids,
                          domain=aml.Binary,
                          initialize=0)

        # i(i) is the computed cleavage at position i
        model.i = aml.Var(model.SequencePositions,
                          domain=aml.Reals,
                          initialize=0)
Пример #26
0
def output_datarate_optimization_PYOMO(q,
                                       w,
                                       N,
                                       M,
                                       P,
                                       T_s,
                                       U_max=1000,
                                       Q_max=1,
                                       tol=1e-7):
    if N == 0:
        return []
    m = pyo.ConcreteModel()
    m.N = pyo.RangeSet(0, N - 1)
    m.M = pyo.RangeSet(0, M - 1)
    m.q = pyo.Param(m.N, initialize={i: q[i] for i in m.N}, within=pyo.Reals)
    m.w = pyo.Param(m.N,
                    initialize={i: w[i]
                                for i in m.N},
                    within=pyo.NonNegativeReals)
    m.P = pyo.Param(m.N,
                    m.M,
                    initialize={(i, j): P[i][j]
                                for j in m.M for i in m.N},
                    within=pyo.NonNegativeReals)
    m.T_s = pyo.Param(initialize=T_s, within=pyo.NonNegativeReals)
    m.U_max = pyo.Param(initialize=U_max, within=pyo.NonNegativeReals)
    m.Q_max = pyo.Param(initialize=Q_max, within=pyo.NonNegativeReals)

    m.u_k = pyo.Var(m.N, m.M, domain=pyo.NonNegativeReals)

    m.visible_basestation_constraint = pyo.Constraint(
        m.N, m.M, rule=visible_basestation_constraint_rule)
    m.max_U_constraint = pyo.Constraint(m.M, rule=max_U_constraint_rule)
    m.queue_constraint_lower = pyo.Constraint(m.N,
                                              rule=queue_constraint_lower_rule)
    m.queue_constraint_upper = pyo.Constraint(m.N,
                                              rule=queue_constraint_upper_rule)
    m.obj = pyo.Objective(rule=obj_rule)
    opt = pyo.SolverFactory("ipopt", executable="ipopt-win64\\ipopt.exe")
    ret = opt.solve(m)
    u_final = np.zeros((N, M))
    for i in range(N):
        for j in range(M):
            u_final[i, j] = pyo.value(m.u_k[i, j])
    return u_final
Пример #27
0
def Create_Model_Stg1():
    """Create Pyomo model.

    Model consists of
    1. Functions to properly initialize number of weaks and respective bound from global data loader class
    2. Variables to optimize
    3. Objective function
    4. Constraints

    """

    def Weeks_Init(Model, PPG_index):
        return Globals.EDLP_Events[PPG_index]

    def Weeks_bound(Model, PPG_index):
        return (Globals.Min_EDLP_Events[PPG_index], Globals.Max_EDLP_Events[PPG_index])

    def TPR_Bound_Init(Model, P):

        LB = min(Globals.TPR_Perc_Val[P])
        UB = max(Globals.TPR_Perc_Val[P])

        return (LB, UB)

    def TPR_Initial(Model, P):

        UB = max(Globals.TPR_Perc_Val[P])

        return UB

    Model = pyo.ConcreteModel(name="Spend_Optim")
    Model.PPGs = pyo.Param(initialize=Globals.Tot_Prod, domain=pyo.PositiveIntegers)
    Model.PPG_index = pyo.RangeSet(0, Model.PPGs - 1)
    Model.EDLP = pyo.Var(
        Model.PPG_index,
        initialize=Globals.EDLP_UB,
        domain=pyo.NonNegativeReals,
        bounds=(Globals.EDLP_LB, Globals.EDLP_UB),
    )
    Model.TPR = pyo.Var(
        Model.PPG_index,
        initialize=TPR_Initial,
        domain=pyo.NonNegativeReals,
        bounds=TPR_Bound_Init,
    )
    Model.Weeks = pyo.Var(
        Model.PPG_index,
        initialize=Weeks_Init,
        domain=pyo.PositiveIntegers,
        bounds=Weeks_bound,
    )
    Model.Obj = pyo.Objective(rule=Dollar_Sales_Stg1_Fn, sense=pyo.maximize)
    # Model.Tot_Spent_Bnd = pyo.Constraint(Model.PPG_index, rule=Total_Trade_Spent_Bnd_Stg1_Fn)
    Model.EDLP_Bnd = pyo.Constraint(Model.PPG_index, rule=EDLP_Trade_Spent_Bnd_Stg1_Fn)
    Model.TPR_Bnd = pyo.Constraint(Model.PPG_index, rule=TPR_Trade_Spent_Bnd_Stg1_Fn)
    Model.Overall = pyo.Constraint(rule=Overall_Total_Trade_Spent_Stg1_Fn)
    return Model
    def _prepare_pyomo_function1(self):
        model1 = pyo.AbstractModel()

        model1.m = pyo.Param(
            within=pyo.NonNegativeIntegers)  # количество ограничений
        model1.n = pyo.Param(
            within=pyo.NonNegativeIntegers)  # количество переменных

        model1.I = pyo.RangeSet(1, model1.m)  # индексы ограничений
        model1.J = pyo.RangeSet(1, model1.n)  # индексы переменных

        model1.a = pyo.Param(model1.I,
                             model1.J)  # объявляем матрицу ограничений
        model1.b = pyo.Param(model1.I)  # правые части
        model1.c = pyo.Param(model1.J)  # коэффициенты цф
        model1.lb = pyo.Param(model1.J)  # нижние границы
        model1.sense = pyo.Param(model1.I)  # знаки в ограничениях

        # the next line declares a variable indexed by the set J
        model1.x = pyo.Var(model1.J)

        def obj_expression(m):
            return pyo.summation(m.c, m.x)

        model1.OBJ = pyo.Objective(rule=obj_expression)

        def ax_constraint_rule(m, i):
            if m.sense[i] == -1:
                return sum(m.a[i, j] * m.x[j] for j in m.J) <= m.b[i]
            if m.sense[i] == 0:
                return sum(m.a[i, j] * m.x[j] for j in m.J) == m.b[i]
            if m.sense[i] == 1:
                return sum(m.a[i, j] * m.x[j] for j in m.J) >= m.b[i]

        # the next line creates one constraint for each member of the set model.I
        model1.AxbConstraint = pyo.Constraint(model1.I,
                                              rule=ax_constraint_rule)

        def bounds_rule(m, j):
            return (m.lb[j], m.x[j], None)

        model1.boundx = pyo.Constraint(model1.J, rule=bounds_rule)
        self._inverse_cost_vector_model = model1
Пример #29
0
    def __init__(self):

        pe.ConcreteModel.__init__(self)

        #
        # Metadata [Component Objects]
        
        self.__chem = dict() # Name to chemical mapping
        
        #
        # Model sets 
        self.comp = pe.Set()            # Stream components 
        self.prop = pe.RangeSet(0,10)   # Coefficient set  

        
        #
        # Model parameters
        self.MW = pe.Param(self.comp, default=0)       # Molecular weight
        self.tc = pe.Param(self.comp, default=298)     # Critric temperature
        self.pc = pe.Param(self.comp, default=101325)  # Critic pressure

        self.mu_coef = pe.Param(self.comp, self.prop,
                                mutable = True, default = 0)  # Viscosity coefficients 

        self.rho_coef = pe.Param(self.comp, self.prop,
                                 mutable = True, default =0)  # Density coefficients
        
        #
        # Model variables
        
        # Basic properties
        self.mass_flow = pe.Var(domain = pe.PositiveReals)              # Mass flow [kg/s]
        self.molar_flow = pe.Var(domain = pe.PositiveReals)             # Mole flow [mol/s]
        self.vol_flow = pe.Var(domain = pe.PositiveReals)               # Volume flow [m3/s]
        self.T = pe.Var(domain = pe.PositiveReals, initialize=298)      # Temperature [K]
        self.P = pe.Var(domain = pe.PositiveReals, initialize=101325)   # Pressure [Pa]

        # TODO : Implement new types of properties 
        # Component properties
        self.xw = pe.Var(self.comp, bounds=(0,1))  # Mass fraction
        self.xm = pe.Var(self.comp, bounds=(0,1))  # Molar fraction
        self.vf = pe.Var(self.comp, bounds=(0,1))  # Volume fraction 
        self.rho = pe.Var(self.comp, domain = pe.PositiveReals)   # Component density [kg/m3]
        self.dymu = pe.Var(self.comp, domain = pe.PositiveReals)  # Component absolut viscosity [mPa.s] 
        self.kimu = pe.Var(self.comp, domain = pe.PositiveReals)  # Component kynetic viscosiy  [cSt]
        
        # Mixture properties
        self.Rho = pe.Var(domain = pe.PositiveReals)  # Mixture density [kg/m3]
        self.Dmu = pe.Var(domain = pe.PositiveReals)  # Mixture dynamic viscosity
        self.Kmu = pe.Var(domain = pe.PositiveReals)  # Mixture kinematic viscosity
        #
        # Balance constraints flags
        self.__massbal_flag = False   # Boolean : Activated mass balance
        self.__molarbal_flag = False  # Boolean : Activated molar balance
        self.__volbal_flag = False    # Boolean : Activated 
Пример #30
0
    def insert_constraint(self, params, model, solver):
        cs = {}  # we create components here, then insert them with the prefixed name

        cs['Options'] = aml.RangeSet(0, len(self._epitope_coverage[0]) - 1)

        # for every option, indicates which epitopes cover it
        # FIXME terrible for caching as we iterate over columns
        cs['Coverage'] = aml.Param(cs['Options'], initialize=lambda _, o: set(
            i for i, epi_cov in enumerate(self._epitope_coverage) if epi_cov[o]
        ))

        if self._min_coverage is not None:
            cs['IsOptionCovered'] = aml.Var(cs['Options'], domain=aml.Binary, initialize=0)
            cs['AssignIsOptionCovered'] = aml.Constraint(
                cs['Options'], rule=lambda model, option: sum(
                    model.x[e, p]
                    for e in cs['Coverage'][option]
                    for p in model.EpitopePositions
                ) >= cs['IsOptionCovered'][option]
            )

            cs['MinCoverage'] = aml.Param(initialize=(
                int(self._min_coverage) if self._min_coverage > 1
                else math.ceil(self._min_coverage * len(self._epitope_coverage[0]))
            ), mutable=True)

            cs['MinCoverageConstraint'] = aml.Constraint(rule=lambda model: sum(
                cs['IsOptionCovered'][o] for o in cs['Options']
            ) >= cs['MinCoverage'])

        if self._min_conservation is not None:
            cs['MinConservation'] = aml.Param(initialize=(
                int(self._min_conservation) if self._min_conservation > 1
                else math.ceil(self._min_conservation * len(self._epitope_coverage[0]))
            ), mutable=True)

            cs['MinConservationConstraint'] = aml.Constraint(rule=lambda model: sum(
                model.x[e, p]
                for o in cs['Options']
                for e in cs['Coverage'][o]
                for p in model.EpitopePositions
            ) >= cs['MinConservation'] * model.VaccineLength)

        for k, v in cs.items():
            name = '%s_%s' % (self._name, k)
            setattr(model, name, v)
            if isinstance(v, aml.Constraint):
                self._constraints.append(name)
            elif isinstance(v, aml.Var):
                self._variables.append(name)

        self._cs = cs
        super().insert_constraint(params, model, solver)