Example #1
0
def GbpDualStd():
    #  Constants
    Aij = np.random.randint(5, 50, 25)
    Aij = Aij.reshape(5, 5)
    AijSum = np.sum(Aij)
    Cj = np.random.randint(10, 20, 5)
    CjSum = np.sum(Cj)
    Bi = np.random.randint(10, 20, 5)
    BiSum = np.sum(Bi)

    # Matrix Shape
    rows = range(len(Aij))
    cols = range(len(Aij[0]))

    # Instantiate Model
    mDual_Standard_GUROBI = gbp.Model(
        ' -- Standard Dual Linear Programming Problem -- ')

    # Set Focus to Optimality
    gbp.setParam('MIPFocus', 2)

    # Decision Variables
    desc_var = []
    for orig in rows:
        desc_var.append([])
        desc_var[orig].append(
            mDual_Standard_GUROBI.addVar(vtype=gbp.GRB.CONTINUOUS,
                                         name='u' + str(orig + 1)))
    # Slack Variables
    slack_var = []
    for dest in cols:
        slack_var.append([])
        slack_var[dest].append(
            mDual_Standard_GUROBI.addVar(vtype=gbp.GRB.CONTINUOUS,
                                         name='t' + str(dest + 1)))
    # Update Model
    mDual_Standard_GUROBI.update()

    #Objective Function
    mDual_Standard_GUROBI.setObjective(
        gbp.quicksum(Bi[orig] * desc_var[orig][0] for orig in rows),
        gbp.GRB.MAXIMIZE)
    # Constraints
    for dest in cols:
        mDual_Standard_GUROBI.addConstr(
            gbp.quicksum(Aij[orig][dest] * desc_var[orig][0]
                         for orig in rows) + slack_var[dest][0] -
            Cj[dest] == 0)

    # Optimize
    try:
        mDual_Standard_GUROBI.optimize()
    except Exception as e:
        print '   ################################################################'
        print ' < ISSUE : ', e, ' >'
        print '   ################################################################'

    # Write LP file
    mDual_Standard_GUROBI.write('LP.lp')
    print '\n*************************************************************************'
    print '    |   Decision Variables'
    for v in mDual_Standard_GUROBI.getVars():
        print '    |  ', v.VarName, '=', v.x
    print '*************************************************************************'
    val = mDual_Standard_GUROBI.objVal
    print '    |   Objective Value ------------------ ', val
    print '    |   Aij Sum -------------------------- ', AijSum
    print '    |   Cj Sum --------------------------- ', CjSum
    print '    |   Bi Sum --------------------------- ', BiSum
    print '    |   Matrix Dimensions ---------------- ', Aij.shape
    print '    |   Date/Time ------------------------ ', dt.datetime.now()
    print '*************************************************************************'
    print '-- Gurobi Standard Dual Linear Programming Problem --'
def solve_allocation(Robots, Pallets, dist):
    # Build useful data structures
    K = [k.name for k in Robots]
    C = [j.name for j in Pallets]
    J = [j.loc for j in Pallets ]
    L = list(set([l[0] for l in dist.keys()]))
    D = list(set([t.init_loc for t in Robots]))
    cap = {k.name : k.cap for k in Robots}
    loc = {j.name : j.loc for j in Pallets}
    init_loc = {k.name : k.init_loc for k in Robots}
    canCover = {j.name : [k.name for k in j.job.coveredBy] for j in Pallets}
    dur = {j.name : j.job.duration for j in Pallets}
    tStart = {j.name : j.tStart for j in Pallets}
    tEnd = {j.name : j.tEnd for j in Pallets}
    tDue = {j.name : j.tDue for j in Pallets}
    priority = {j.name : j.job.priority for j in Pallets}
    
    ### Create model
    m = gp.Model("trs0")
    
    ### Decision variables
    # Pallet-Robot assignment
    x = m.addVars(C, K, vtype=GRB.BINARY, name="x")
    
    # Robot assignment
    u = m.addVars(K, vtype=GRB.BINARY, name="u")
    
    # Edge-route assignment to Robot
    y = m.addVars(L, L, K, vtype=GRB.BINARY, name="y")
   
    # Robot cannot leave or return to an init_loc that is not its base
    for k in Robots:
        for d in D:
            if k.init_loc != d:
                for i in L:
                    y[i,d,k.name].ub = 0
                    y[d,i,k.name].ub = 0
    
    # Start time of service
    t = m.addVars(L, ub=600, name="t")
    
    # Lateness of service
    z = m.addVars(C, name="z")
    
    # Artificial variables to correct time window upper and lower limits
    xa = m.addVars(C, name="xa")
    xb = m.addVars(C, name="xb")
    
    # Unfilled jobs
    g = m.addVars(C, vtype=GRB.BINARY, name="g")
    
    ### Constraints

    # A Robot must be assigned to a job, or a gap is declared (1)
    m.addConstrs((gp.quicksum(x[j, k] for k in canCover[j]) + g[j] == 1 for j in C), name="assignToJob")
    
    # At most one Robot can be assigned to a job (2)
    m.addConstrs((x.sum(j, '*') <= 1 for j in C), name="assignOne")

    # Robot capacity constraints (3)
    capLHS = {k : gp.quicksum(dur[j]*x[j,k] for j in C) +\
        gp.quicksum(dist[i,j]*y[i,j,k] for i in L for j in L) for k in K}
    m.addConstrs((capLHS[k] <= cap[k]*u[k] for k in K), name="techCapacity")

    # Robot tour constraints (4 and 5)
    m.addConstrs((y.sum('*', loc[j], k) == x[j,k] for k in K for j in C),\
        name="techTour1")
    m.addConstrs((y.sum(loc[j], '*', k) == x[j,k] for k in K for j in C),\
        name="techTour2")

    # Same init_loc constraints (6 and 7)
    m.addConstrs((gp.quicksum(y[j,init_loc[k],k] for j in J) == u[k] for k in K),\
        name="sameinit_loc1")
    m.addConstrs((gp.quicksum(y[init_loc[k],j,k] for j in J) == u[k] for k in K),\
        name="sameinit_loc2")

    # Temporal constraints (8) for Pallet locations
    M = {(i,j) : 600 + dur[i] + dist[loc[i], loc[j]] for i in C for j in C}
    m.addConstrs((t[loc[j]] >= t[loc[i]] + dur[i] + dist[loc[i], loc[j]]\
        - M[i,j]*(1 - gp.quicksum(y[loc[i],loc[j],k] for k in K))\
        for i in C for j in C), name="tempoPallet")
    
    # Temporal constraints (8) for init_loc locations
    M = {(i,j) : 600 + dist[i, loc[j]] for i in D for j in C}
    m.addConstrs((t[loc[j]] >= t[i] + dist[i, loc[j]]\
        - M[i,j]*(1 - y.sum(i,loc[j],'*')) for i in D for j in C),\
        name="tempoinit_loc")

    # Time window constraints (9 and 10)
    m.addConstrs((t[loc[j]] + xa[j] >= tStart[j] for j in C), name="timeWinA")
    m.addConstrs((t[loc[j]] - xb[j] <= tEnd[j] for j in C), name="timeWinB")

    # Lateness constraint (11)
    m.addConstrs((z[j] >= t[loc[j]] + dur[j] - tDue[j] for j in C),\
        name="lateness")

    ### Objective function
    M = 6100
    
    m.setObjective( gp.quicksum( 0.01 * M * priority[j] * (xa[j] + xb[j]) for j in C) +
                   gp.quicksum( M * priority[j] * g[j] for j in C) + \
                   (10.*gp.quicksum(dist[i,j]*y[i,j,k] \
                            for i,j in dist.keys() for k in K)), GRB.MINIMIZE)
    
    m.write("TRS0.lp")
    m.optimize()

    # import pdb; pdb.set_trace()
    status = m.Status
    if status in [GRB.INF_OR_UNBD, GRB.INFEASIBLE, GRB.UNBOUNDED]:
        print("Model is either infeasible or unbounded.")
        sys.exit(0)
    elif status != GRB.OPTIMAL:
        print("Optimization terminated with status {}".format(status))
        sys.exit(0)
        
    ### Print results
    # Assignments
    print("")
    for j in Pallets:
        if g[j.name].X > 0.5:
            jobStr = "Nobody assigned to {} ({}) in {}".format(j.name,j.job.name,j.loc)
        else:
            for k in K:
                if x[j.name,k].X > 0.5:
                    jobStr = "{} assigned to {} ({}) in {}. Start at t={:.2f}.".format(k,j.name,j.job.name,j.loc,t[j.loc].X)
                    if z[j.name].X > 1e-6:
                        jobStr += " {:.2f} minutes late.".format(z[j.name].X)
                    if xa[j.name].X > 1e-6:
                        jobStr += " Start time corrected by {:.2f} minutes.".format(xa[j.name].X)
                    if xb[j.name].X > 1e-6:
                        jobStr += " End time corrected by {:.2f} minutes.".format(xb[j.name].X)
        print(jobStr)

    #import pdb; pdb.set_trace()
    # Robots
    print("")
    for k in Robots:
        if u[k.name].X > 0.5:
            cur = k.init_loc
            route = k.init_loc
            N = 15
            while N>0:
                N -= 1
                for j in Pallets:
                    if y[cur,j.loc,k.name].X > 0.5:
                        #route += " -> {} (dist={}, t={:.2f}, proc={})".format(j.loc, dist[cur,j.loc], t[j.loc].X, j.job.duration)
                        route += " -> {} -> {} (dist={}, t={:.2f}, proc={})".format(j.pick, j.loc, dist[cur,j.loc], t[j.loc].X, j.job.duration)
                        cur = j.loc
                for i in D:
                    if y[cur,i,k.name].X > 0.5:
                        # route += " -> {} (dist={})".format(i, dist[cur,i])
                        cur = i
                        break
                if cur == k.init_loc:
                    break
            print("{}'s route: {}".format(k.name, route))
        else:
            print("{} is not used".format(k.name)) 
            
    
    # Utilization
    print("")
    for k in K:
        used = capLHS[k].getValue()
        util = used / cap[k] if cap[k] > 0 else 0
        print("{}'s utilization is {:.2%} ({:.2f}/{:.2f})".format(k, util,\
            used, cap[k]))
    totUsed = sum(capLHS[k].getValue() for k in K)
    totCap = sum(cap[k] for k in K)
    totUtil = totUsed / totCap if totCap > 0 else 0
    print("Total Robot utilization is {:.2%} ({:.2f}/{:.2f})".format(totUtil, totUsed, totCap))
Example #3
0
# tupledict形式
inflow = {
    ('Pencils', 'Detroit'): 50,
    ('Pencils', 'Denver'): 60,
    ('Pencils', 'Boston'): -50,
    ('Pencils', 'New York'): -50,
    ('Pencils', 'Seattle'): -10,
    ('Pens', 'Detroit'): 60,
    ('Pens', 'Denver'): 40,
    ('Pens', 'Boston'): -40,
    ('Pens', 'New York'): -30,
    ('Pens', 'Seattle'): -30
}

# Create optimization model
m = gp.Model('netflow')

# Create variables
flow = m.addVars(commodities, arcs, obj=cost, name="flow")

# Arc-capacity constraints
m.addConstrs((flow.sum('*', i, j) <= capacity[i, j] for i, j in arcs), "cap")

# Equivalent version using Python looping
# for i, j in arcs:
#   m.addConstr(sum(flow[h, i, j] for h in commodities) <= capacity[i, j],
#               "cap[%s, %s]" % (i, j))

# Flow-conservation constraints
m.addConstrs((flow.sum(h, '*', j) + inflow[h, j] == flow.sum(h, j, '*')
              for h in commodities for j in nodes), "node")
Example #4
0
def MILP_method_for_incentive_synthesis(model, rewards, init, target, blocks,
                                        epsilon):
    # This function synthesizes a sequence of incentives for a given N-BMP instance
    # by solving the corresponding MILP

    # Inputs:
    # model: a class variable corresponding to the given MDP instance
    # rewards: a dict variable corresponding to reward functions of all possible agent types
    # init: a scalar variable corresponding to the initial state of the MDP
    # target: a list variable corresponding to the set of target states
    # blocks: a list variable corresponding to the set of absorbing states
    # epsilon: a scalar variable indicating the suboptimality of the solution

    MDP_m = MDP(model)
    num_of_states = len(MDP_m.states())
    num_of_actions = len(MDP_m.actions())
    num_of_types = len(rewards)

    # Construct initial distribution
    alpha = np.zeros((num_of_states, 1))
    alpha[init] = 1

    # Compute big-M parameters
    R_max = max([
        rewards[i][max(rewards[i], key=rewards[i].get)]
        for i in range(num_of_types)
    ])
    R_min = min([
        rewards[i][min(rewards[i], key=rewards[i].get)]
        for i in range(num_of_types)
    ])
    M_e = 2 * (R_max - R_min + epsilon)

    C = {}
    for pair in MDP_m.state_action_pairs():
        array = []
        for types in range(num_of_types):
            max_reward = R_min
            for act in MDP_m.active_actions()[pair[0]]:
                if rewards[types][(pair[0], act)] > max_reward:
                    max_reward = rewards[types][(pair[0], act)]
            array.append(max_reward - rewards[types][pair])
        C[pair] = max(array) + epsilon

    min_cost, _ = MDP_m.compute_min_cost_subject_to_max_reach(
        init, target, blocks, C)
    M_e_bar = min_cost

    M_e2_bar = num_of_states

    ## Compute max reachability probability and construct reach reward function
    max_reach, _ = MDP_m.compute_max_reach_value_and_policy(
        init, target, blocks)
    reach_rew = MDP_m.reward_for_reach(target)

    ##### Construct the optimization problem
    ## We implement the algorithm without using the variables Q_theta(s,a) and Q_{p,theta}(s,a).
    ## Note that the constraints (20b) and (20k) are redundant equality constraints which are
    ## just introduced to define these variables.
    m = gp.Model()
    #    m.setParam( 'OutputFlag', False )

    # Variables
    gamma = m.addVars(num_of_states, num_of_actions, lb=0.0, name='incentives')
    omega = m.addVar(lb=-GRB.INFINITY)
    X = m.addVars(num_of_types,
                  num_of_states,
                  num_of_actions,
                  vtype=GRB.BINARY,
                  name='actions')  # binary variables
    V_theta = m.addVars(num_of_types,
                        num_of_states,
                        lb=-GRB.INFINITY,
                        name='V_theta')
    V_p = m.addVars(num_of_types, num_of_states, lb=0.0, name='V_p')
    lambda_theta = m.addVars(num_of_types,
                             num_of_states,
                             num_of_actions,
                             lb=0.0,
                             name='lambda_theta')
    mu_theta = m.addVars(num_of_types,
                         num_of_states,
                         num_of_actions,
                         name='mu_theta')

    sum_successor_p = {}
    dummy_integer_counter = {}
    sum_actions_counter = {}
    sum_mu_counter = {}
    total_reach_prob = {}

    for theta in range(num_of_types):
        for state in range(num_of_states):
            sum_mu_counter[(theta, state)] = gp.LinExpr()
            dummy_integer_counter[(theta, state)] = gp.LinExpr()
            sum_actions_counter[(theta, state)] = gp.LinExpr()

            for i, act in enumerate(
                    model[0][state]):  # available actions in a state
                sum_actions_counter[(theta,
                                     state)].add(mu_theta[theta, state, i], 1)
                dummy_integer_counter[(theta,
                                       state)].add(X[theta, state, i], 1)

                ################ McCormick envelopes for mu_theta variables
                ################ Corresponding constraints (20i), (20j)
                m.addConstr(0 <= mu_theta[theta, state, i])
                m.addConstr(
                    mu_theta[theta, state, i] <= M_e2_bar * X[theta, state, i])
                m.addConstr(
                    lambda_theta[theta, state, i] - M_e2_bar *
                    (1 - X[theta, state, i]) <= mu_theta[theta, state, i])
                m.addConstr(
                    mu_theta[theta, state, i] <= lambda_theta[theta, state, i])

                ################ Value function of the agent type theta
                ################ Corresponding constraints -- (20c), (20d)

                m.addConstr(
                    V_theta[theta, state] >= rewards[theta][(state, act)] +
                    gamma[state, i])
                m.addConstr(
                    V_theta[theta, state] <= rewards[theta][(state, act)] +
                    gamma[state, i] + (1 - X[theta, state, i]) * M_e)

                ############## Uniqueness of the agent theta's optimal policy
                ################ Corresponding constraints -- (20e)
                for j, act2 in enumerate(model[0][state]):
                    if act2 != act:
                        m.addConstr( rewards[theta][(state,act2)]+gamma[state,j]+epsilon <= \
                                     rewards[theta][(state,act)]+gamma[state,i]+(1-X[theta,state,i])*M_e)

                ############### Principal's total cost for type theta
                ############### Corresponding constraints -- (20l), (20m)
                sum_successor_p[(theta, state, i)] = gp.LinExpr()
                for k, succ in enumerate(model[1][(state, act)][1]):
                    sum_successor_p[(theta, state,
                                     i)].add(V_p[theta, succ],
                                             model[1][(state, act)][0][k])
                m.addConstr(
                    V_p[theta, state] >= sum_successor_p[(theta, state, i)] +
                    gamma[state, i] - (1 - X[theta, state, i]) * M_e_bar)
                m.addConstr(
                    V_p[theta, state] <= sum_successor_p[(theta, state, i)] +
                    gamma[state, i] + (1 - X[theta, state, i]) * M_e_bar)

            ################ Principal's flow constraint for type theta and state s
            ################ Corresponding constraint -- (20f)
            for pair in model[1]:
                if state in model[1][pair][1]:
                    trans_prob = model[1][pair][1].index(state)
                    act_index = model[0][pair[0]].index(pair[1])
                    sum_mu_counter[(theta, state)].add(
                        mu_theta[theta, pair[0], act_index],
                        model[1][pair][0][trans_prob])
            if state not in target and state not in blocks:
                m.addConstr(sum_actions_counter[(theta, state)] -
                            sum_mu_counter[(theta, state)] == alpha[state])

            ################ Corresponding constraint -- (20o)
            m.addConstr(dummy_integer_counter[(theta, state)] == 1)

        ################ Principal's reachability constraint for type theta
        ################ Corresponding constraint -- (20h)
        total_reach_prob[theta] = gp.LinExpr()
        for pair in model[1]:
            index_action = model[0][pair[0]].index(pair[1])
            total_reach_prob[theta].add(mu_theta[theta, pair[0], index_action],
                                        reach_rew[pair])
        m.addConstr(total_reach_prob[theta] >= max_reach)

        ################ Corresponding constraint -- (20n)
        m.addConstr(omega >= V_p[theta, init])

    m.setObjective(omega, GRB.MINIMIZE)
    m.setParam("IntFeasTol", 1e-4)

    # Optimize model
    m.optimize()

    incentivized_rewards = [{} for k in range(num_of_types)]
    incentive_amount = {}
    for i in range(num_of_types):
        for pair in model[1]:
            index_action = model[0][pair[0]].index(pair[1])
            incentivized_rewards[i][pair] = rewards[i][pair] + gamma[
                pair[0], index_action].x
            incentive_amount[pair] = gamma[pair[0], index_action].x
    compute_time = m.Runtime

    optimal_policy = [{} for k in range(num_of_types)]
    for types in range(num_of_types):
        for state in range(num_of_states):
            optimal_policy[types][state] = model[0][state][0]
            opt_reward = incentivized_rewards[types][(
                state, optimal_policy[types][state])]
            for action in model[0][state]:
                if incentivized_rewards[types][
                    (state, action)] - opt_reward >= epsilon / 10:
                    optimal_policy[types][state] = action
                    opt_reward = incentivized_rewards[types][(state, action)]

    return incentive_amount, incentivized_rewards, optimal_policy, compute_time
Example #5
0
    def solve(self, objective, constraints, cached_data,
              warm_start, verbose, solver_opts):
        """Returns the result of the call to the solver.

        Parameters
        ----------
        objective : LinOp
            The canonicalized objective.
        constraints : list
            The list of canonicalized cosntraints.
        cached_data : dict
            A map of solver name to cached problem data.
        warm_start : bool
            Not used.
        verbose : bool
            Should the solver print output?
        solver_opts : dict
            Additional arguments for the solver.

        Returns
        -------
        tuple
            (status, optimal value, primal, equality dual, inequality dual)
        """
        import gurobipy

        # Get problem data
        data = self.get_problem_data(objective, constraints, cached_data)

        c = data[s.C]
        b = data[s.B]
        A = dok_matrix(data[s.A])
        # Save the dok_matrix.
        data[s.A] = A
        data[s.BOOL_IDX] = solver_opts[s.BOOL_IDX]
        data[s.INT_IDX] = solver_opts[s.INT_IDX]

        n = c.shape[0]

        solver_cache = cached_data[self.name()]

        # TODO warmstart with SOC constraints.
        if warm_start and solver_cache.prev_result is not None \
           and len(data[s.DIMS][s.SOC_DIM]) == 0:
            model = solver_cache.prev_result["model"]
            variables = solver_cache.prev_result["variables"]
            gur_constrs = solver_cache.prev_result["gur_constrs"]
            c_prev = solver_cache.prev_result["c"]
            A_prev = solver_cache.prev_result["A"]
            b_prev = solver_cache.prev_result["b"]

            # If there is a parameter in the objective, it may have changed.
            if len(lu.get_expr_params(objective)) > 0:
                c_diff = c - c_prev

                I_unique = list(set(np.where(c_diff)[0]))

                for i in I_unique:
                    variables[i].Obj = c[i]
            else:
                # Stay consistent with Gurobi's representation of the problem
                c = c_prev

            # Get equality and inequality constraints.
            sym_data = self.get_sym_data(objective, constraints, cached_data)
            all_constrs, _, _ = self.split_constr(sym_data.constr_map)

            # If there is a parameter in the constraints,
            # A or b may have changed.
            if self._param_in_constr(all_constrs):
                A_diff = dok_matrix(A - A_prev)
                b_diff = b - b_prev

                # Figure out which rows of A and elements of b have changed
                try:
                    idxs, _ = zip(*[x for x in A_diff.keys()])
                except ValueError:
                    idxs = []
                I_unique = list(set(idxs) | set(np.where(b_diff)[0]))

                nonzero_locs = gurobipy.tuplelist(A.keys())

                # Update locations which have changed
                for i in I_unique:

                    # Remove old constraint if it exists
                    if gur_constrs[i] is not None:
                        model.remove(gur_constrs[i])
                        gur_constrs[i] = None

                    # Add new constraint
                    if nonzero_locs.select(i, "*"):
                        expr_list = []
                        for loc in nonzero_locs.select(i, "*"):
                            expr_list.append((A[loc], variables[loc[1]]))
                        expr = gurobipy.LinExpr(expr_list)
                        if i < data[s.DIMS][s.EQ_DIM]:
                            ctype = gurobipy.GRB.EQUAL
                        elif data[s.DIMS][s.EQ_DIM] <= i \
                                < data[s.DIMS][s.EQ_DIM] + data[s.DIMS][s.LEQ_DIM]:
                            ctype = gurobipy.GRB.LESS_EQUAL
                        gur_constrs[i] = model.addConstr(expr, ctype, b[i])

                model.update()
            else:
                # Stay consistent with Gurobi's representation of the problem
                A = A_prev
                b = b_prev

        else:
            model = gurobipy.Model()
            variables = []
            for i in range(n):
                # Set variable type.
                if i in data[s.BOOL_IDX]:
                    vtype = gurobipy.GRB.BINARY
                elif i in data[s.INT_IDX]:
                    vtype = gurobipy.GRB.INTEGER
                else:
                    vtype = gurobipy.GRB.CONTINUOUS
                variables.append(
                    model.addVar(
                        obj=c[i],
                        name="x_%d" % i,
                        vtype=vtype,
                        # Gurobi's default LB is 0 (WHY???)
                        lb=-gurobipy.GRB.INFINITY,
                        ub=gurobipy.GRB.INFINITY)
                )
            model.update()

            eq_constrs = self.add_model_lin_constr(model, variables,
                                                   range(data[s.DIMS][s.EQ_DIM]),
                                                   gurobipy.GRB.EQUAL,
                                                   A, b)
            leq_start = data[s.DIMS][s.EQ_DIM]
            leq_end = data[s.DIMS][s.EQ_DIM] + data[s.DIMS][s.LEQ_DIM]
            ineq_constrs = self.add_model_lin_constr(model, variables,
                                                     range(leq_start, leq_end),
                                                     gurobipy.GRB.LESS_EQUAL,
                                                     A, b)
            soc_start = leq_end
            soc_constrs = []
            new_leq_constrs = []
            for constr_len in data[s.DIMS][s.SOC_DIM]:
                soc_end = soc_start + constr_len
                soc_constr, new_leq, new_vars = self.add_model_soc_constr(
                    model, variables, range(soc_start, soc_end),
                    A, b
                )
                soc_constrs.append(soc_constr)
                new_leq_constrs += new_leq
                variables += new_vars
                soc_start += constr_len

            gur_constrs = eq_constrs + ineq_constrs + \
                soc_constrs + new_leq_constrs
            model.update()

        # Set verbosity and other parameters
        model.setParam("OutputFlag", verbose)
        # TODO user option to not compute duals.
        model.setParam("QCPDual", True)

        for key, value in solver_opts.items():
            model.setParam(key, value)

        results_dict = {}
        try:
            model.optimize()
            print(model)
            results_dict["primal objective"] = model.ObjVal
            results_dict["x"] = np.array([v.X for v in variables])

            # Only add duals if not a MIP.
            # Not sure why we need to negate the following,
            # but need to in order to be consistent with other solvers.
            if not self.is_mip(data):
                vals = []
                for lc in gur_constrs:
                    if lc is not None:
                        if isinstance(lc, gurobipy.QConstr):
                            vals.append(lc.QCPi)
                        else:
                            vals.append(lc.Pi)
                    else:
                        vals.append(0)
                results_dict["y"] = -np.array(vals)

            results_dict["status"] = self.STATUS_MAP.get(model.Status,
                                                         s.SOLVER_ERROR)
        except Exception:
            results_dict["status"] = s.SOLVER_ERROR

        results_dict["model"] = model
        results_dict["variables"] = variables
        results_dict["gur_constrs"] = gur_constrs
        results_dict[s.SOLVE_TIME] = model.Runtime

        return self.format_results(results_dict, data, cached_data)
Example #6
0
def optimize_test_capacity_multiple_vaccines_robust(T, Delta, Capacity, Instance):

    m = gp.Model("vaccinations")

    Capacity = 2 * Capacity

    m.Params.LogToConsole = 0
    vaccine = {"Pfizer", "Moderna", "Astrazeneca"}
    dicti = {}
    dict_B = {}
    dict_stocks = {}

    for i in vaccine:
        for j in range(0, T):
            dicti[(i, j)] = [j+1]
            for k in Instance:
                dict_stocks[(i,j,k)] = [j+1]

    combinations, time_frame = gp.multidict(dicti)
    combinations_stock, time_frame = gp.multidict(dict_stocks)

    first_doses = m.addVars(combinations, lb=0.0, vtype=GRB.INTEGER, name="First_Doses")
    second_doses = m.addVars(combinations, lb = 0.0, vtype=GRB.INTEGER, name="Second_Doses")
    stocks = m.addVars(combinations_stock, lb=0.0, vtype=GRB.INTEGER, name="Stocks")
    z = m.addVar(lb = 0.0, vtype = GRB.CONTINUOUS, name="Z")

    m.addConstrs( (first_doses.sum('*',j) + second_doses.sum('*', j) <= Capacity for j in range(0, T)))  

    m.addConstrs( (first_doses[j, i] == second_doses[j,i+Delta[j]] for j, i in combinations if i < T-Delta[j] ))
    m.addConstrs( (first_doses[j, i] == 0 for j, i in combinations if i >= T-Delta[j] ))

    m.addConstrs( second_doses[j,i] == 0 for j, i in combinations if i < Delta[j])
    #m.addConstrs( stocks[j, i, k] <= 10000  for j, i, k in combinations_stock if i == T-1)
    
    m.addConstrs( (first_doses[j,i] + 0 + stocks[j,i,k] == Instance[k][j][i] + 0 for j, i, k in combinations_stock if i == 0))
    m.addConstrs( (first_doses[j,i] + 0 + stocks[j,i,k] == Instance[k][j][i] + stocks[j,i-1,k] for j, i, k in combinations_stock if i >= 1 and i < Delta[j]))
    m.addConstrs( (first_doses[j,i] + first_doses[j,i-Delta[j]] + stocks[j,i,k] == Instance[k][j][i] + stocks[j,i-1,k] for j, i, k in combinations_stock if i >= 1 and i >= Delta[j]))

    for k in Instance:
        m.addConstr( z >= (( 2 / (Instance[k]["TotalB"]) * (gp.quicksum(second_doses[j,i] * i for j,i in combinations) + ( Instance[k]["stock_values_Pfizer"]*(180 + 21) + (Instance[k]["stock_values_Moderna"])*(180 + 28) + (Instance[k]["stock_values_Astrazeneca"])*(180 + 78)))) - Instance[k]["Result"] ) )

    m.setObjective(  z , GRB.MINIMIZE)
    # m.addConstrs( stocks[j, i, k] <= 15000 for j, i, k in stocks_combinations if i == T-1)

    #m.addConstrs ( z >=  ( ( (gp.quicksum(second_doses[j,i] * i   for j,i in combinations))) )   for k in Instance )

    #m.setObjective(  gp.quicksum(second_doses[j,i] * i  + Instance[0]['stock_values_Astrazeneca'] + Instance[0]['stock_values_Moderna'] + Instance[0]['stock_values_Pfizer'] for j,i in combinations ), GRB.MINIMIZE)

    m.optimize()

    if (m.solCount > 0):

        print(m.objVal)

        resultList = m.getAttr(GRB.Attr.X, m.getVars())
            
        first_doses_dict = {}
        second_doses_dict = {}
        stocks_dict = {}

        '''for i in range(0, len(original_B)):
            
            first_doses_dict[list(original_B)[i]] = resultList[T*i:T*(i+1)]
            first_doses_values = resultList[T*i:T*(i+1)]

        for i in range(0, len(original_B)):

            second_doses_dict[list(original_B)[i]] = resultList[T*(i+len(original_B)):T*(i+1+len(original_B))]
            second_doses_values = resultList[T*(i+len(original_B)):T*(i+1+len(original_B))]
        
        for i in range(0, len(original_B)):
            stocks_dict[list(original_B)[i]] = resultList[T*(i+2*len(original_B)):T*(i+1+2*len(original_B))]
            stock_values = resultList[T*(i+2*len(original_B)):T*(i+1+2*len(original_B))]'''

        object_function_value = m.objVal
        return[first_doses_dict, second_doses_dict, stocks_dict, object_function_value]
    else:
        print("\n***** No solutions found *****")
Example #7
0

# Step 3 BOFdat
# Generation of the initial population
population_name = r"C:\Users\maria.moscardo\Desktop\Internship\BOFdat_data\Populations\test_pop"
path_to_model = r"C:\Users\maria.moscardo\Desktop\Internship\BOFdat_data\Recon204_final.xml"
base_biomass_path = r"C:\Users\maria.moscardo\Desktop\Internship\BOFdat\data\bofdat_step2.csv"
exp_essentiality_path = r"C:\Users\maria.moscardo\Desktop\Internship\BOFdat_data\Hela_EG.csv"


# In[1]:


# Set gurobi solver
import gurobipy
gurobipy.Model()
import optlang.gurobi_interface as grb
grb.Model()


# In[ ]:


from BOFdat import step3
step3.generate_initial_population(population_name,
                                  path_to_model,
                                  base_biomass_path,
                                  exp_essentiality_path,
                                  number_of_populations=5)

Aij = []
for i in Cij:
    if i <= S:
        outtext = 1
    else:
        outtext = 0
    Aij.append(outtext)
Cij = np.array(Cij)
Cij = Cij.reshape(5, 5)
rows, cols = Cij.shape
Aij = np.array(Aij)
Aij = Aij.reshape(5, 5)
client_nodes = range(len(Cij[0]))

#     2. Create Model, Set MIP Focus, Add Variables, & Update Model
m = gbp.Model(" -- SCLP -- ")
# Set MIP Focus to 2 for optimality
gbp.setParam('MIPFocus', 2)
# Add Client Decision Variables
client_var = []
for orig in client_nodes:
    client_var.append(
        m.addVar(vtype=gbp.GRB.BINARY, ub=1, name='x' + str(orig + 1)))
# Update Model Variables
m.update()

#     4. Set Objective Function
m.setObjective(gbp.quicksum(client_var[orig] for orig in client_nodes),
               gbp.GRB.MINIMIZE)

#    5. Add Constraints
Example #9
0
def TW(n,q):

    try:
        M = 1e4
        E = 8
        L = 24

        ss = np.random.randint(1,4,n)
        s = list(ss)
        s.insert(0,0) # insert 0 at 0
        s.append(0)  # before and after add 0 element.

        pp = np.random.randint(10,60,n)
        p = list(pp)
        p.insert(0,0)
        p.append(0)  # before and after add 0 element.

        subscript_i = len(s)  # the number of nodes
        subscript_j = subscript_i
        subscript_k = len(q)
        u =24

        m = gp.Model("dis1")

        x = m.addVars(subscript_i, subscript_j, subscript_k, vtype=GRB.BINARY, name="open")
        y = m.addVars(subscript_i, subscript_j, subscript_k, vtype=GRB.BINARY, name="time")
        T = m.addVars(subscript_i, subscript_j, subscript_k, vtype=GRB.BINARY, name="space")

        w = m.addVars(subscript_i,subscript_k, lb=0, name="start")
        m.update()

        # Set objective
        m.setObjective(gp.quicksum((x[i,j,k]*p[i]/q[k] + T[i,j,k]) for k in range(subscript_k) for i in range(subscript_i) for j in range(subscript_j)), GRB.MAXIMIZE)

        # Add constraints
        # constraint 1
        m.addConstrs((gp.quicksum(x[i,j,k] for j in range(1,subscript_j) for k in range(subscript_k)) == 1) for i in range(1,subscript_i-1))

        # constraint 2

        m.addConstrs((gp.quicksum(x[i,j,k] for i in range(subscript_i)) == gp.quicksum(x[j,i,k] for i in range(subscript_i))) for j in range(1,subscript_j-1) for k in range(subscript_k))

        # constraint 3
        m.addConstrs((gp.quicksum(x[0,j,k] for j in range(1,subscript_j)) == 1) for k in range(subscript_k))

        # constraint 4
        m.addConstrs((gp.quicksum(x[i,subscript_j-1,k] for i in range(subscript_i-1)) == 1) for k in range(subscript_k))

        # constraint 5
        m.addConstrs((w[i,k] + s[i] -w[j,k]) <= ((1-x[i,j,k])*M) for k in range(subscript_k) for i in range(subscript_i) for j in range(subscript_j))

        # constraint 6
        m.addConstrs(w[0,k] == E for k in range(subscript_k))
        m.addConstrs(w[subscript_i-1,k] == L for k in range(subscript_k))

        # constructs 7
        m.addConstrs(x[i,i,k] == 0 for i in range(subscript_i) for k in range(subscript_k))

        # constructs 8
        m.addConstrs(T[i,j,k] <= y[i,j,k] for i in range(subscript_i) for j in range(subscript_j) for k in range(subscript_k))

        # constructs 9
        m.addConstrs(T[i,j,k] >= y[i,j,k]- u*(1-x[i,j,k]) for i in range(subscript_i) for j in range(subscript_j) for k in range(subscript_k))

        # constructs 10
        m.addConstrs(T[i,j,k] <= u* x[i,j,k] for i in range(subscript_i) for j in range(subscript_j) for k in range(subscript_k))
        m.write('dis2.lp')

        m.params.outputflag = 0
        m.optimize()

        x_ijk =  m.getAttr('X', x)

        w_ik = m.getAttr('X', w)

        route = []
        serviceT = []
        # Generate the route and Specific service time
        for k in range(subscript_k):
            route.append([0])
            i = 0
            serviceT.append([w_ik[i,k]])
            terminate = True
            while terminate:
                for j in range(subscript_j):
                    if x_ijk[i,j,k] >= 0.5:

                        route[k].append(j)
                        serviceT[k].append(w_ik[j,k])
                        i = j
                        break
                if (i == subscript_i-1):
                    terminate = False

        for i in range(subscript_i-2):

            print('Group {0} service time is {1}'.format(i+1, s[i+1]))
            print('The number of people is {0}'.format(p[i+1]))

        for i in range(len(route)):
            print('The room {0} serves: {1}'.format(i+1, route[i][1:-1]))

            print('Service start time is:' + str(serviceT[i][1:-1]))

        return m.objVal

    except gp.GurobiError as e:
        print('Main-Error code ' + str(e.errno) + ": " + str(e))

    except AttributeError:
        print('Main-Encountered an attribute error')
import gurobipy as grb

model = grb.Model()

# 定义变量的下标
tl = [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)]
vars = model.addVars(tl, name="d")

# 基于元素下标的操作
print(sum(vars.select(1, '*')))
# 输出
# <gurobi.LinExpr: d[1,1] + d[1,2] + d[1,3]>
Example #11
0
regions = list(set(order_regions.values()))

# get stock for each product type in each region
region_stock = {
    r: {
        k: sum([
            warehouse_stock[w][k] for w in warehouses
            if warehouse_regions[w] == r
        ])
        for k in products
    }
    for r in regions
}

#instantiate model object
m = gp.Model('Model A')

## DECISION VARIABLES
flow = {}

# index is (warehouse, order, product)
indices = [(i, j, k) for i in warehouses for j in orders for k in products
           if k in orders_data[j]]
flow = m.addVars(indices, lb=0, vtype=GRB.INTEGER)

#binary variable for incurring fixed cost
fixed_cost_ind = m.addVars([(w, o) for w in warehouses for o in orders],
                           vtype=GRB.BINARY)
# use max stock as big M to activate fixed costs ind
max_stock = max(warehouse_stock[w][k] for w in warehouses for k in products)
# use max regional demand for big M in nonregional flow constraint
Example #12
0
def insd(G, aa, c, sparsed=False):
    """
    Построение таблицы с помощью метода INSD(improved normalized square difference).
    Решает систему G*x = c, где G - матрица and c - вектор ограничений.

    Parameters
    ----------
    G : np.ndarray
        матрица коэффициентов для линейных ограничений
    aa: np.ndarray
        векторизованная базовая матрица
    c: np.ndarray
        вектор ограничений

    Returns
    -------
    a: np.ndarray
        векторизованная матрица результата
    """
    try:
        model = gr.Model("INSD")
        a = aa.astype(float)

        a[aa == 0] = 1e-10
        at = a.flatten()

        # add variable z to model ( z_ij = x_ij/a_ij)
        z = model.addVars(len(at), lb=0., name='z')
        for i in range(len(z)):
            z[i].start = 1.
        model.update()

        # add function for minimization to model
        t = gr.QuadExpr()
        for i in range(len(at)):
            t.add(abs(at[i]) * (z[i] - 1.) * (z[i] - 1.))
        model.setObjective(t)

        # add constraint G*(z.*a)=c
        if sparsed:
            for i in range(G.shape[0]):
                expr = gr.LinExpr()
                start = G.indptr[i]
                end = G.indptr[i + 1]
                idx = G.indices[start:end]
                coef = G.data[start:end] * at[idx]

                for j, k in enumerate(idx):
                    expr.add(z[k], coef[j])
                model.addLConstr(expr, gr.GRB.EQUAL, c[i])
        else:
            cover_rows = [np.nonzero(row)[0] for row in G]

            for i in range(len(G)):
                expr = gr.LinExpr()
                idx = cover_rows[i]
                coef = G[i, idx] * at[idx]

                for j, k in enumerate(idx):
                    expr.add(z[k], coef[j])
                model.addLConstr(expr, gr.GRB.EQUAL, c[i])

        # Set params
        model.setParam('BarConvTol', 1e-8)
        model.setParam('BarQCPConvTol', 1e-6)

        model.setParam('DualReductions', 0)
        # model.setParam('FeasibilityTol',0.01)
        model.setParam('OutputFlag', 0)

        model.optimize()

        result = np.array([v.x for v in model.getVars()])
        return result * at
    except Exception as e:
        logging.error(traceback.format_exc())
        return -1
Example #13
0
def main():

    # 前処理
    # ==============================================================================================

    # ファイルロード
    # File1 = "book/exp_full_height.csv"
    File1 = "/Users/takedakiyoshi/lab/kline/KLINE/高さ制約を比較するフォルダ/exp_full_height.csv"
    # File2 = "data/hold_with_height.csv"
    File2 = "/Users/takedakiyoshi/lab/kline/KLINE/高さ制約を比較するフォルダ/hold_with_height.csv"
    File3 = "data/mainlamp.csv"
    File4 = "data/back_mainlamp.csv"
    File5 = "data/afr_mainlamp.csv"
    File6 = "data/stress_mainlamp.csv"
    File7 = "data/gangnum_2.csv"
    File8 = "data/gangnum_3.csv"

    # 注文情報の読み込み
    T, L, D, J, U, A, G, J_small, J_large, Port, Check_port, Booking, VehicleHeight = Read_booking(
        File1)

    # 船体情報の読み込み1
    I, B, I_pair, I_next, I_same, I_lamp, I_deck, RT_benefit, delta_s, min_s, max_s, delta_h, max_h, Hold_encode, Hold, HoldHeight = Read_hold(
        File2)

    # 船体情報の読み込み2
    Ml_Load, Ml_Back, Ml_Afr, Stress, GANG2, GANG3 \
        = Read_other(File3, File4, File5, File6, File7, File8, Hold_encode)

    # ==============================================
    #print('-----Loaded threshold data-----')
    # print(delta_s)
    # print(delta_h)
    # print(min_s)
    # print(max_s)
    # print(max_h)
    # print("\n")
    #print('-----Loaded instance data-----')
    # print(I)
    # print(I_pair)
    # print(I_next)
    # print(I_same)
    # print(I_lamp)
    # print(I_deck)
    # print(J)
    # print(B)
    # print(A)
    # print("\n")
    # ==============================================

    J_t_load = []  # J_t_load:港tで積む注文の集合
    J_t_keep = []  # J_t_keep:港tを通過する注文の集合
    J_t_dis = []  # J_t_dis:港tで降ろす注文の集合
    J_lk = []  # J_lk:J_t_load + J_t_keep
    J_ld = []  # J_ld:J_t_load + J_t_dis

    for t in T:

        J_load = []
        J_keep = []
        J_dis = []
        lk = []
        ld = []
        tmp_load = list(Port.iloc[:, 0])
        tmp_dis = list(Port.iloc[:, 1])
        N = len(J)

        k = 0
        for i in L:
            if k < i:
                k = i

        count = 0
        for t_l in tmp_load:
            if t == t_l:
                J_load.append(count)
                lk.append(count)
                ld.append(count)
            count = count + 1

        count = 0
        for t_d in tmp_dis:
            if t == t_d:
                J_dis.append(count)
                ld.append(count)
            count = count + 1

        for t_k in range(N):
            if t > tmp_load[t_k] and t < tmp_dis[t_k]:
                J_keep.append(J[t_k])
                lk.append(t_k)

        J_t_load.append(J_load)
        J_t_keep.append(J_keep)
        J_t_dis.append(J_dis)
        J_lk.append(lk)
        J_ld.append(ld)

    # ==============================================
    # print(Port)
    # print(Booking)
    # print(T)
    # print(L)
    # print(D)
    # print(J)
    # print(U)
    # print(J_t_load)
    # print(J_t_keep)
    # print(J_t_dis)
    # print(J_lk)
    # print(J_ld)
    # print(gang_num)
    # print(J_large_divide)
    # print("\n")
    # ==============================================

    # モデリング1(定数・変数の設定)
    # ==============================================================================================

    # Gurobiパラメータ設定
    GAP_SP = gp.Model()
    GAP_SP.setParam("TimeLimit", 7200)
    GAP_SP.setParam("MIPFocus", 1)
    GAP_SP.setParam("LPMethod", 1)
    GAP_SP.printStats()

    # ハイパーパラメータ設定
    # 各目的関数の重み
    w1 = 1
    w2 = 1
    w3 = 1
    w4 = 1
    w5 = 0

    # 最小分割RT
    v_min = 10

    # 目的関数1のペナルティ
    penal1_z = 10

    # 目的関数2のペナルティ
    penal2_load = 1
    penal2_dis = 10

    # 目的関数3のペナルティ
    penal3_m = 10

    # 目的関数4のチェックポイント
    check_point = Check_port

    # 目的関数5のペナルティ
    penal5_k = 1000

    # 最適化変数
    # V_ij:注文jをホールドiにkRT割り当てる
    V_ij = {}
    for i in I:
        for j in J:
            V_ij[i, j] = GAP_SP.addVar(lb=0,
                                       ub=A[j],
                                       vtype=gp.GRB.CONTINUOUS,
                                       name=f"V_ij({i},{j})")

    # 目的関数1
    # X_ij:注文jをホールドiに割り当てるなら1、そうでなければ0
    X_ij = GAP_SP.addVars(I, J, vtype=gp.GRB.BINARY)

    # Y_keep_it:港tにおいてホールドiを通過する注文があるなら1、そうでなければ0
    Y_keep_it = GAP_SP.addVars(I, T, vtype=gp.GRB.BINARY)

    # Y_it1t2:ホールドiにおいてt1で積んでt2で降ろす注文があるなら1、そうでなければ0
    Y_it1t2 = GAP_SP.addVars(I, T, T, vtype=gp.GRB.BINARY)

    # Z_it1t2:ホールドiにおいてt2を通過する注文があるとき異なる乗せ港t1の数分のペナルティ
    Z_it1t2 = GAP_SP.addVars(I, L, D, vtype=gp.GRB.BINARY)

    OBJ1 = gp.quicksum(w1 * penal1_z * Z_it1t2[i, t1, t2] for i in I
                       for t1 in L for t2 in D)

    # 目的関数2
    # Y_load_i1i2t:港tにおいてホールドペア(i1,i2)で積む注文があるなら1
    Y_load_i1i2t = GAP_SP.addVars(I, I, L, vtype=gp.GRB.BINARY)

    # Y_keep_i1i2t:港tにおいてホールドペア(i1,i2)を通過する注文があるなら1
    Y_keep_i1i2t = GAP_SP.addVars(I, I, T, vtype=gp.GRB.BINARY)

    # Y_dis_i1i2t:港tにおいてホールドペア(i1,i2)で揚げる注文があるなら1
    Y_dis_i1i2t = GAP_SP.addVars(I, I, D, vtype=gp.GRB.BINARY)

    # ホールドペア(i1,i2)においてtで注文を積む際に既にtで積んだ注文があるときのペナルティ
    Z1_i1i2t = GAP_SP.addVars(I, I, L, vtype=gp.GRB.BINARY)

    # ホールドペア(i1,i2)においてtで注文を揚げる際にtを通過する注文があるときのペナルティ
    Z2_i1i2t = GAP_SP.addVars(I, I, D, vtype=gp.GRB.BINARY)

    OBJ2_1 = gp.quicksum(penal2_load * Z1_i1i2t[i1, i2, t] for i1 in I
                         for i2 in I for t in L)
    OBJ2_2 = gp.quicksum(penal2_dis * Z2_i1i2t[i1, i2, t] for i1 in I
                         for i2 in I for t in D)
    OBJ2 = w2 * (OBJ2_1 + OBJ2_2)

    # 目的関数3
    # M_it:港tにおいてホールドiが作業効率充填率を超えたら1
    M_it = GAP_SP.addVars(I, T, vtype=gp.GRB.BINARY)

    # M_ijt:港tにおいてホールドiに自動車を積むまでに作業効率充填率を上回ったホールドに自動車を通すペナルティ
    M_ijt = GAP_SP.addVars(I, J, T, lb=0, vtype=gp.GRB.CONTINUOUS)

    OBJ3 = gp.quicksum(w3 * penal3_m * M_ijt[i, j, t] for i in I for j in J
                       for t in T)

    # 目的関数4
    # N_jt:チェックポイントにおけるホールドiの残容量
    N_it = GAP_SP.addVars(I, check_point, lb=0, vtype=gp.GRB.CONTINUOUS)

    OBJ4 = gp.quicksum(w4 * N_it[i, t] * RT_benefit[i] for i in I
                       for t in check_point)

    # 目的関数5
    # K1_it:lampで繋がっている次ホールドが充填率75%を上回ったら1、そうでなければ0
    K1_it = GAP_SP.addVars(I_lamp, L, vtype=gp.GRB.BINARY)

    # K2_it:ホールドiが1RT以上のスペースがあったら1、そうでなければ0
    K2_it = GAP_SP.addVars(I, L, lb=0, vtype=gp.GRB.BINARY)

    # K3_it:目的関数5のペナルティ
    K3_it = GAP_SP.addVars(I_lamp, L, lb=0, vtype=gp.GRB.CONTINUOUS)

    OBJ5 = gp.quicksum(w5 * penal5_k * K3_it[i, t] for i in I_lamp for t in L)

    # 目的関数の設計
    OBJ = OBJ1 + OBJ2 + OBJ3 - OBJ4 + OBJ5
    GAP_SP.setObjective(OBJ, gp.GRB.MINIMIZE)

    # モデリング2(制約)
    # ==============================================================================================

    # 基本制約
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    # 高さ制約
    # ホールドの高さ
    HoldHeightVar = []
    for i in range(len(HoldHeight)):
        HoldHeightVar.append(GAP_SP.addVar(lb=0, vtype=gp.GRB.CONTINUOUS))
    # 車の高さ
    VehicleHeightVar = []
    for i in range(len(VehicleHeight)):
        VehicleHeightVar.append(GAP_SP.addVar(lb=0, vtype=gp.GRB.CONTINUOUS))

    # 制約式
    for i in range(len(HoldHeight)):
        for j in range(len(VehicleHeight)):
            GAP_SP.addConstr(
                VehicleHeightVar[j] * X_ij[i, j] <= HoldHeightVar[i])

    # 割当てた注文がコンパートメント毎にリソースを超えない
    GAP_SP.addConstrs(gp.quicksum(V_ij[i, j] for j in J) <= B[i] for i in I)

    # 全注文内の自動車の台数を全て割り当てる
    GAP_SP.addConstrs(gp.quicksum(V_ij[i, j] for i in I) == A[j] for j in J)

    # VとXの制約
    GAP_SP.addConstrs(V_ij[i, j] / A[j] <= X_ij[i, j] for i in I for j in J)

    # 目的関数の制約
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    # 目的関数1の制約
    for t in T:
        GAP_SP.addConstrs(X_ij[i, j] <= Y_keep_it[i, t] for i in I
                          for j in J_t_keep[t])

    for t in D:
        t2 = t
        for t1 in L:

            J_sub = []  # J_sub:t1で積んでt2で揚げる注文の集合
            for j in J_t_dis[t2]:
                if j in J_t_load[t1]:
                    J_sub.append(j)

            GAP_SP.addConstrs(X_ij[i, j] <= Y_it1t2[i, t1, t2] for i in I
                              for j in J_sub)
            GAP_SP.addConstrs(Z_it1t2[i, t1, t2] <= Y_it1t2[i, t1, t2]
                              for i in I)
            GAP_SP.addConstrs(Z_it1t2[i, t1, t2] <= Y_keep_it[i, t2]
                              for i in I)
            GAP_SP.addConstrs(
                Z_it1t2[i, t1, t2] >= Y_it1t2[i, t1, t2] + Y_keep_it[i, t2] - 1
                for i in I)

    # 目的関数2の制約
    for t in T:
        for i1, i2 in I_pair:
            GAP_SP.addConstrs(
                X_ij[i1, j] + X_ij[i2, j] <= 2 * Y_keep_i1i2t[i1, i2, t]
                for j in J_t_keep[t])

            if t in L:
                GAP_SP.addConstrs(
                    X_ij[i1, j] + X_ij[i2, j] <= 2 * Y_load_i1i2t[i1, i2, t]
                    for j in J_t_load[t])
                GAP_SP.addConstr(
                    Z1_i1i2t[i1, i2, t] <= Y_load_i1i2t[i1, i2, t])
                GAP_SP.addConstr(
                    Z1_i1i2t[i1, i2, t] <= Y_keep_i1i2t[i1, i2, t])
                GAP_SP.addConstr(
                    Z1_i1i2t[i1, i2, t] >= Y_load_i1i2t[i1, i2, t] +
                    Y_keep_i1i2t[i1, i2, t] - 1)

            if t in D:
                GAP_SP.addConstrs(
                    X_ij[i1, j] + X_ij[i2, j] <= 2 * Y_dis_i1i2t[i1, i2, t]
                    for j in J_t_dis[t])
                GAP_SP.addConstr(Z2_i1i2t[i1, i2, t] <= Y_dis_i1i2t[i1, i2, t])
                GAP_SP.addConstr(
                    Z2_i1i2t[i1, i2, t] <= Y_keep_i1i2t[i1, i2, t])
                GAP_SP.addConstr(
                    Z2_i1i2t[i1, i2, t] >= Y_dis_i1i2t[i1, i2, t] +
                    Y_keep_i1i2t[i1, i2, t] - 1)

    # 目的関数3の制約
    for t in T:
        GAP_SP.addConstrs(M_it[i, t] >= -Stress[i] +
                          (gp.quicksum(V_ij[i, j] for j in J_t_keep[t]) / B[i])
                          for i in I)

        for i1 in I:

            I_primetmp = []
            for k in Ml_Load.iloc[i1, :]:
                I_primetmp.append(k)

            I_prime = [x for x in I_primetmp if str(x) != 'nan']
            I_prime.pop(0)

            GAP_SP.addConstrs(M_ijt[i1, j, t] >= gp.quicksum(M_it[i2, t]
                                                             for i2 in I_prime)
                              for j in J_ld[t])

    # 目的関数4の制約
    for t in check_point:
        GAP_SP.addConstrs(N_it[i, t] <= B[i] - gp.quicksum(V_ij[i, j]
                                                           for j in J_lk[t])
                          for i in I)

    # 目的関数5の制約
    GAP_SP.addConstrs(
        K1_it[i, t] >= -0.75 + gp.quicksum(V_ij[i, j] for j in J_lk[t]) / B[i]
        for i in I_lamp for t in L)
    GAP_SP.addConstrs(K2_it[i, t] >= 1 -
                      (gp.quicksum(V_ij[i, j] for j in J_lk[t]) + 1) / B[i]
                      for i in I for t in L)

    for i in range(len(Ml_Back)):
        i1 = Ml_Back.iloc[i, 0]
        I_backtmp = []
        for k in Ml_Back.iloc[i, :]:
            I_backtmp.append(k)

        I_back_i1 = [x for x in I_backtmp if str(x) != 'nan']
        I_back_i1.pop(0)
        GAP_SP.addConstrs(K3_it[i1, t] >= len(I) *
                          (K1_it[i1, t] - 1) + gp.quicksum(K2_it[i2, t]
                                                           for i2 in I_back_i1)
                          for t in L)

    # 特殊制約1(注文の分割制約)
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    # J_smallを分割しない
    GAP_SP.addConstrs(gp.quicksum(X_ij[i, j] for i in I) == 1 for j in J_small)

    # 10RT以下に分割しない
    # GAP_SP.addConstrs(V_ij[i, j] + v_min * (1 - X_ij[i, j])
    #                   >= v_min for i in I for j in J)

    # 特殊制約2(移動経路制約)
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    # 港を通過する荷物が移動の邪魔をしない
    for t in T:
        for i1 in I:

            I_primetmp = []
            Frtmp = []

            for k in Ml_Load.iloc[i1, :]:
                I_primetmp.append(k)

            for k in Ml_Afr.iloc[i1, :]:
                Frtmp.append(k)

            I_prime = [int(x) for x in I_primetmp if str(x) != 'nan']
            Fr = [x for x in Frtmp if str(x) != 'nan']
            I_prime.pop(0)
            Fr.pop(0)

            N_prime = len(I_prime)
            for k in range(N_prime):
                i2 = int(I_prime[k])
                GAP_SP.addConstrs(
                    gp.quicksum(V_ij[i2, j1] for j1 in J_t_keep[t]) /
                    B[i2] <= 1 + Fr[k] - X_ij[i1, j2] for j2 in J_ld[t])

    # 特殊制約3(船体重心の制約)
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    # 船の上下前後の配置バランスが閾値を超えない
    for t in T:

        # 荷物を全て降ろしたとき
        GAP_SP.addConstr(
            gp.quicksum(delta_h[i] * U[j] * G[j] * V_ij[i, j] / A[j]
                        for j in J_t_keep[t] for i in I) <= max_h)
        GAP_SP.addConstr(
            gp.quicksum(delta_s[i] * U[j] * G[j] * V_ij[i, j] / A[j]
                        for j in J_t_keep[t] for i in I) <= max_s)
        GAP_SP.addConstr(
            gp.quicksum(delta_s[i] * U[j] * G[j] * V_ij[i, j] / A[j]
                        for j in J_t_keep[t] for i in I) >= min_s)

        # 荷物を全て載せたとき
        GAP_SP.addConstr(
            gp.quicksum(delta_h[i] * U[j] * G[j] * V_ij[i, j] / A[j]
                        for j in J_lk[t] for i in I) <= max_h)
        GAP_SP.addConstr(
            gp.quicksum(delta_s[i] * U[j] * G[j] * V_ij[i, j] / A[j]
                        for j in J_lk[t] for i in I) <= max_s)
        GAP_SP.addConstr(
            gp.quicksum(delta_s[i] * U[j] * G[j] * V_ij[i, j] / A[j]
                        for j in J_lk[t] for i in I) >= min_s)

    # 特殊制約4(ギャングの制約)
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    """
    count = 0
    for t in L:
       gang = gang_num[count] 
       
       if gang == 2:
           gang_low = GANG2[0]
           gang_high = GANG2[1]
            
           #ギャングの担当領域毎に均等に注文を分ける
           GAP_SP.addConstr(gp.quicksum(V_ij[i1,j] for i1 in gang_low for j in J_t_load[t]) - gp.quicksum(V_ij[i2,j] for i2 in gang_high for j in J_t_load[t]) <= 100)
           GAP_SP.addConstr(gp.quicksum(V_ij[i1,j] for i1 in gang_low for j in J_t_load[t]) - gp.quicksum(V_ij[i2,j] for i2 in gang_high for j in J_t_load[t]) >= -100)
              
       if gang == 3:
           gang_low = GANG3[0]
           gang_mid = GANG3[1]
           gang_high = GANG3[2]
           
           #ギャングの担当領域毎に均等に注文を分ける
           GAP_SP.addConstr(gp.quicksum(V_ij[i1,j] for i1 in gang_low for j in J_t_load[t]) - gp.quicksum(V_ij[i2,j] for i2 in gang_mid for j in J_t_load[t]) <= 100)
           GAP_SP.addConstr(gp.quicksum(V_ij[i1,j] for i1 in gang_low for j in J_t_load[t]) - gp.quicksum(V_ij[i2,j] for i2 in gang_mid for j in J_t_load[t]) >= -100)
           GAP_SP.addConstr(gp.quicksum(V_ij[i1,j] for i1 in gang_low for j in J_t_load[t]) - gp.quicksum(V_ij[i2,j] for i2 in gang_high for j in J_t_load[t]) <= 100)
           GAP_SP.addConstr(gp.quicksum(V_ij[i1,j] for i1 in gang_low for j in J_t_load[t]) - gp.quicksum(V_ij[i2,j] for i2 in gang_high for j in J_t_load[t]) >= -100)
           GAP_SP.addConstr(gp.quicksum(V_ij[i1,j] for i1 in gang_mid for j in J_t_load[t]) - gp.quicksum(V_ij[i2,j] for i2 in gang_high for j in J_t_load[t]) <= 100)
           GAP_SP.addConstr(gp.quicksum(V_ij[i1,j] for i1 in gang_mid for j in J_t_load[t]) - gp.quicksum(V_ij[i2,j] for i2 in gang_high for j in J_t_load[t]) >= -100)
    """

    # 最適化計算
    # ==============================================================================================

    print(
        "\n========================= Solve Assignment Problem ========================="
    )
    GAP_SP.optimize()

    # 解の保存
    # ==============================================================================================

    # 目的関数の値
    val_opt = GAP_SP.ObjVal

    # ペナルティ計算
    print("-" * 65)
    print("penalty count => ")

    # OBJ1のペナルティ
    penal1 = 0
    for i in I:
        for t1 in L:
            for t2 in D:
                if Z_it1t2[i, t1, t2].X > 0:
                    penal1 = penal1 + Z_it1t2[i, t1, t2].X

    # OBJ2のペナルティ
    penal2_1 = penal2_2 = 0
    for i1 in I:
        for i2 in I:
            for t in L:
                if Z1_i1i2t[i1, i2, t].X > 0:
                    penal2_1 = penal2_1 + 1
                    # print(f"ホールド{i1},{i2}で積み地ペナルティ")
            for t in D:
                if Z2_i1i2t[i1, i2, t].X > 0:
                    penal2_2 = penal2_2 + 1
                    # print(f"ホールド{i1},{i2}で揚げ地ペナルティ")

    # OBJ3のペナルティ
    penal3 = 0
    for i in I:
        for j in J:
            for t in T:
                if M_ijt[i, j, t].X > 0:
                    penal3 = penal3 + M_ijt[i, j, t].X

    # OBJ4のペナルティ
    benefit4 = 0
    for t in check_point:
        for i in I:
            if N_it[i, t].X > 0:
                benefit4 = benefit4 + N_it[i, t].X

    # OBJ5のペナルティ
    penal5 = 0
    for t in L:
        for i in I_lamp:
            if K3_it[i, t].X > 0:
                penal5 = penal5 + K3_it[i, t].X

    # 解の書き込み
    answer = []
    assign = []
    for i in I:
        for j in J:
            if V_ij[i, j].X > 0:
                # assign_data[ホールド番号、注文番号、積載RT,RT、ユニット数、積み地、揚げ地]
                answer.append([i, j])
                assign.append([0, 0, V_ij[i, j].X, 0, 0, "L", "D"])

    print("")
    print("[weight]")
    print(f"Object1's weight : {w1}")
    print(f"Object2's weight : {w2}")
    print(f"Object3's weight : {w3}")
    print(f"Object4's weight : {w4}")
    print(f"Object5's weight : {w5}")

    print("")
    print("[penalty & benefit]")
    print(
        f"Different discharge port in one hold                  : {penal1_z} × {penal1}"
    )
    print(
        f"Different loading port in pair hold                   : {penal2_load} × {penal2_1}"
    )
    print(
        f"Different discharge port in pair hold                 : {penal2_dis} × {penal2_2}"
    )
    print(
        f"The number of cars passed holds that exceed threshold : {penal3_m} × {penal3}"
    )
    print(
        f"The benefit remaining RT of hold near the entrance    : {benefit4}")
    print(
        f"The penalty of total dead space                       : {penal5_k} × {penal5}"
    )
    print("")
    print(f" => Total penalty is {val_opt}")
    print("-" * 65)

    # 残リソース
    I_left_data = Hold.iloc[:, 0:2]

    for k in range(len(assign)):

        key = Booking.columns.get_loc('Index')
        i_t = answer[k][0]
        j_t = int(Booking.iloc[answer[k][1], key])

        # hold_ID
        assign[k][0] = Hold.iloc[i_t, 0]

        # order_ID
        assign[k][1] = Booking.iloc[j_t, Booking.columns.get_loc('Order_num')]

        # RT
        assign[k][3] = Booking.iloc[j_t, Booking.columns.get_loc('RT')]

        # Units(original booking)
        assign[k][4] = Booking.iloc[j_t, Booking.columns.get_loc('Units')]
        """
        for j in range(len(divide_dic)):
            if assign[k][1] - 1 == divide_dic[j][0]:
                assign[k][3] = divide_dic[j][1]
        """

        # L_port
        assign[k][5] = Booking.iloc[j_t, Booking.columns.get_loc('LPORT')]

        # D_port
        assign[k][6] = Booking.iloc[j_t, Booking.columns.get_loc('DPORT')]

        # 残リソース計算
        I_left_data.iloc[answer[k][0],
                         1] = I_left_data.iloc[answer[k][0], 1] - assign[k][2]
        if I_left_data.iloc[answer[k][0], 1] < 0.1:
            I_left_data.iloc[answer[k][0], 1] = 0

    csv = []
    for k in range(len(assign)):
        if assign[k][2] > 0.1:
            csv.append(assign[k])

    c_list = []
    c_list.append("Hold_ID")
    c_list.append("Order_ID")
    c_list.append("Load_RT")
    c_list.append("RT_sum")
    c_list.append("Units")
    c_list.append("LPORT")
    c_list.append("DPORT")
    assign_data = pd.DataFrame(csv, columns=c_list)
    assign_data.to_excel('result/assignment.xlsx', index=False, columns=c_list)
    I_left_data.to_excel('result/leftRT.xlsx', index=False)
 def _build_model(self):
     
     self.model = gb.Model()
     self._build_variables()
     self._build_objective()
     self._build_constraints()
Example #15
0
@author: woute
"""

from Iteration import *
import gurobipy as grb

raw_input = ('Hit Enter to continue')

row_loop = True


#Same as 'Iteration.py'

while row_loop == True:

    m = grb.Model('MinAllocCost')
    
    # DECISION VARIABLES
    tpre     = {}    #t_p^r,e
    tprb     = {}    #t_p^r,b
    fik      = {}    #f_i^k
    yak      = {}    #y_a^k 
    
    ### CREATE INITIAL DECISION VARIABLES ###########################################################################################
    
    #t_p^r for economy
    for p in range(len(itinerary_no)):
        for r in list(r_obj[p]):
            tpre[p,r] = m.addVar(vtype=GRB.CONTINUOUS, lb=0,
            name="t_%s^{%s,e}"%(p,r))
            tpre[r,p] = m.addVar(vtype=GRB.CONTINUOUS, lb=0,
Example #16
0
#!/usr/bin/env python3

import gurobipy as gb

m = gb.Model()

x1 = m.addVar(lb=-gb.GRB.INFINITY, ub=gb.GRB.INFINITY, vtype=gb.GRB.CONTINUOUS)
x2 = m.addVar(lb=-gb.GRB.INFINITY, ub=gb.GRB.INFINITY, vtype=gb.GRB.CONTINUOUS)

m.update()

m.addConstr(-4 * x1 - 9 * x2 <= -18)
m.addConstr((3 / 2) * x1 - x2 <= 27 / 4)
m.addConstr(-(8 / 17) * x1 + x2 <= 2)

m.setObjective(-x1 + 2 * x2, sense=gb.GRB.MINIMIZE)

m.optimize()

print('')
print('Optimal solution?: ', m.status == gb.GRB.OPTIMAL)
print('Optimal objective: ', m.objVal)
print('Solution: x1 = {0}, x2 = {1}'.format(x1.x, x2.x))
Example #17
0
def optimize_test_capacity_multiple_vaccines(T, B, Delta, Capacity, heu_result, alpha):

    m = gp.Model("vaccinations")

    somma = sum(B["Pfizer"]) + sum(B["Astrazeneca"]) + sum(B["Moderna"])

    m.Params.LogToConsole = 0

    dicti = {}
    dict_B = {}

    for i in B:
        for j in range(0, T):
            dicti[(i, j)] = [j+1]
            dict_B[(i,j)] = B[i][j]  
    original_B = B
    B = dict_B

    combinations, time_frame = gp.multidict(dicti)

    first_doses = m.addVars(combinations, lb=0.0, vtype=GRB.INTEGER, name="First_Doses")
    second_doses = m.addVars(combinations, lb = 0.0, vtype=GRB.INTEGER, name="Second_Doses")
    stocks = m.addVars(combinations, lb=0.0, vtype=GRB.INTEGER, name="Stocks")
    z = m.addVar(lb = 0.0, vtype = GRB.INTEGER, name="Z")

    m.addConstrs( (first_doses.sum('*',j) + second_doses.sum('*', j) <= Capacity for j in range(0, T)))  

    m.addConstrs( (first_doses[j, i] == second_doses[j,i+Delta[j]] for j, i in combinations if i < T-Delta[j] ))
    m.addConstrs( (first_doses[j, i] == 0 for j, i in combinations if i >= T-Delta[j] ))

    m.addConstrs( second_doses[j,i] == 0 for j, i in combinations if i < Delta[j])
    
    m.addConstrs( (first_doses[j,i]  + 0 + stocks[j,i] == B[j,i] + 0 for j, i in combinations if i == 0))
    m.addConstrs( (first_doses[j,i] + 0 + stocks[j,i] == B[j,i] + stocks[j,i-1] for j, i in combinations if i >= 1 and i < Delta[j]))
    m.addConstrs( (first_doses[j,i] + first_doses[j,i-Delta[j]] + stocks[j,i] == B[j,i] + stocks[j, i-1] for j, i in combinations if i >= 1 and i >= Delta[j]))

    for i in range(0, 180):
            m.addConstr( z >= first_doses["Astrazeneca",i] + first_doses["Moderna",i] + first_doses["Pfizer",i] + second_doses["Astrazeneca",i] + second_doses["Moderna",i] + second_doses["Pfizer",i])

    # m.setObjective( alpha * (z / Capacity ) + (1-alpha) * ( ( ( gp.quicksum(second_doses[j,i] * i for j,i in combinations ) + stocks["Pfizer", T-1] * (180 + Delta["Pfizer"]) + stocks["Moderna", T-1] * (180 + Delta["Moderna"]) + stocks["Astrazeneca", T-1] * (180 + Delta["Astrazeneca"])  ) / (somma / 2) ) / heu_result ) + ( 1000 * ( stocks['Pfizer', T-1] + stocks['Moderna', T-1] + stocks['Astrazeneca', T-1]) ), GRB.MINIMIZE)
    m.setObjective( alpha * (z) + (1-alpha) * ( ( ( gp.quicksum(second_doses[j,i] * i for j,i in combinations ) + stocks["Pfizer", T-1] * (180 + Delta["Pfizer"]) + stocks["Moderna", T-1] * (180 + Delta["Moderna"]) + stocks["Astrazeneca", T-1] * (180 + Delta["Astrazeneca"]) ) / (1) ) / 1)  + 1000 * (stocks["Astrazeneca", T-1] + stocks["Moderna", T-1] + stocks["Pfizer", T-1]) , GRB.MINIMIZE)

    m.optimize()
        
    if (m.solCount > 0):

        resultList = m.getAttr(GRB.Attr.X, m.getVars())
            
        first_doses_dict = {}
        second_doses_dict = {}
        stocks_dict = {}

        for i in range(0, len(original_B)):
            
            first_doses_dict[list(original_B)[i]] = resultList[T*i:T*(i+1)]
            first_doses_values = resultList[T*i:T*(i+1)]

        for i in range(0, len(original_B)):

            second_doses_dict[list(original_B)[i]] = resultList[T*(i+len(original_B)):T*(i+1+len(original_B))]
            second_doses_values = resultList[T*(i+len(original_B)):T*(i+1+len(original_B))]
        
        for i in range(0, len(original_B)):
            stocks_dict[list(original_B)[i]] = resultList[T*(i+2*len(original_B)):T*(i+1+2*len(original_B))]
            stock_values = resultList[T*(i+2*len(original_B)):T*(i+1+2*len(original_B))]

        max_value = 0
        for kk in range (0, 180):
            somma = second_doses["Astrazeneca", kk].X + second_doses["Moderna",kk].X + second_doses["Pfizer", kk].X + first_doses["Astrazeneca", kk].X + first_doses["Moderna",kk].X + first_doses["Pfizer", kk].X
            if somma > max_value:
                max_value = somma
        object_function_value = m.objVal

        return[first_doses_dict, second_doses_dict, stocks_dict, object_function_value, z.X]
    else:
        print("\n***** No solutions found *****")
Example #18
0
from math import exp


def f(u):
    return exp(-u)


def g(u):
    return 2 * u * u - 4 * u


try:

    # Create a new model

    m = gp.Model()

    # Create variables

    lb = 0.0
    ub = 1.0

    x = m.addVar(lb, ub, name='x')
    y = m.addVar(lb, ub, name='y')
    z = m.addVar(lb, ub, name='z')

    # Set objective for y

    m.setObjective(-y)

    # Add piecewise-linear objective functions for x and z
A[:,:-1]=mp
B[:,:-1]=uc

for loop in range(len(test_mean)):
    l[loop,int(alllabels[loop])]=1
    l[loop,150]=0.5

# escalation and negative data set have ones on the last column
for loop in range(len(test_mean), len(alllabels)):
    l[loop, 150]=1
    
#best result

try:
    m = grby.Model("Optimal Threshold Problem")
    
    rowcount = len(A)
    ncl=151
    
#     x = m.addVars(rowcount*ncl, vtype=GRB.BINARY, name="x")
    
#     b = m.addVar(lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, name="b")
#     c = m.addVar(lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, name="c")
#     d = m.addVar(lb=0.0, ub=3.0, vtype=GRB.CONTINUOUS, name="d")
    
    x = m.addVars(rowcount*ncl, vtype=GRB.BINARY, name="x")
    y = m.addVars(rowcount*ncl, vtype=GRB.BINARY, name="y")
    z = m.addVars(rowcount*ncl, vtype=GRB.BINARY, name="z")
    b = m.addVar(lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, name="b")
    c = m.addVar(lb=0.0, ub=1.0, vtype=GRB.CONTINUOUS, name="c")
Example #20
0
    def _construct_local_problem(self, scenario, lambda_k):
        # TODO I generate the entire local model every iteration, even though the only thing changing is the objective
        # It would be faster to store the model once it's generated the first time and then to just change the objective.
        ##################################################################
        # local optimization program (inner problem) for single scenario #
        ##################################################################

        scenario_program = gb.Model()

        # -- variables -- #
        x = {}
        for i in range(self.n_x):
            x[i] = scenario_program.addVar(
                obj=scenario.c[1][i] * scenario.probability - lambda_k[i],
                lb=scenario.lb[1][i],
                ub=scenario.ub[1][i],
                vtype=scenario.vtype[1][i],
                name='x{}'.format(i))
        y = {}
        for i in range(self.n_y):
            y[i] = scenario_program.addVar(obj=scenario.c[2][i] *
                                           scenario.probability,
                                           lb=scenario.lb[2][i],
                                           ub=scenario.ub[2][i],
                                           vtype=scenario.vtype[2][i],
                                           name='y{}'.format(i))
        scenario_program.update()

        # -- constraints -- #
        # first stage (sparse matrix)
        lhs = defaultdict(gb.LinExpr)
        for entry in scenario.A[1, 1].items():
            row, column = entry[0]
            value = entry[1]
            lhs[row] = lhs[row] + value * x[column]

        for row, value in enumerate(scenario.b[1]):
            scenario_program.addConstr(lhs[row],
                                       scenario.b_sense[1][row],
                                       scenario.b[1][row],
                                       name='stage1_row{}'.format(row))

        # constraints, second-stage; contribution to lhs from A[2,1]
        lhs_1 = defaultdict(gb.LinExpr)
        for entry in scenario.A[2, 1].items():
            row, column = entry[0]
            value = entry[1]
            lhs_1[row] = lhs_1[row] + value * x[column]
        # contribution from A[2,2]
        lhs_2 = defaultdict(gb.LinExpr)
        for entry in scenario.A[2, 2].items():
            row, column = entry[0]
            value = entry[1]
            lhs_2[row] = lhs_2[row] + value * y[column]

        for row, value in enumerate(scenario.b[2]):
            scenario_program.addConstr(lhs_1[row] + lhs_2[row],
                                       scenario.b_sense[2][row],
                                       scenario.b[2][row],
                                       name='stage2_sc{}_row{}'.format(
                                           scenario.scenario_id, row))
        scenario_program.update()
        return scenario_program, x, y
def solve_optimization(x,
                       mu,
                       c=1.0,
                       k=GaussianKernel(),
                       tolerance=1e-4,
                       adjustment=0):
    '''Builds and solves the constrained optimization problem on the basis
   of the fuzzy learning procedure.

Arguments:

- x: iterable of objects
- mu: iterable of membership values for the objects in x
- c: constant managing the trade-off in joint radius/error optimization
- k: kernel function to be used
- tolerance: tolerance to be used in order to clamp the problem solution to
             interval extremes
- adjustment: diagonal adjustment in order to deal with non PSD matrices

Returns: a lists containing the optimal values for the two sets of independent
         variables chis of the problem

Throws:

- ValueError if c is non-positive or if x and mu have different lengths

'''
    if c <= 0:
        raise ValueError('c should be positive')

    if len(x) != len(mu):
        raise ValueError('patterns and labels have different length')

    m = len(x)

    mu = np.array(mu)

    model = gpy.Model('possibility-learn')
    model.setParam('OutputFlag', 0)

    for i in range(m):
        if c < np.inf:
            model.addVar(name='chi_%d' % i,
                         lb=-c * (1 - mu[i]),
                         ub=c * mu[i],
                         vtype=gpy.GRB.CONTINUOUS)

        else:
            model.addVar(name='chi_%d' % i, vtype=gpy.GRB.CONTINUOUS)

    model.update()

    chis = model.getVars()

    obj = gpy.QuadExpr()

    for i, j in it.product(range(m), range(m)):
        obj.add(chis[i] * chis[j], k.compute(x[i], x[j]))

    for i in range(m):
        obj.add(-1 * chis[i] * k.compute(x[i], x[i]))

    if adjustment:
        for i in range(m):
            obj.add(adjustment * chis[i] * chis[i])

    model.setObjective(obj, gpy.GRB.MINIMIZE)

    constEqual = gpy.LinExpr()
    constEqual.add(sum(chis), 1.0)

    model.addConstr(constEqual, gpy.GRB.EQUAL, 1)

    model.optimize()

    if model.Status != gpy.GRB.OPTIMAL:
        raise ValueError('optimal solution not found!')

    chis_opt = [
        chop(ch.x, l, u, tolerance)
        for ch, l, u in zip(chis, -c * (1 - np.array(mu)), c * np.array(mu))
    ]

    return chis_opt
Example #22
0
def interior_point_using_distance(coefficients,
                                  nCuts,
                                  dim,
                                  marker,
                                  weight,
                                  index=-1):
    ''' Get the interior point from the certain region described by marker. The returned point should be far from all the hyperplanes. 
    coefficients: the coefficients of hyperplanes with the same order. For example, (a1, a2, a3, c) in the hyperplane (a1 * x1 + a2 * x2 + a3 * x3 + c = 0)
    nCuts: the number of the hyerplanes.
    Dim: the dimension of the space.
    marker: the sign of the hyperplane.
    weight: calcualte the norm 2 of the coefficients except the constant of all hyperplanes  
    index: the hyperplane we want to trim. Usually index = -1, which means no hyperplane will be trimed.
    
    Here, we add the different weights for different hyperplanes when we calculate the distance.

    maximize z
     subject to  A*x + b + weight*z <= np.spacing(1), for all sign >=0
                       -1*(A*x + b) + weight*z <= np.spacing(1), for all sign <= 0
    '''

    #Create a new model
    m = gb.Model('Interior_point')

    #Set parameters
    m.setParam('OutputFlag', False)

    x = [0 for i in xrange(dim)]
    for i in xrange(dim):
        x[i] = m.addVar(lb=-1e7,
                        ub=1e7,
                        vtype=gb.GRB.CONTINUOUS,
                        name='x_%d' % (i))

    obj = m.addVar(lb=0.0, vtype=gb.GRB.CONTINUOUS, name='objective')
    m.update()

    for i in xrange(nCuts):
        #hyperplane index is trimed, so there is no constraint for index hyperplane.
        if index != i:
            g_expr = gb.LinExpr()
            g_expr.addConstant(coefficients[i][-1])
            for j in xrange(dim):
                g_expr.add(x[j] * coefficients[i][j])
            if marker[i] == 0:
                m.addConstr(-1 * g_expr + weight[i] * obj <= np.spacing(0),
                            name='qc_%d' % (i))
            elif marker[i] == 1:
                m.addConstr(g_expr + weight[i] * obj <= np.spacing(0),
                            name='qc_%d' % (i))
    m.update()

    #Create the objective : maximize obj
    m.setObjective(obj, gb.GRB.MAXIMIZE)
    m.update()

    #Optimize the test problem.
    try:
        m.optimize()
    except gb.GurobiError as e:
        print e.message

    if m.Status == gb.GRB.OPTIMAL:
        xOpt = np.empty(dim)
        for i in xrange(dim):
            xOpt[i] = x[i].x
        return m.Status, xOpt, obj.x
    else:
        return m.Status, np.nan, np.nan
Example #23
0
    cut = []
    for i,j in fullgraph.edges():
        if i in subtourset and j not in subtourset:
            cut.append((i,j))
        elif j in subtourset and i not in subtourset:
            cut.append((j,i))
    
    #Add cut constraint
    varsx = Model.addVars(cut)
    for i,j in varsx.keys():
        varsx[i,j] = vars[i,j]
    Model.addConstr(varsx.sum() >= 2)
    

#Generate Gurobi model
m = grb.Model()

#Create variables - edges
edgedict = dict(nx.get_edge_attributes(G, 'weight'))
vars = m.addVars(edgedict.keys(), obj=edgedict, vtype=grb.GRB.BINARY, name='edge')
for i,j in vars.keys():
    vars[j,i] = vars[i,j] # edge in opposite direction is equal and referred to edge

#Add initial constraints: Degree of each node = 2
m.addConstrs(vars.sum(i,'*') == 2 for i in G.nodes())

#First Iteration:
m.optimize()
FG = saveresult(draw=True)
tour = findsubtour(FG, 'city 1')
Example #24
0
    def __init__(self, data, objective, nr_runways=1):
        """Represents an instance of the aircraft landing problem.

        - i as aircraft unique id within the problem instance
        - E as vector of earliest landing times
        - T as vector of target landing times
        - L as vector of latest landing times
        - h as vector of penalty costs per time unit before target landing time
        - g as vector of penalty cost per time unit after target landing time

        In addition, an instance can be solved for either one (default)
        or multiple runways which are treated equally.

        The problem can be solved for two objectives:
        - linear: minimize weighted earliness and lateness
        - non-linear: maximize utilization (earliness)

        Args:
            data (list of ints): instance data according to the
                specification of the OR library (see Beasley (1990)).
            objective (ALP.Objective): 'min_cost' for minimized weighted earliness
                and lateness or 'max_util' for maximized earliness
            nr_runways (int): number of equally treated runways
                the instance should be solved for
        """
        # store persistent copy of input data
        self._data = copy.copy(data)

        # Parse input data
        self.E = list()
        self.T = list()
        self.L = list()
        self.S = list()
        self.h = list()
        self.g = list()
        self.nr_planes = int(data.pop(0))

        int(data.pop(0))  # freeze time: discarded
        for i in range(self.nr_planes):
            int(data.pop(0))  # appearance time: discarded
            self.E.append(int(data.pop(0)))  # earliest landing time
            self.T.append(int(data.pop(0)))  # target landing time
            self.L.append(int(data.pop(0)))  # latest landing time
            self.g.append(data.pop(0))  # penalty before target
            self.h.append(data.pop(0))  # penalty after target
            # separation times to preceeding aircraft
            self.S.append([int(data.pop(0)) for j in range(self.nr_planes)])

        # fig = plt.figure()
        # ax = fig.add_subplot(111)
        # plt.plot(range(self.nr_planes),self.E)
        # plt.plot(range(self.nr_planes),self.T)
        # plt.plot(range(self.nr_planes),self.L)
        # plt.legend(["earliest landing time", "target landing time", "latest landing time"], loc="upper right")
        # plt.xlabel("planes")
        # plt.ylabel("time")
        # ax.xaxis.set_major_locator(MaxNLocator(integer=True))
        # plt.savefig("Test_data.png")

        if nr_runways <= 0:
            raise ValueError("Illegal number of runways: %d" % nr_runways)
        else:
            self.nr_runways = nr_runways

        # Perform Pre-Processing
        self.U, self.V, self.W = self._preprocess_airplanes()

        # Configure linear program
        self._objective = objective
        self._mode = None

        # model is only solvable for linear objective
        if self._objective is ALP.Objective.min_cost:
            # maintain separate models to avoid re-building if mode is switched

            self._objectives = {ALP.Mode.normal: None, ALP.Mode.relaxed: None}
            self._normal_model = grb.Model()
            self._relaxed_model = grb.Model()

            self._constrs = {
                self._normal_model: dict(),
                self._relaxed_model: dict()
            }  # store all constraints
            self._dvars = {
                self._normal_model: dict(),
                self._relaxed_model: dict()
            }  # store all decision variables

            self._build_dynamic_model(self._normal_model)
            self._enforce_sep_time(self._normal_model)

            self._build_dynamic_model(self._relaxed_model)
            self._relax_sep_time(self._relaxed_model)
Example #25
0
def pov_oracle_iter(e, cand, mu, stepsize):
    t0 = time.process_time()
    convex = False
    opp = cand.opp
    # if cand.id == "A":
    #     A, B = cand, cand.opp
    # else:
    #     B, A = cand, cand.opp
    m = gp.Model("POV")
    c = e.theta + (opp.goal - e.theta) * opp.p * opp.X
    u = cand.marginal_payoff(e, opp.X)

    # decision variables, bounded between 0 and 1
    X = m.addVars([i for i in range(e.n)], name=["X" + str(i) for i in range(e.n)], ub=[1./cand.p[i] for i in range(e.n)])

    # objective function
    obj = gp.QuadExpr()
    for i in range(e.n):
        y = 0
        for j in range(e.n):
            y += e.P_T.item(i, j) * (e.theta[j] + (opp.goal - e.theta[j]) * opp.p[j] * opp.X[j] + (cand.goal-e.theta[j]) * cand.p[j]*X[j] \
             + (2 * e.theta[j] - 1) * cand.p[j] * opp.p[j] * opp.X[j] * X[j]) 
        obj += y * y
    

    # check if either A losing and optimizing for A, or B losing and optimizing for B
    if (mu < (e.n+1)/2 and cand.id == "A") or (mu > (e.n+1)/2 and cand.id == "B"):
        convex = True
        m.setObjective(obj, gp.GRB.MINIMIZE)
    else:
        convex = False
        m.setObjective(obj, gp.GRB.MAXIMIZE)
        m.params.NonConvex = 2

    # budget constraint
    m.addConstr(X.sum() <= cand.k)

    # expected value constraint
    mean = gp.LinExpr()
    sign = 1 if cand.goal else -1
    for i in range(e.n):
        mean += sign * X[i] * u[i] + e.alpha[i] * c[i]
    m.addConstr(mean == mu)

    # min/max opinion constraint
    m.addConstrs((X[i] <= cand.max_expenditure(e, opp.X, i) for i in range(e.n)))

    m.setParam("OutputFlag", 0);
    m.setParam('TimeLimit', 4*60)

    m.optimize()

    # for v in m.getVars():
    #     print('%s %g' % (v.varName, v.x))
    # print('Obj: %g' % m.objVal)
    X_cand = []
    for i, var in enumerate(m.getVars()):
        if var.x <=1:
            X_cand.append(var.x)
        else:
            X_cand.append(1/cand.p[i])
    cand.X = X_cand
    print("Probability Xp", np.multiply(cand.X, cand.p))
    assert all([x <=1.001 for x in list(np.multiply(cand.X, cand.p))])
    assert all([x <=1 for x in list(np.multiply(cand.X, cand.p))])
    print("Probability Xp", np.multiply(cand.X, cand.p))
    t1 = time.process_time()
    
    return X_cand, convex, t1-t0
    def solve(self,
              dict_data,
              sam,
              n_scenarios,
              time_limit=None,
              gap=None,
              verbose=False):
        nodes = range(dict_data['n_nodes'])
        scenarios = range(n_scenarios)

        problem_name = "StohasticSaphlp"
        logging.info("{}".format(problem_name))

        model = gp.Model(problem_name)

        # Z is a vector that tells us the nodes which host a hub
        Z = model.addVars(dict_data['n_nodes'],
                          lb=0,
                          ub=1,
                          vtype=GRB.INTEGER,
                          name='Z')

        # X is a matrix which tells us which node is linked to a hub
        # (if Xik == 1, then node i is linked to a hub in node k, if Xik == 0 then no link b\w i and k)
        X = model.addVars(dict_data['n_nodes'],
                          dict_data['n_nodes'],
                          n_scenarios,
                          lb=0,
                          ub=1,
                          vtype=GRB.INTEGER,
                          name='X')

        # objective function 1st stage
        obj_funct = gp.quicksum(dict_data['f'][i] * Z[i] for i in nodes)

        # objective function 2nd stage - 1st term
        for s in scenarios:
            temp = 0
            for i in nodes:
                for k in nodes:
                    if i != k:
                        temp += sam.c[i, k, s] * X[i, k, s]
            obj_funct += temp / n_scenarios

        # objective function 2nd stage - 2nd term
        A = 0
        B = 0
        C = 0
        D = 0
        for s in scenarios:
            s_term = 0
            for i in nodes:
                for j in nodes:
                    A = dict_data['d'][i, j] * Z[i] * Z[j]

                    for l in nodes:
                        if l != j:
                            B += dict_data['d'][i, l] * Z[i] * X[j, l, s]

                    for k in nodes:
                        if i != k:
                            C += dict_data['d'][k, j] * X[i, k, s] * Z[j]

                    for l in nodes:
                        for k in nodes:
                            if i != k:
                                if j != l:
                                    D += (dict_data['d'][k, l] * X[i, k, s] *
                                          X[j, l, s])
                    s_term += dict_data['alpha'] * sam.w[i, j,
                                                         s] * (A + B + C + D)

                    A = 0
                    B = 0
                    C = 0
                    D = 0

            obj_funct += s_term / n_scenarios

        model.setObjective(obj_funct, GRB.MINIMIZE)

        # constraint equation 25
        for s in scenarios:
            for i in nodes:
                sum_constr = 0
                for k in nodes:
                    if i != k:
                        sum_constr += X[i, k, s]
                model.addConstr(sum_constr == (1 - Z[i]), f"only _one_hubs{s}")

        # constraint equation 26
        for s in scenarios:
            for i in nodes:
                for k in nodes:
                    if k != i:
                        model.addConstr(X[i, k, s] <= Z[k],
                                        f"nodes_no connected{i, k, s}")

        model.update()
        if gap:
            model.setParam('MIPgap', gap)
        if time_limit:
            model.setParam(GRB.Param.TimeLimit, time_limit)
        if verbose:
            model.setParam('OutputFlag', 1)
        else:
            model.setParam('OutputFlag', 0)
        model.setParam('LogFile', './logs/gurobi.log')
        model.write("./logs/model.lp")

        start = time.time()
        model.optimize()
        end = time.time()
        comp_time = end - start

        solZ = np.zeros(shape=dict_data['n_nodes'])
        solX = np.zeros(shape=(dict_data['n_nodes'], dict_data['n_nodes'],
                               n_scenarios))

        of = -1

        if model.status == GRB.Status.OPTIMAL:
            for k in nodes:
                grb_var1 = model.getVarByName(f"Z[{k}]")
                solZ[k] = grb_var1.X
            for s in scenarios:
                for i in nodes:
                    for k in nodes:
                        grb_var2 = model.getVarByName(f"X[{i},{k},{s}]")
                        solX[i, k, s] = grb_var2.X
            of = model.getObjective().getValue()

        return of, solZ, solX, comp_time
Example #27
0
def min_max_distance(pod_sites, blocks, distance, population, loadingSites, capacity, supplies, labor, cost, budget, opening_cost, bigM, max_days_open):
    ####### MODEL 2
    m2 = gp.Model()

    ### Decision variables
    ## number of days POD is open for
    x2 = m2.addVars(pod_sites, vtype=GRB.CONTINUOUS, lb = 0.0)
    ## whether or not a block is assigned to a POD
    y2 = m2.addVars(pod_sites, blocks, vtype=GRB.BINARY)
    ## whether or not a POD is open
    z2 = m2.addVars(pod_sites, vtype=GRB.BINARY)
    ## M - the maximum distance any one car is allowed to travel
    M = m2.addVar(lb=0.0, obj=1.0, vtype=GRB.CONTINUOUS)

    ### Objective function
    ## want to minimize the total/weighted travel distance of Allegheny's population
    m2.setObjective(M)
    m2.modelSense = GRB.MINIMIZE
    
    ### Constraints
    ## all pod sites are bounded by a given capacity
    for i in pod_sites:
        #m1.addConstr(sum(y1[i, k]*population[k] for k in blocks) <= capacity[i]*x1[i])
        m2.addConstr(sum(y2[i, k]*population[k] for k in blocks) == capacity[i]*x2[i])
        m2.addConstr(z2[i]*bigM >= x2[i])
        m2.addConstr(x2[i] <= max_days_open)
     
    ## each block is assigned to exactly 1 pod site
    for k in blocks:
        m2.addConstr(sum(y2[i, k] for i in pod_sites) == 1)

        # the total money used is at most the maximum budget
        m2.addConstr(sum(cost[i]*x2[i] + z2[i]*opening_cost for i in pod_sites) <= budget)

    for i in pod_sites:
        for k in blocks:
            ## max dist traveled for anyone is M
            m2.addConstr(distance[k, i]*y2[i,k] <= M)

    ## Solve
    m2.optimize()

    lst = []
    lst_np = np.zeros([len(pod_sites), 1100])
    pod_days = []
    block_dist = []
    #long_ls_vals = []

    for i in pod_sites:
        for k in blocks:
            #if(x1[i].x >= 0): ## this will still print out all of them since weakly greater than 0.
            if(x2[i].x > 0):
                lst_np[i,k] = distance[k,i]*y2[i,k].x
                lst.append((budget, opening_cost, i, k, distance[k,i]*y2[i,k].x))

                #long_ls_vals.append((budget, opening_cost, m1.objVal, i, x1[i].x, k, distance[k,i]*y1[i,k].x))
        pod_days.append((i, x2[i].x))

    for k in blocks:
        for i in pod_sites:
            if(y2[i, k].x > 0):
                block_dist.append((k, distance[k,i]*y2[i,k].x, i)) 
    
    # Print optimized solution
    print(m2.objVal)

    return(m2.objVal, pod_days, block_dist)
}

interest_rate = 0.03

additional_budget = 50

# creates lower triangular matrix needed in Value at Risk analysis in Q4 using Cholesky factorization
# Note that this results in L to be in matrix format (i.e., not in the dataframe format anymore)
L = np.linalg.cholesky(cov)

########################################
########### MODEL ######################
########################################

# Create an empty model
m = gp.Model('portfolio')
m.update()

# ADD DECISION VARIABLES (AND FOR Q4 HELPER DECISION VARIABLES) HERE
vars = pd.Series(m.addVars(projects, vtype=GRB.BINARY), index=projects)
h = m.addVar()

########################################
#### CONSTRAINTS & OBJ FUNCTIONS #######
########################################

# ADD CONSTRAINTS HERE
for x in ther:
    m.addConstr(sum(vars * cost * (t_area == x)) <= t_bud[x], f'{x} budget')

m.addConstr(sum(vars * (ttm == '1')) >= 0.15 * sum(vars), '1 year')
Example #29
0
def lp_scheduler(M, DAG, M_SRC, M_SNK, G, P, C, S, R, L_SLO):

    print("M_SRC Source Nodes:")
    print(M_SRC)
    print("M_SNK Sink Nodes:")
    print(M_SNK)
    print("DAG:")
    print(DAG)

    P_conf = gp.tuplelist([(m, g, k) for m in M for g in G for k in range(len(P[m, g]))])

    P_b = {(m, g, k): P[m, g][k][0] for m, g, k in P_conf}
    P_p = {(m, g, k): P[m, g][k][1] for m, g, k in P_conf}
    P_l = {(m, g, k): P[m, g][k][2] for m, g, k in P_conf}
    P_d = {(m, g, k): P[m, g][k][3] for m, g, k in P_conf}

    # print("P_conf PROFILE CONF:")
    # print(P_conf)
    # print("P_b BATCH:")
    # print(P_b)
    # print("P_p PARALLEL:")
    # print(P_p)
    # print("P_l Expected LATENCY:")
    # print(P_l)
    # print("P_d DURATION:")
    # print(P_d)

    C = {g: 1.0 for g in G}

    # print("COST:")
    # print(C)

    R_upper = {(m, g, k): R[m] for m, g, k in P_conf}
    # print("R_upper Input Rate ub:")
    # print(R_upper)

    # Constants
    capacity = 1.0

    # Decision Variables

    model = gp.Model("Resource_Allocation")

    x = model.addVars(P_conf, vtype=GRB.BINARY, name='X')
    r = model.addVars(P_conf, vtype=GRB.INTEGER, ub=R_upper, name='R')
    u = model.addVars(P_conf, vtype=GRB.CONTINUOUS, ub=capacity, name='U')
    st = model.addVars(M, vtype=GRB.CONTINUOUS, ub=L_SLO, name='ST')
    l_max = model.addVar(vtype=GRB.CONTINUOUS, ub=L_SLO, name='L_max')
    model.update()

    # print("VARIABLE: X")
    # print(x)
    # print("VARIABLE: R")
    # print(r)
    # print("VARIABLE: U")
    # print(u)
    # print("VARIABLE: ST")
    # print(st)
    # print("VARIABLE: L_max")
    # print(l_max)

    # Objective Function
    obj = gp.quicksum(
        C[g] * x[m, g, k]
            for m, g, k in P_conf)

    model.setObjective(obj, GRB.MINIMIZE)

    # Constraints

    model.addConstrs(
        (gp.quicksum(x[m, g, k] 
        for k in range(len(P[m, g]))) <= 1 
        for m in M for g in G), 
        name="Constr1")

    model.addConstrs(
        (r[m, g, k] == 0 
        for m, g, k in P_conf 
        if not x[m, g, k]), 
        name="Constr2")

    model.addConstrs(
        (gp.quicksum(x[m, g, k] * r[m, g, k] 
        for g in G 
        for k in range(len(P[m, g])) 
        if x[m, g, k]) == R[m]
        for m in M), 
        name="Constr3")

    model.addConstrs(
        (u[m, g, k] == 0 
        for m, g, k in P_conf 
        if not x[m, g, k]), 
        name="Constr4")

    model.addConstrs(
        (u[m, g, k] == (r[m, g, k]/(P_b[m, g, k] * P_p[m, g, k] / P_d[m, g, k])) 
        for m, g, k in P_conf 
        if x[m, g, k]), 
        name="Constr5")

    model.addConstrs(
        (gp.quicksum(u[m, g, k] 
        for m in M 
        for k in range(len(P[m, g]))) <= 1.0 
        for g in G), 
        name="Constr6")

    model.addConstrs(
        (st[m] == 0.0
        for m in M_SRC),
        name="Const7")

    model.addConstrs(
        (st[m] >= st[l] + (x[l, g, k] * P_l[l, g, k])
        for l, m in DAG
        for temp, g, k in P_conf
        if temp == l),  
        name='Constr8')

    model.addConstrs(
        (l_max >= st[m] + (x[m, g, k] * P_l[m, g, k])
        for m in M_SNK
        for temp, g, k in P_conf
        if temp == m),  
        name='Constr9')


    model.addConstr(
        (l_max <= L_SLO),
        name="Const10")

    model.Params.Threads = 1

    # Run Optimization
    model.optimize()

    print('Runtime (in ms): ', model.Runtime*1000)
    model.printAttr('X')

    model.write('Resource_Allocation.lp')
Example #30
0
#        x +   y + 2 z
#  subject to
#        x + 2 y + 3 z <= 4
#        x +   y       >= 1
#        x, y, z binary

import gurobipy as gp
from gurobipy import GRB
import numpy as np
import scipy.sparse as sp

if __name__ == "__main__":
    try:

        # Create a new model
        m = gp.Model("matrix1")

        # Create variables
        x = m.addMVar(shape=3, vtype=GRB.BINARY, name="x")

        # Set objective
        obj = np.array([1.0, 1.0, 2.0])
        m.setObjective(obj @ x, GRB.MAXIMIZE)

        # Build (sparse) constraint matrix
        val = np.array([1.0, 2.0, 3.0, -1.0, -1.0])
        row = np.array([0, 0, 0, 1, 1])
        col = np.array([0, 1, 2, 0, 1])

        A = sp.csr_matrix((val, (row, col)), shape=(2, 3))