Example #1
0
 def obj_rule(_model):
     return (
         pyo.summation(_model.f, _model.y)  # cost of opening facilities
         + pyo.summation(
             _model.t,
             _model.x)  # cost of moving units from facilities to clients
     )
Example #2
0
    def model(self):
        m = pyo.ConcreteModel()
        m.fs = fs = pyo.Block()

        fs.input = pyo.Var(['a', 'b'], within=pyo.UnitInterval, initialize=0.5)
        fs.output = pyo.Var(['c', 'd'],
                            within=pyo.UnitInterval,
                            initialize=0.5)

        fs.slack = pyo.Var(['ab_slack', 'cd_slack'],
                           bounds=(0, 0),
                           initialize=0.0)
        fs.slack_penalty = pyo.Param(default=1000.,
                                     mutable=True,
                                     within=pyo.PositiveReals)

        fs.ab_constr = pyo.Constraint(
            expr=(fs.output['c'] + fs.slack['ab_slack'] == 2 * fs.input['a']))
        fs.cd_constr = pyo.Constraint(
            expr=(fs.output['d'] + fs.slack['cd_slack'] == 3 * fs.input['b']))

        fs.performance = pyo.Expression(expr=pyo.summation(fs.output))

        m.objective = pyo.Objective(
            expr=m.fs.performance -
            m.fs.slack_penalty * pyo.summation(m.fs.slack),
            sense=pyo.maximize)
        return m
Example #3
0
    def _build_model(self):
        Model._build_model(self)
        # Constraint: sum(x forage) [<= >=] 20%
        self._diet.p_forage = pyo.Param(self._diet.s_var_set,
                                        initialize=self.data.d_forage)
        self._diet.p_rhs_forage_ge = pyo.Param(within=pyo.Any, initialize=0.2)
        self._diet.p_rhs_forage_le = pyo.Param(within=pyo.Any, initialize=0.2)
        self._diet.c_forage_ge = pyo.Constraint(expr=pyo.summation(
            self._diet.p_forage, self._diet.v_x) >= self._diet.p_rhs_forage_ge)
        self._diet.c_forage_le = pyo.Constraint(expr=pyo.summation(
            self._diet.p_forage, self._diet.v_x) <= self._diet.p_rhs_forage_le)

        if self.parameters.e_forage_sense == "G":
            self._diet.c_forage_ge.activate()
            self._diet.c_forage_le.deactivate()
        elif self.parameters.e_forage_sense == "L":
            self._diet.c_forage_ge.deactivate()
            self._diet.c_forage_le.activate()
        else:
            self._diet.c_forage_ge.activate()
            self._diet.c_forage_le.deactivate()

        # Constraint: sum(x lca) <= LCA_rhs
        self._diet.p_lca = pyo.Param(self._diet.s_var_set,
                                     within=pyo.Any,
                                     mutable=True)
        self._diet.p_rhs_lca = pyo.Param(within=pyo.Any, mutable=True)
        self._diet.c_lca = pyo.Constraint(expr=pyo.summation(
            self._diet.p_lca, self._diet.v_x) <= self._diet.p_rhs_lca)
Example #4
0
        def rule(model):
            scaling = 0.2
            affinity = np.outer(c.AFFINITY_COGNITIVE, self.task_cognitive_load)

            # TODO(cathywu) replace this code when "simple slicing" is clarified
            zeros1 = np.zeros((1, self.num_tasks))
            zeros2 = np.zeros((2, self.num_tasks))
            zeros3 = np.zeros((3, self.num_tasks))

            total = summation(affinity, model.A)
            total += summation(affinity, model.A2)
            total += summation(affinity, model.A3)
            total += summation(affinity, model.A4)

            total += summation(np.vstack((affinity[1:, :], zeros1)), model.A2)
            total += summation(np.vstack((affinity[1:, :], zeros1)), model.A3)
            total += summation(np.vstack((affinity[1:, :], zeros1)), model.A4)

            total += summation(np.vstack((affinity[2:, :], zeros2)), model.A3)
            total += summation(np.vstack((affinity[2:, :], zeros2)), model.A4)

            total += summation(np.vstack((affinity[3:, :], zeros3)), model.A4)
            total *= scaling

            return model.Affinity_cognitive_total == total
Example #5
0
def demand_rule(model,r,f,b,t):
    vp=pe.summation(model.Vposition, index = [(p, r, f, b, t) for p in model.nonfix_pilots])
    tp=pe.summation(model.Tposition, index = [(p, r, f, b, t) for p in model.trainer_pilots])
    traineep= pe.summation(model.Trainee_po, index = [(p, r, f, b, t) for p in model.fleet_pilots])
    vfixp= pe.summation(model.Vfix_position, index = [(p, r, f, b, t) for p in model.fix_pilots])
    curr_fixed = fixed_df[(fixed_df.Rank==r)&(fixed_df.Cur_Fleet==f)&(fixed_df.Current_Base==b)]['Crew_ID'].values
    pilot = len(curr_fixed)
    nonfix_pilot = pe.summation(model.Y, index = [(p, r, f, b, t) for p in model.nonfix_pilots])
    rhs = pilot + nonfix_pilot - vp - tp - vfixp - traineep + model.shortage[r,f,b,t] - model.surplus[r,f,b,t]
    demand = get_demand(r,f,b,t)
    return rhs == demand 
Example #6
0
    def Objective_fn(m):
        # Link demand / value not yet implemented

        fn = summation(m.nodeValueDB, m.nodeDeliveryDB) \
                   - 10 * summation(m.floodStorage) \
                   - 5 * summation(m.nodeSpill) \
                   # - 1 * summation(m.emptyStorage)

        # - 1000 * summation(m.virtualPrecipGain) \
        fn_debug_gain = -1000 * summation(m.debugGain) if debug_gain else 0
        fn_debug_loss = -1000 * summation(m.debugLoss) if debug_loss else 0

        return fn + fn_debug_gain + fn_debug_loss
Example #7
0
def QuadraticObjective(model):
    Expr = pyo.summation(model.Mu, model.x)
    for i in model.N:
        Expr += model.Sigma[i, i] * model.x[i]**2
        for j in range(i+1, len(model.N)):
            Expr += 2 * model.Sigma[i, j] * model.x[i] * model.x[j]
    return Expr
Example #8
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))
Example #9
0
def create_and_solve_simple_model_with_battery(a, d, c_u, q_u, P_max):
    model = pyo.ConcreteModel(name="with battery")
    model.productors_index = range(len(a))
    model.q = pyo.Var(model.productors_index, domain=pyo.NonNegativeReals)
    model.u = pyo.Var(domain=pyo.NonNegativeReals)

    obj_func = lambda model : (pyo.summation(a, model.q) + c_u*model.u)

    def equality(model, d):
        return pyo.summation(model.q) + model.u - d == 0

    def prod_constraint(model, i):
        return model.q[i] <= P_max[i]

    def battery_constraint(model):
        return model.u <= q_u

    model.balance_constraint = pyo.Constraint(rule=lambda model : equality(model, d))
    model.production_constraint = pyo.Constraint(model.productors_index, rule=prod_constraint)
    model.battery = pyo.Constraint(rule=battery_constraint)
    model.obj = pyo.Objective(rule=obj_func)
    # Export and import floating point data
    model.dual = pyo.Suffix(direction=pyo.Suffix.IMPORT_EXPORT)

    solver = pyo.SolverFactory('gurobi')
    solver.solve(model, tee=True)
    results = [pyo.value(model.q[i]) for i in model.productors_index]
    return model
Example #10
0
def distribute_clusters(n, n_clusters, focus_weights=None, solver_name=None):
    if solver_name is None:
        solver_name = snakemake.config['solving']['solver']['name']

    L = (n.loads_t.p_set.mean().groupby(n.loads.bus).sum().groupby(
        [n.buses.country, n.buses.sub_network]).sum().pipe(normed))

    N = n.buses.groupby(['country', 'sub_network']).size()

    assert n_clusters >= len(N) and n_clusters <= N.sum(), \
        "Number of clusters must be {} <= n_clusters <= {} for this selection of countries.".format(len(N), N.sum())

    if focus_weights is not None:

        total_focus = sum(list(focus_weights.values()))

        assert total_focus <= 1.0, "The sum of focus weights must be less than or equal to 1."

        for country, weight in focus_weights.items():
            L[country] = weight / len(L[country])

        remainder = [
            c not in focus_weights.keys()
            for c in L.index.get_level_values('country')
        ]
        L[remainder] = L.loc[remainder].pipe(normed) * (1 - total_focus)

        logger.warning(
            'Using custom focus weights for determining number of clusters.')

    assert np.isclose(
        L.sum(), 1.0, rtol=1e-3
    ), "Country weights L must sum up to 1.0 when distributing clusters. Is {}.".format(
        L.sum())

    m = po.ConcreteModel()

    def n_bounds(model, *n_id):
        return (1, N[n_id])

    m.n = po.Var(list(L.index), bounds=n_bounds, domain=po.Integers)
    m.tot = po.Constraint(expr=(po.summation(m.n) == n_clusters))
    m.objective = po.Objective(expr=sum(
        (m.n[i] - L.loc[i] * n_clusters)**2 for i in L.index),
                               sense=po.minimize)

    opt = po.SolverFactory(solver_name)
    if not opt.has_capability('quadratic_objective'):
        logger.warning(
            f'The configured solver `{solver_name}` does not support quadratic objectives. Falling back to `ipopt`.'
        )
        opt = po.SolverFactory('ipopt')

    results = opt.solve(m)
    assert results['Solver'][0][
        'Status'].key == 'ok', "Solver returned non-optimally: {}".format(
            results)

    return pd.Series(m.n.get_values(), index=L.index).astype(int)
Example #11
0
 def computeSecondStageCost(model):
   """
     Method to compute second stage cost of stochastic programming, i.e. maximum NPVs
     @ In, model, instance, pyomo abstract model instance
     @ Out, expr, pyomo.expression, second stage cost
   """
   expr = pyomo.summation(model.net_present_values, model.x)
   return expr
Example #12
0
 def computeFirstStageCost(model):
   """"
     Method to compute first stage cost of stochastic programming
     @ In, model, instance, pyomo abstract model instance
     @ Out, expr, float, first stage cost
   """
   expr = -model.epsilon * model.gamma + pyomo.summation(model.prob, model.nu)
   return expr
Example #13
0
 def rule(model):
     den = self.num_tasks * slots
     num = 20
     weights = np.ones((7, self.num_tasks))
     for j in range(self.num_tasks):
         weights[:, j] = self.task_spread[j]
     total = summation(weights, model.S) / den * num
     return model.S_total == total
Example #14
0
   def expectProfit(model):
       """
   Method to compute the expect profit of stochastic programming
   @ In, model, instance, pyomo abstract model instance
   @ Out, expr, pyomo.expression, constraint to compute the expect profit
 """
       return model.expectProfit - pyomo.summation(
           model.net_present_values, model.x) == 0
Example #15
0
def L1_LinearObjective(model):
    Expr = pyo.summation(model.f, model.x)
    if hasattr(model, "lambda1"):
        Expr += model.lambda1 * sum(abs(model.x[i]-model.c[i]) for i in model.N)
    if hasattr(model, "lambda2"):
        Expr += model.lambda2 * sum((abs(model.x[i]-model.c_pos[i])+(model.x[i]-model.c_pos[i]))/2 for i in model.N)
    if hasattr(model, "lambda3"):
        Expr += model.lambda3 * sum((abs(model.x[i]-model.c_pos[i])-(model.x[i]-model.c_neg[i]))/2 for i in model.N)
    return Expr
Example #16
0
 def computeSecondStageCost(model):
     """
   Method to compute second stage cost of stochastic programming
   @ In, model, instance, pyomo abstract model instance
   @ Out, expr, pyomo.expression, second stage cost
 """
     expr = pyomo.summation(model.net_present_values, model.x) * (1.-model._lambda) - \
            model._lambda/(1.0-model.alpha)*model.nu
     return expr
Example #17
0
def QuadraticConstraint(model, suffix):
    Sigma = getattr(model, "Sigma"+suffix)
    Mu = getattr(model, "Mu"+suffix)
    q = getattr(model, "q"+suffix)
    Expr = pyo.summation(Mu, model.x)
    for i in model.N:
        for j in model.N:
            Expr += model.x[i]*Sigma[i, j]*model.x[j]
    return (Expr<=q)
Example #18
0
    def Objective_fn(m):
        # Link demand / value not yet implemented

        fn = summation(m.nodeValueDB, m.nodeDeliveryDB) \
             + summation(m.nodeStorageValueDB, m.nodeStorageDB) \
             + summation(m.nodeBaseHydropowerValueDB, m.nodeHydropowerDB) \
             + summation(m.nodeExcessValue, m.nodeExcessHydropower) \
             + summation(m.nodeViolationCost, m.nodeFlowRequirementDelivery) \
             - 10 * summation(m.floodStorage) \
             - 5 * summation(m.nodeSpill) \
            # - 1 * summation(m.emptyStorage)
        # - 1000 * summation(m.virtualPrecipGain) \
        fn_debug_gain = - 1000 * summation(m.debugGain) if debug_gain else 0
        fn_debug_loss = - 1000 * summation(m.debugLoss) if debug_loss else 0

        return fn + fn_debug_gain + fn_debug_loss
Example #19
0
def L1_QuadraticObjective(model):
    Expr = pyo.summation(model.Mu, model.x)
    for i in model.N:
        for j in model.N:
            Expr += model.x[i]*model.Sigma[i, j]*model.x[j]
    if hasattr(model, "lambda1"):
        Expr += model.lambda1 * sum(abs(model.x[i]-model.c[i]) for i in model.N)
    if hasattr(model, "lambda2"):
        Expr += model.lambda2 * sum((abs(model.x[i]-model.c_pos[i])+(model.x[i]-model.c_pos[i]))/2 for i in model.N)
    if hasattr(model, "lambda3"):
        Expr += model.lambda3 * sum((abs(model.x[i]-model.c_pos[i])-(model.x[i]-model.c_neg[i]))/2 for i in model.N)
    return Expr
Example #20
0
def distribute_clusters_optim(n, n_clusters, solver_name=None):
    if solver_name is None:
        solver_name = snakemake.config['solver']['solver']['name']

    L = (n.loads_t.p_set.mean().groupby(n.loads.bus).sum().groupby(
        [n.buses.country, n.buses.sub_network]).sum().pipe(normed))

    m = po.ConcreteModel()
    m.n = po.Var(list(L.index), bounds=(1, None), domain=po.Integers)
    m.tot = po.Constraint(expr=(po.summation(m.n) == n_clusters))
    m.objective = po.Objective(expr=po.sum(
        (m.n[i] - L.loc[i] * n_clusters)**2 for i in L.index),
                               sense=po.minimize)

    opt = po.SolverFactory(solver_name)
    if isinstance(opt, pypsa.opf.PersistentSolver):
        opt.set_instance(m)
    results = opt.solve(m)
    assert results['Solver'][0][
        'Status'].key == 'ok', "Solver returned non-optimally: {}".format(
            results)

    return pd.Series(m.n.get_values(), index=L.index).astype(int)
Example #21
0
def distribute_clusters(n, n_clusters, solver_name=None):
    if solver_name is None:
        solver_name = snakemake.config['solver']['solver']['name']

    L = (n.loads_t.p_set.mean().groupby(n.loads.bus).sum().groupby(
        [n.buses.country, n.buses.sub_network]).sum().pipe(normed))

    N = n.buses.groupby(['country', 'sub_network']).size()

    assert n_clusters >= len(N) and n_clusters <= N.sum(), \
        "Number of clusters must be {} <= n_clusters <= {} for this selection of countries.".format(len(N), N.sum())

    m = po.ConcreteModel()

    def n_bounds(model, *n_id):
        return (1, N[n_id])

    m.n = po.Var(list(L.index), bounds=n_bounds, domain=po.Integers)
    m.tot = po.Constraint(expr=(po.summation(m.n) == n_clusters))
    m.objective = po.Objective(expr=po.sum(
        (m.n[i] - L.loc[i] * n_clusters)**2 for i in L.index),
                               sense=po.minimize)

    opt = po.SolverFactory(solver_name)
    if not opt.has_capability('quadratic_objective'):
        logger.warn(
            f'The configured solver `{solver_name}` does not support quadratic objectives. Falling back to `ipopt`.'
        )
        opt = po.SolverFactory('ipopt')

    results = opt.solve(m)
    assert results['Solver'][0][
        'Status'].key == 'ok', "Solver returned non-optimally: {}".format(
            results)

    return pd.Series(m.n.get_values(), index=L.index).astype(int)
Example #22
0
 def one_out_rule(model, n):
     return ( pe.summation(model.y, index=model.g.out_edges(n)) == 1)
	return model.Yall[p,r,f,b,t] == model.Y[p,r,f,b,t]
model.yall_y_binding = pe.Constraint(model.nonfix_var_set*model.time, rule = yall_y_binding_rule)

###Yall setting rule(for fix-pilot part)
def yall_setting_rule(model, p, r, f, b, t):
	df_new = fixed_df.set_index(['Crew_ID','Rank','Cur_Fleet','Current_Base'])
	if (p, r, f, b) in df_new.index:
		return model.Yall[p,r,f,b,t] == 1
	else:
		return model.Yall[p,r,f,b,t] == 0
model.yall_setting = pe.Constraint(model.fix_var_set*model.time, rule = yall_setting_rule)


###OBJ###
###Normal Operation:
model.total_normal_cost = pe.summation(model.normal_cost, model.Y)
###Transitions:
# changing (p, r, f, b, 25)'s to (p, r, f, b, )
model.total_fleet_trans_cost = pe.summation(model.fleet_transition_cost, model.Y, index = [(p, r, f, b, len(demand_df)-1) for(p, r, f, b) in model.to_pos if p in model.fleet_pilots ])
model.total_base_trans_cost = pe.summation(model.base_transition_cost, model.Y, index = [(p, r, f, b, len(demand_df)-1) for(p, r, f, b) in model.to_pos if p in model.base_pilots ])
model.total_trans_cost = model.total_fleet_trans_cost + model.total_base_trans_cost
###Shortages:
model.total_shortage_cost = pe.summation(model.short_cost, model.shortage)
###Vacation Penalty:
model.total_vacation_penalty = pe.summation(model.vacation_penalty, model.VP)
model.total_seniority_reward = pe.summation(model.seniority_reward, model.VS)

model.OBJ = pe.Objective(expr = model.total_shortage_cost + model.total_trans_cost + model.total_normal_cost + model.total_vacation_penalty - model.total_seniority_reward, sense=pe.minimize)
solver = pyomo.opt.SolverFactory('cplex')

	def utilityCalc(model):
		return (model.UTILITY == kwargs['tstep'] * kwargs['scale1'] * pe.summation(model.CEMUTOTPER) + kwargs['scale2'])
Example #25
0
 def y_flow(model, depot):
     return pe.summation(model.y, index=[arc for arc in model.arc_set if arc[1] == depot]) == pe.summation(
         model.y, index=[arc for arc in model.arc_set if arc[0] == depot]
     )
Example #26
0
 def forth_const(model, j):
     return pe.summation(model.y, index=[arc for arc in model.arc_set if arc[0] == j]) == 1
Example #27
0
 def six_const(model, depot):
     return pe.summation(model.y, index=[arc for arc in model.arc_set if arc[0] == depot]) <= model.K
Example #28
0
def o_rule(model):
    return pyo.summation(model.x)
Example #29
0
File: main.py Project: egbuck/ormm
 def _obj_expression(model):
     """Objective Expression: Minimizing Shipping Costs"""
     return pyo.summation(model.ShippingCosts, model.Flows)
Example #30
0
File: milp.py Project: egbuck/ormm
 def _obj_expression(model):
     """Objective Expression: Maximizing Value"""
     return pyo.summation(model.Cost, model.Blend)
Example #31
0
def create_pyomo_network_lp(g,edge_cost_field='VehicleCost',node_rhs_field='b'):
    ## Create the model
    model = pe.ConcreteModel()
    ## Tell pyomo to read in dual-variable information from the solver
    model.dual = pe.Suffix(direction=pe.Suffix.IMPORT)

    ## Associate the graph with this model
    model.g = g

    ## Create the problem data
    model.node_set = pe.Set( initialize=g.nodes() )
    model.edge_set = pe.Set( initialize=g.edges() )
    model.depot_node = pe.Set(initialize=[1])
    
    model.node_rhs = pe.Param( model.node_set, 
            initialize=lambda model, n: model.g.node[n].get(node_rhs_field,0))

    ## Only edge_cost is vehicle cost, no other cost
    model.edge_costs = pe.Param( model.edge_set, 
            initialize=lambda model, i,j: model.g.edge[i][j].get(edge_cost_field,0))


    ## Create the node variables, t_i
    model.x = pe.Var(model.node_set, domain=pe.NonNegativeReals)
    model.x_depot = pe.Var(model.depot_node, domain=pe.NonNegativeReals)
    model.x_except_depot = pe.Var(model.node_set-model.depot_node, domain=pe.NonNegativeReals)

    ## Create the variables
    model.y = pe.Var(model.edge_set, domain=pe.Binary)

    ## Create the objective
    model.OBJ = pe.Objective(expr = pe.summation(model.edge_costs, model.y)+pe.summation(model.edge_costs, model.y))

    ## Create the constraints, one for each node
    def one_in_rule(model, n):
        return ( pe.summation(model.y, index=model.g.in_edges(n)) == 1)
    def one_out_rule(model, n):
        return ( pe.summation(model.y, index=model.g.out_edges(n)) == 1)
        
    def time_A_rule(model, n):
        return ( model.x[n] >= model.g.node[n]['A_1'])
    def time_B_rule(model, n):
        return ( model.x[n] <= model.g.node[n]['B_1'])
    
    def anti_cycle_rule(model,i,j):
        if((i != 1) & (j != 1)):
            return(model.x_except_depot[i] + model.g.edge[i][j]['cost'] - model.x_except_depot[j]<= max((model.g.node[i]['B_1'] + model.g.edge[i][j]['cost'] - model.g.node[j]['A_1']),0)*(1-model.y[(i,j)]))
        else:
            return pe.Constraint.Skip
        
    model.OneIn = pe.Constraint(model.node_set-model.depot_node, rule=one_in_rule)
    model.OneOut = pe.Constraint(model.node_set-model.depot_node, rule=one_out_rule)
    model.TimeA = pe.Constraint(model.node_set-model.depot_node, rule=time_A_rule)
    model.TimeB = pe.Constraint(model.node_set-model.depot_node, rule=time_B_rule)
    model.AntiCycle = pe.Constraint(model.edge_set, rule=anti_cycle_rule)

    # Solve the model
    model.create()

    solver = pyomo.opt.SolverFactory('cplex')
    results = solver.solve(model, tee=True, keepfiles=True)

    # Check that we actually computed an optimal solution, load results
    if (results.solver.status != pyomo.opt.SolverStatus.ok):
        logging.warning('Check solver not ok?')
    if (results.solver.termination_condition != pyomo.opt.TerminationCondition.optimal):  
        logging.warning('Check solver optimality?')

    model.load(results)

    # Print the model objective
    print 'Optimal solution value:', model.OBJ()
    
    # Load solution data back into the networkx object 
    # for e in model.edge_set:
    #     model.g.edge[e[0]][e[1]]['flow_val'] = model.y[e].value

    # for n in model.node_set:
    #     model.g.node[n]['dual_val'] = model.dual[ model.FlowBalance[n] ]

    return model
Example #32
0
	return model.Yall[p,r,f,b,t] == model.Y[p,r,f,b,t]
model.yall_y_binding = pe.Constraint(model.nonfix_var_set*model.time, rule = yall_y_binding_rule)

###Yall setting rule(for fix-pilot part)
def yall_setting_rule(model, p, r, f, b, t):
	df_new = fixed_df.set_index(['Crew_ID','Rank','Cur_Fleet','Current_Base'])
	if (p, r, f, b) in df_new.index:
		return model.Yall[p,r,f,b,t] == 1
	else:
		return model.Yall[p,r,f,b,t] == 0
model.yall_setting = pe.Constraint(model.fix_var_set*model.time, rule = yall_setting_rule)


###OBJ###
###Transitions:
model.total_fleet_trans_cost = pe.summation(model.fleet_transition_cost, model.Y, index = [(p, r, f, b, model.endtime) for(p, r, f, b) in model.to_pos if p in model.fleet_pilots ])
model.total_base_trans_cost = pe.summation(model.base_transition_cost, model.Y, index = [(p, r, f, b, model.endtime) for(p, r, f, b) in model.to_pos if p in model.base_pilots ])
model.total_trans_cost = model.total_fleet_trans_cost + model.total_base_trans_cost
###Shortages:
model.total_shortage_cost = pe.summation(model.short_cost, model.shortage)
###Vacation Penalty:
model.total_vacation_penalty = pe.summation(model.vacation_penalty, model.VP)
model.total_seniority_reward = pe.summation(model.seniority_reward, model.VS)
###Vacation reward:
model.total_vacation_reward = pe.summation(model.vacation_reward,model.V)

###Daily operation cost:
model.operationcost = pe.summation(model.dailycost,model.Yall)
model.operationminus = pe.summation(model.dailycost,model.Ynowork)

model.OBJ = pe.Objective(expr = model.total_shortage_cost + model.total_trans_cost + model.total_vacation_penalty + 7*model.operationcost - 7*model.operationminus - model.total_seniority_reward - model.total_vacation_reward, sense=pe.minimize)
Example #33
0
File: milp.py Project: egbuck/ormm
 def _obj_expression(model):
     """Objective Expression: Maximizing Value"""
     return pyo.summation(model.Values, model.NumActivity)
Example #34
0
from pyomo.opt import SolverFactory

m = pyo.ConcreteModel()

#sets and parameters
m.setMachine = pyo.Set(initialize=['A', 'B', 'C'])
m.Demand = 10000
M = 1e6

#variables
m.C = pyo.Var(m.setMachine, bounds=(0, None))
m.P = pyo.Var(m.setMachine, within=pyo.Integers, bounds=(0, None))
m.B = pyo.Var(m.setMachine, within=pyo.Binary)

#objective function
m.obj = pyo.Objective(expr=pyo.summation(m.C), sense=pyo.minimize)

#constraints
m.C1 = pyo.Constraint(expr=pyo.summation(m.P) == m.Demand)
m.C2 = pyo.Constraint(expr=m.C['A'] == 0.1 * m.P['A']**2 + 0.5 * m.P['A'] +
                      m.B['A'] * 0.1)
m.C3 = pyo.Constraint(expr=m.C['B'] == 0.3 * m.P['B'] + m.B['B'] * 0.5)
m.C4 = pyo.Constraint(expr=m.C['C'] == 0.01 * m.P['C']**3)

m.C5 = pyo.Constraint(expr=m.P['A'] <= m.B['A'] * M)
m.C6 = pyo.Constraint(expr=m.P['B'] <= m.B['B'] * M)

#solve
opt = SolverFactory('couenne')
m.results = opt.solve(m)
Example #35
0
File: milp.py Project: egbuck/ormm
 def _conservation_constraint_rule(model):
     return pyo.summation(model.Blend) == 1
Example #36
0
    df_new = fixed_df.set_index(
        ['Crew_ID', 'Rank', 'Cur_Fleet', 'Current_Base'])
    if (p, r, f, b) in df_new.index:
        return model.Yall[p, r, f, b, t] == 1
    else:
        return model.Yall[p, r, f, b, t] == 0


model.yall_setting = pe.Constraint(model.fix_var_set * model.time,
                                   rule=yall_setting_rule)

###OBJ###
###Transitions:
model.total_fleet_trans_cost = pe.summation(model.fleet_transition_cost,
                                            model.Y,
                                            index=[(p, r, f, b, model.endtime)
                                                   for (p, r, f,
                                                        b) in model.to_pos
                                                   if p in model.fleet_pilots])
model.total_base_trans_cost = pe.summation(model.base_transition_cost,
                                           model.Y,
                                           index=[(p, r, f, b, model.endtime)
                                                  for (p, r, f,
                                                       b) in model.to_pos
                                                  if p in model.base_pilots])
model.total_trans_cost = model.total_fleet_trans_cost + model.total_base_trans_cost
###Shortages:
model.total_shortage_cost = pe.summation(model.short_cost, model.shortage)
###Vacation Penalty:
model.total_vacation_penalty = pe.summation(model.vacation_penalty, model.VP)
model.total_seniority_reward = pe.summation(model.seniority_reward, model.VS)
###Vacation reward:
Example #37
0
def pilot_pos_rule(model, pilot, t):
	lhs = pe.summation(model.Y, index = [(p, r, f, b, t) for (p, r, f, b) in variable_set if p == pilot])
	return lhs == 1
#Parameter and Sets
model.T = pyo.Param(initialize=10)
T = model.T
model.M = pyo.Param(initialize=4)
M = model.M
model.LimProd = pyo.Param(initialize=10)

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

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

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

#constraints
model.C1 = pyo.ConstraintList()
for t in model.setT:
    model.C1.add(expr=2 * x[2, t] - 8 * x[3, t] <= 0)

model.C2 = pyo.ConstraintList()
for t in range(3, T + 1):
    model.C2.add(expr=x[2, t] - 2 * x[3, t - 2] + x[4, t] >= 1)

model.C3 = pyo.ConstraintList()
for t in model.setT:
    model.C3.add(expr=sum([x[m, t] for m in range(1, M + 1)]) <= 50)

model.C4 = pyo.ConstraintList()
Example #39
0
 def ball_constraint(model):
     return summation(model.Variable) == num_balls
Example #40
0
def create_pyomo_network_lp_primal(g):
    model = pe.ConcreteModel()
    model.g = g

    # Create the problem data
    p = list(powerset(g.nodes()))
    model.power_set = pe.Set(initialize=p, dimen=None)

    ## Write some additional code here defining sets, parameters, variables
    # create index
    model.node_set = pe.Set(initialize=model.g.nodes())
    model.arc_set = pe.Set(initialize=model.g.edges())
    departure_arc = []
    for arc in g.edges():
        if arc[0] == "407 Radam Ln":
            departure_arc.append(arc)
    model.departure_arc = pe.Set(initialize=departure_arc)
    return_arc = []
    for arc in g.edges():
        if arc[1] == "407 Radam Ln":
            return_arc.append(arc)
    model.return_arc = pe.Set(initialize=return_arc)

    model.customer_arc = model.arc_set - model.departure_arc - model.return_arc
    model.depotnode = pe.Set(initialize=["407 Radam Ln"])
    model.customer_node = model.node_set - model.depotnode
    model.vehicle = pe.Set(initialize=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    costcf = [1, 1.2, 1.5, 1.8, 2, 2, 2, 2, 2, 2]
    vcostcf = [1, 1.5, 2, 3, 3, 3, 3, 3, 3, 3]
    car_capacity = [100, 200, 300, 500, 600, 600, 600, 600, 600, 600]

    def indexrule(model):
        return [(v, i, j) for v in model.vehicle for i, j in model.arc_set]

    model.veh_arc_set = pe.Set(dimen=3, initialize=indexrule)
    # create parameters
    model.cost = pe.Param(
        model.veh_arc_set, initialize=lambda model, v, i, j: costcf[v] * model.g.edge[i][j]["cost"], mutable=True
    )
    model.vcost = pe.Param(
        model.veh_arc_set,
        initialize=lambda model, v, i, j: vcostcf[v] * model.g.edge[i][j]["VehicleCost"],
        mutable=True,
    )
    model.demand = pe.Param(model.customer_node, initialize=lambda model, n: model.g.node[n]["Demand"], mutable=True)
    model.loadingtime = pe.Param(model.customer_node, initialize=0.25, mutable=True)
    model.Tij = pe.Param(model.arc_set, initialize=lambda model, i, j: model.g.edge[i][j]["cost"], mutable=True)
    model.big_M = 10000
    model.K = len(model.vehicle)
    # create variables
    model.x = pe.Var(model.veh_arc_set, domain=pe.Binary)
    model.y = pe.Var(model.arc_set, domain=pe.Binary)
    model.iv = pe.Var(model.customer_node, domain=pe.Binary)
    model.t = pe.Var(model.customer_node, domain=pe.NonNegativeReals)
    model.t_depot = 9
    model.wt = pe.Var(model.arc_set, domain=pe.NonNegativeReals)
    ## Define objective and constraints
    def pset_rule(model, *q):
        if len(q) == 0 or ("407 Radam Ln" in q):
            return pe.Constraint.Skip
        lhs = 0
        empty = True
        for i in q:
            for j in q:
                if model.g.has_edge(i, j):
                    empty = False
                    lhs = lhs + model.y[(i, j)]
        if empty:
            return pe.Constraint.Skip
        return lhs <= len(q) - 1

    model.PSetConst = pe.Constraint(model.power_set, rule=pset_rule)

    ## Write some code here defining the objective function, rest of constraints etc
    # define objective function
    # model.OBJ = pe.Objective(expr = pe.summation(model.cost, model.x), sense=pe.minimize)
    model.OBJ = pe.Objective(
        expr=pe.summation(model.cost, model.x) + pe.summation(model.vcost, model.x) + pe.summation(model.wt),
        sense=pe.minimize,
    )
    # define flow constraint
    def flow_bal(model, v, n):
        return (
            pe.summation(model.x, index=[(a, i, j) for a, i, j in model.veh_arc_set if j == n if a == v])
            - pe.summation(model.x, index=[(a, i, j) for a, i, j in model.veh_arc_set if i == n if a == v])
            == 0
        )

    model.FlowConst_v1 = pe.Constraint(model.vehicle, model.node_set, rule=flow_bal)
    # define the second constraint
    def sec_const(model, i, j):
        return pe.summation(model.x, index=[(v, i, j) for v in model.vehicle]) == model.y[(i, j)]

    model.ArcConst = pe.Constraint(model.arc_set, rule=sec_const)

    def third_const(model, j):
        return pe.summation(model.y, index=[arc for arc in model.arc_set if arc[1] == j]) == 1

    model.ThirdConst = pe.Constraint(model.customer_node, rule=third_const)

    def forth_const(model, j):
        return pe.summation(model.y, index=[arc for arc in model.arc_set if arc[0] == j]) == 1

    model.ForthConst = pe.Constraint(model.customer_node, rule=forth_const)

    def fif_const(model, depot):
        return pe.summation(model.y, index=[arc for arc in model.arc_set if arc[1] == depot]) <= model.K

    model.FifConst = pe.Constraint(model.depotnode, rule=fif_const)

    def six_const(model, depot):
        return pe.summation(model.y, index=[arc for arc in model.arc_set if arc[0] == depot]) <= model.K

    model.SixConst = pe.Constraint(model.depotnode, rule=six_const)

    def y_flow(model, depot):
        return pe.summation(model.y, index=[arc for arc in model.arc_set if arc[1] == depot]) == pe.summation(
            model.y, index=[arc for arc in model.arc_set if arc[0] == depot]
        )

    model.yflowconst = pe.Constraint(model.depotnode, rule=y_flow)

    def const7(model, k):
        summ = 0
        for j in model.customer_node:
            arclist = [arc for arc in model.arc_set if arc[1] == j]
            for arc in arclist:
                summ = summ + model.demand[j] * model.x[(k, arc[0], arc[1])]
        return summ <= car_capacity[k]

    model.const7 = pe.Constraint(model.vehicle, rule=const7)
    ######################################################################
    # define timewindow constraint
    def timewindow_const1(model, n):
        return model.g.node[n]["A_1"] * model.iv[n] + model.g.node[n]["A_2"] * (1 - model.iv[n]) <= model.t[n]

    model.timeconst1 = pe.Constraint(model.customer_node, rule=timewindow_const1)

    def timewindow_const2(model, n):
        return model.t[n] <= model.g.node[n]["B_1"] * model.iv[n] + model.g.node[n]["B_2"] * (1 - model.iv[n])

    model.timeconst2 = pe.Constraint(model.customer_node, rule=timewindow_const2)

    def finconst(model, i, j):
        return model.t[i] + model.loadingtime[i] + model.Tij[(i, j)] + model.wt[(i, j)] - model.t[j] <= model.big_M * (
            1 - model.y[(i, j)]
        )

    model.finconst = pe.Constraint(model.customer_arc, rule=finconst)

    def finconst2(model, i, j):
        return model.t[i] + model.loadingtime[i] + model.Tij[(i, j)] + model.wt[(i, j)] - model.t[j] >= -model.big_M * (
            1 - model.y[(i, j)]
        )

    model.finconst2 = pe.Constraint(model.customer_arc, rule=finconst2)

    def finconst3(model, n):
        return model.t_depot + model.Tij[("407 Radam Ln", n)] + model.wt[("407 Radam Ln", n)] <= model.t[n]

    model.finconst3 = pe.Constraint(model.customer_node, rule=finconst3)

    # Solve the model
    model.create()
    model = resolve_mip(model)

    # Print the model objective
    print "Primal objective function value:", model.OBJ()
    return model
Example #41
0
 def block_limit_rule(model):
     model.attacks = self._attacks
     return pe.summation(model.x) <= model.attacks  # pylint: disable=no-member
Example #42
0
 def flow_bal(model, v, n):
     return (
         pe.summation(model.x, index=[(a, i, j) for a, i, j in model.veh_arc_set if j == n if a == v])
         - pe.summation(model.x, index=[(a, i, j) for a, i, j in model.veh_arc_set if i == n if a == v])
         == 0
     )
Example #43
0
 def block_limit_rule(model):
     model.attacks = self.attacks
     return pe.summation(model.x) <= model.attacks
Example #44
0
 def sec_const(model, i, j):
     return pe.summation(model.x, index=[(v, i, j) for v in model.vehicle]) == model.y[(i, j)]
Example #45
0
 def third_const(model, j):
     return pe.summation(model.y, index=[arc for arc in model.arc_set if arc[1] == j]) == 1
 def Objective_fn(m):
     return summation(m.P_DB, m.D_DB) + summation(m.P_RB, m.S_RB) + summation(m.P_LB, m.Q_LB)