Example #1
1
def get_mapping(PG, VG):
    vnodes, vhosts = multidict({n: len(VG.node[n]['host_ports']) for n in VG.nodes()})
    pnodes, phosts = multidict({n: len(PG.node[n]['host_ports']) for n in PG.nodes()})
    parcs, pcapacity = multidict({(m, n): PG.edge[m][n]['weight'] for (m, n) in PG.edges()})
    parcs = tuplelist(parcs)

    varcs, vcapacity = multidict({(m, n): VG.edge[m][n]['weight'] for (m, n) in VG.edges()})
    varcs = tuplelist(varcs)

    m = Model('mapping')

    # Create variables
    node_mapping = {}
    for i in vnodes:
        for j in pnodes:
            node_mapping[i, j] = m.addVar(vtype=GRB.BINARY, name="x_%s_%s" % (i, j))


    edge_mapping = {}
    for i in vnodes:
        for p in VG.neighbors(i):
            for (j, q) in parcs:
                edge_mapping[i, p, j, q] = m.addVar(vtype=GRB.BINARY, name="y_%s_%s_%s_%s" % (i, p, j, q))

    m.update()

    # Arc capacity constraints
    for i in vnodes:
        m.addConstr(quicksum(node_mapping[i, j] for j in pnodes) == 1, 'node_%s' % i)

    for i in vnodes:
        for p in VG.neighbors(i):
            for (j, q) in parcs:
                m.addConstr(edge_mapping[i, p, j, q] <= ( node_mapping[i, j] + node_mapping[p, q] )/2, 'edge_%s_%s_%s_%s' % (i, p, j, q))

    for (j, q) in parcs:
        m.addConstr(quicksum(edge_mapping[i, p, j, q] + edge_mapping[p, i, j, q]for (i, p) in varcs) <= pcapacity[j, q], 'pcap_%s_%s' % (j, q))

    for (i, p) in varcs:
        m.addConstr(quicksum(edge_mapping[i, p, j, q] + edge_mapping[p, i, j, q] for (j, q) in parcs) >= vcapacity[i, p], 'vcap_%s_%s' % (i, p))

    for j in pnodes:
        m.addConstr(quicksum(node_mapping[i, j] * vhosts[i] for i in vnodes) <= phosts[j], 'phosts_%s' % j)
    for i in vnodes:
        m.addConstr(quicksum(node_mapping[i, j] * phosts[j] for j in pnodes) >= vhosts[i], 'vhosts_%s' % i)
    # Compute optimal solution
    m.optimize()

    # Print solution
    if m.status == GRB.status.OPTIMAL:
        mapping = {}
        mapping2 = {}
        portlist = {}

        for n in PG:
            if 'host_ports' in PG.node[n]:
                portlist[n] = PG.node[n]['host_ports']

        solution = m.getAttr('x', edge_mapping)
        for h in solution:
            if solution[h] == 1.0:
                vid1, vid2, pid1, pid2 = h
                vport1, vport2 = list(VG.node[vid1]['links'][vid2])[0]

                if (vid1, pid1) not in mapping:
                    mapping[(vid1, pid1)] =[vid1, pid1]
                if (pid1, vid1) not in mapping2:
                    mapping2[(pid1, vid1)] =[pid1, vid1]
                (pport1, pport2) = PG.node[pid1]['links'][pid2].pop()
                # print vid1, vid2, pid1, pid2, pport1, pport2
                if pid1 != pid2:
                    PG.node[pid2]['links'][pid1].remove((pport2, pport1))
                mapping[(vid1, pid1)].append(vport1)
                mapping[(vid1, pid1)].append(pport1)
                mapping2[(pid1, vid1)].append(pport1)
                mapping2[(pid1, vid1)].append(vport1)

                if (vid2, pid2) not in mapping:
                    mapping[(vid2, pid2)] =[vid2, pid2]
                if (pid2, vid2) not in mapping2:
                    mapping2[(pid2, vid2)] =[pid2, vid2]
                mapping[(vid2, pid2)].append(vport2)
                mapping[(vid2, pid2)].append(pport2)
                mapping2[(pid2, vid2)].append(pport2)
                mapping2[(pid2, vid2)].append(vport2)

        solution2 = m.getAttr('x', node_mapping)
        print [h for h in solution2 if solution2[h] == 1.0]
        for h in solution2:
            if solution2[h] == 1.0:
                vid, pid = h
                if len(VG.node[vid]['host_ports']) == 0:
                    continue

                for vport in VG.node[vid]['host_ports']:
                    pport = portlist[pid].pop()
                    mapping[(vid, pid)].append(vport)
                    mapping[(vid, pid)].append(pport)
                    mapping2[(pid, vid)].append(pport)
                    mapping2[(pid, vid)].append(vport)

    return mapping, mapping2


def main():
    args = parse_args()

    VG = gen_graph(args.target_topology)
    if not networkx.is_connected(VG):
        print 'Target topology is not connected'
        sys.exit(1)

    PG = gen_graph(args.host_topology, int_idx=True)

    mapping, mapping2 = get_mapping(PG, VG)

    f = open(args.output, "w")
    print >>f, "P2Vmap"
    for id in mapping2:
        for id2 in mapping2[id]:
            print >>f, id2,
        print>>f, "65535 65535"
    print >>f, "V2Pmap"
    for id in mapping:
        for id2 in mapping[id]:
            print >>f, id2,
        print>>f, "65535 65535"


if __name__ == "__main__":
    main()
Example #2
0
    def _build_variables(self):
        """
        Build variables.
        """

        edge_flow, lbs, ubs = gp.multidict(self._edge_flow_data)
        self._edge_flow_vars = self._model.addVars(edge_flow,
                                                   name="flow",
                                                   lb=lbs,
                                                   ub=ubs)
        node_pressure, lbs, ubs = gp.multidict(self._node_pressure_data)
        self._node_press_vars = self._model.addVars(node_pressure,
                                                    name="pressure",
                                                    lb=lbs,
                                                    ub=ubs)
        node_flow, lbs, ubs = gp.multidict(self._node_flow_data)
        self._node_flow_vars = self._model.addVars(node_flow,
                                                   name="flow",
                                                   lb=lbs,
                                                   ub=ubs)
        if self._compr_incr_data:
            compressor_increase, lbs, ubs = gp.multidict(self._compr_incr_data)
            self._compr_vars = self._model.addVars(compressor_increase,
                                                   name="compressor_incr",
                                                   lb=lbs,
                                                   ub=ubs,
                                                   obj=1.0)
        else:
            self._compr_vars = {}
Example #3
0
def solver(directed_graph):
    """Solves a simple single commoditiy network-flow problem using the data from the user specified graph. Basically
    just a simplified version of the netflow.py example from the gurobi documentation. """

    nodes, generated_flow = gp.multidict(directed_graph.nodes)
    edges, capacity, cost = gp.multidict(directed_graph.edges)

    model = gp.Model('network_flow')
    flow = model.addVars(edges, lb=0, obj=cost, name="flow")

    # Flow capacity constraints
    model.addConstrs(flow[i, j] <= capacity[i, j] for i, j in edges)
    # Flow balance constraints, basically: flow generated by node + input flow to node = output flow from node
    model.addConstrs(generated_flow[j] + flow.sum('*', j) == flow.sum(j, '*') for j in nodes)

    for i, j in edges:
        print(i)
        print(j)

    model.optimize()

    sol_flow = model.getAttr('x', flow)
    obj_val = model.getAttr('ObjVal')
    for i, j in edges:
        cost[(i, j)] = sol_flow[i, j]
    print(sol_flow)
    return sol_flow, obj_val
    def _add_initial_heading(self, times, initial_heading):
        if get_array_greater_zero(initial_heading):
            # create degrees for all initial headings
            degrees = grb.tupledict()
            arcs = grb.tuplelist()
            for index in range(len(self.graph.vertices)):
                v_a = np.array(self.graph.vertices[index])
                ad_indexes = [
                    j for j in range(len(self.graph.vertices))
                    if self.graph.ad_matrix[index, j] > 0
                ]
                vert_arr = np.array(
                    [self.graph.vertices[i] for i in ad_indexes])
                l = len(vert_arr)
                degrees = np.array([
                    get_angle(v_a, vert, initial_heading[index])
                    for vert in vert_arr
                ])
                tuple_list = [((index, ad_indexes[i]), degrees[i])
                              for i in range(l)]
                # Correct entries with NaN
                for i in range(len(tuple_list)):
                    if tuple_list[i] == np.NaN:
                        tuple_list[i][-1] = 0

                arcs_i, multidict_i = grb.multidict(
                    tuple_list) if tuple_list else (None, None)
                degrees.update(multidict_i)
                arcs.extend(arcs_i)

            for arc in arcs:
                self.model.addConstr(times[arc] >= degrees[arc],
                                     name="degree_constraint_init")
Example #5
0
 def __init__(self, DMUs_Name, X, Y, AP=False):
     self.m1, self.m1_name, self.m2, self.m2_name, self.AP = X.shape[
         1], X.columns.tolist(), Y.shape[1], Y.columns.tolist(), AP
     self.DMUs, self.X, self.Y = gurobipy.multidict({
         DMU: [X.loc[DMU].tolist(), Y.loc[DMU].tolist()]
         for DMU in DMUs_Name
     })
     print(f'DEA(AP={AP}) MODEL RUNING...')
Example #6
0
 def get_arcs_capacity(self, sn_directed_graph):
     arcs_cap_dict = {}
     edges = list(sn_directed_graph.edges)
     sn_directed_graph.edges[edges[0]]
     for e in edges:
         arcs_cap_dict[e] = sn_directed_graph.edges[e]['BW_max'] - sn_directed_graph.edges[e]['BW_used']
     arcs, capacity = gp.multidict(arcs_cap_dict)
     return arcs, capacity
 def _get_angles(self, index, ad_indexes) -> list:
     v_a = np.array(self.graph.vertices[index])
     vert_arr = np.array([self.graph.vertices[i] for i in ad_indexes])
     l = len(vert_arr)
     degrees = get_angles(v_a, vert_arr)
     tuple_list = [((index, ad_indexes[i], ad_indexes[j]), degrees[i, j])
                   for i in range(l) for j in range(l) if i != j]
     arcs, multidict = gurobipy.multidict(tuple_list) if tuple_list else (
         None, None)
     return arcs, multidict
 def _get_angles(self, index) -> (grb.tuplelist, grb.tupledict):
     v_a = np.array(self.graph.vertices[index])
     ad_indexes = [
         j for j in range(len(self.graph.vertices))
         if self.graph.ad_matrix[index, j] > 0
     ]
     vert_arr = np.array([self.graph.vertices[i] for i in ad_indexes])
     l = len(vert_arr)
     degrees = get_angles(v_a, vert_arr)
     tuple_list = [((index, ad_indexes[i], ad_indexes[j]), degrees[i, j])
                   for i in range(l) for j in range(i + 1, l)]
     arcs, multidict = grb.multidict(tuple_list) if tuple_list else (None,
                                                                     None)
     return arcs, multidict
 def _get_angles(self, index) -> (grb.tuplelist, grb.tupledict):
     v_a = np.array(self.graph.vertices[index])
     ad_indexes = [
         j for j in range(len(self.graph.vertices))
         if self.graph.ad_matrix[index, j] > 0
     ]
     vert_arr = np.array([self.graph.vertices[i] for i in ad_indexes])
     l = len(vert_arr)
     degrees = get_angles(v_a, vert_arr)
     tuple_list = [((index, ad_indexes[i], ad_indexes[j]), degrees[i, j])
                   for i in range(l) for j in range(l) if i != j]
     # Correct entries with NaN
     for i in range(len(tuple_list)):
         if np.isnan(tuple_list[i][-1]):
             tuple_list[i] = (tuple_list[i][0], 0)
     arcs, multidict = grb.multidict(tuple_list) if tuple_list else (None,
                                                                     None)
     return arcs, multidict
    def maxFlow_gurobi(self):
        cap = {}
        wei = {}
        g = self.G
        for k in g.edges(data=True):
            cap[(k[0], k[1])] = k[2]["capacity"]
            wei[(k[0], k[1])] = k[2]["weight"]

        import gurobipy as gu

        edgeIdx, capacity = gu.multidict(cap)
        m = gu.Model()
        x = m.addVars(edgeIdx, name='flow')

        consts1 = m.addConstrs((x.sum('*', v) == x.sum(v, '*') for v in set(g.nodes).difference(set(['s', 't']))),
                               name="flow_conservation")
        m.addConstrs((x[e[0], e[1]] <= capacity[e[0], e[1]] for e in edgeIdx), "capacityConst")
        m.setObjective(x.sum('s', '*'), gu.GRB.MAXIMIZE)
        # m.write("model.lp")
        m.optimize()
        maxFlowVal = m.objVal
        m.addConstr(x.sum('*', 't') == maxFlowVal)
        m.setObjective(gu.quicksum(wei[e[0], e[1]] * x[e[0], e[1]] for e in edgeIdx), gu.GRB.MAXIMIZE)
        # y[0] = quicksum(x.select(1, '*'))
        # y[1] = quicksum(x.select(8, '*'))
        #
        # m.setObjectiveN( | y[0] - y[1] |, 1)
        m.optimize()

        xvar = pd.DataFrame(columns=['varName', 'value', 'reducedCost', 'lb', 'ub'])
        for i, v in enumerate(x):
            xvar.loc[i] = [v, x[v].x, x[v].RC, x[v].SAObjLow, x[v].SAObjUp]
        xvar.set_index('varName', inplace=True)
        duals = {}
        for c in consts1:
            duals[c] = consts1[c].PI
        self.x = xvar
        self.dual = duals
        return xvar, duals
Example #11
0
def ip_coloring(G, m):
    colors = []
    color_vector_gen = _color_vector_gen(m)
    while len(colors) < len(G):
        try:
            colors.append(next(color_vector_gen))
        except StopIteration:
            break
    m = grb.Model('min_coloring')
    vertex_color_cost_dict = {}
    for v, data in G.nodes(data=True):
        weight = data['weight']
        for k in range(len(colors)):
            vertex_color_cost_dict[(v, k)] = weight * sum(colors[k])
    vertex_color_id, vertex_color_cost = grb.multidict(vertex_color_cost_dict)
    vertex_color_state = m.addVars(vertex_color_id,
                                   lb=0,
                                   ub=1,
                                   name='vertex_colors',
                                   vtype=grb.GRB.BINARY)
    for v in G:
        variables = [vertex_color_state[(v, k)] for k in range(len(colors))]
        expr = grb.quicksum(variables)
        m.addConstr(expr, grb.GRB.EQUAL, 1)
    for u, v in G.edges():
        for k in range(len(colors)):
            m.addConstr(
                vertex_color_state[(u, k)] + vertex_color_state[(v, k)] <= 1)
    m.setObjective(vertex_color_state.prod(vertex_color_cost),
                   grb.GRB.MINIMIZE)
    m.optimize()
    if m.status == grb.GRB.Status.OPTIMAL:
        print(m.getAttr('x', vertex_color_state))
        print('cost: {}'.format(m.objVal))
        return m.objVal
    else:
        print('No Solution Found')
        return None
def main(budget=3):
    data = read_csv('temp.csv')
    s = data.groupby('fbus').p.sum()
    d = -data.groupby('tbus').p.sum()
    b = s.add(d, fill_value=0)

    x = data.set_index(['fbus', 'tbus'])
    capacities = x.to_dict()['p']
    x['costs'] = 1
    c = x.to_dict()['costs']

    buses = list(b.index)
    lines, u = multidict(capacities)
    lines = tuplelist(lines)
    S = set(b[b>0].index)
    D = set(b[b<=0].index)
    b = b.to_dict()

    w, v, y, m = solve(budget, buses, lines, u, c, b, S, D)
    if not m.status == GRB.status.OPTIMAL:
        raise RuntimeError('Gurobi did not converge, status %d' % m.status)
    for i, j in y:
        if y[i, j].x > 0:
            print('%d %d' % (i, j))
def main(budget=3):
    data = read_csv('temp.csv')
    s = data.groupby('fbus').p.sum()
    d = -data.groupby('tbus').p.sum()
    b = s.add(d, fill_value=0)

    x = data.set_index(['fbus', 'tbus'])
    capacities = x.to_dict()['p']
    x['costs'] = 1
    c = x.to_dict()['costs']

    buses = list(b.index)
    lines, u = multidict(capacities)
    lines = tuplelist(lines)
    S = set(b[b > 0].index)
    D = set(b[b <= 0].index)
    b = b.to_dict()

    w, v, y, m = solve(budget, buses, lines, u, c, b, S, D)
    if not m.status == GRB.status.OPTIMAL:
        raise RuntimeError('Gurobi did not converge, status %d' % m.status)
    for i, j in y:
        if y[i, j].x > 0:
            print('%d %d' % (i, j))
Example #14
0
#9(i)=13

# Cost to "pick" each Sub-Set
#1(S1)=32
#2(S2)=38
#3(S3)=63
#4(S4)=30
#5(S5)=49

budget = 120
nodes, reward, covered_by = gp.multidict({
    0: [13, {0}],
    1: [7, {0, 1, 2}],
    2: [15, {0, 1, 2}],
    3: [11, {2, 3}],
    4: [12, {2, 3, 4}],
    5: [14, {2, 4}],
    6: [9, {3, 4}],
    7: [17, {1, 2, 4}],
    8: [13, {1, 4}]
})

subsets, coverage, cost = gp.multidict({
    0: [{0, 1, 2}, 32],
    1: [{1, 2, 7, 8}, 38],
    2: [{1, 2, 3, 4, 5, 7}, 63],
    3: [{3, 4, 6}, 30],
    4: [{4, 5, 6, 7, 8}, 49]
})

z = [1, 0, 1, 0, 0]
Example #15
0
    def solve(self, graph: Graph, **kwargs):
        error_message = None
        returned_order = None
        is_optimal = False
        runtime = 0
        try:
            self.build_model(graph)
            if "time_limit" in kwargs:            
                self.model.setParam("TimeLimit", kwargs.pop("time_limit"))
            self.add_start_solution(graph, kwargs.pop("start_solution", None))
            self._add_callbacks(kwargs.pop("callbacks", None))
            if kwargs.pop("relax", False):
                old_edges = self.edges
                used_edges = None
                rel_model = self.model.relax()
                keys, self.edges = grb.multidict({key: rel_model.getVarByName(self.edges[key].VarName) for key in self.edges})
                rel_model.optimize(callback_rerouter)
                runtime = self.model.Runtime
                
            else:
                circle_found = True
                max_runtime = self.params["TimeLimit"]
                while(circle_found and max_runtime > 0):
                    self.model.optimize(callback_rerouter)
                    max_runtime -= self.model.Runtime
                    runtime = abs(self.params["TimeLimit"] - max_runtime)
                    try:
                        used_edges = grb.tupledict({key: self.edges[key] for key in self.edges if not math.isclose(0, self.edges[key].x, abs_tol=10**-6)})
                        circle_found = self._check_for_cycle(used_edges, self.model, lazy=False)
                        if circle_found and max_runtime > 0:
                            self.model.setParam("TimeLimit", max_runtime)
                    except AttributeError as e:
                        # Can happen if no solution was found in the time limit
                        # If not, raise error
                        if runtime < self.params["TimeLimit"]:
                            raise e
                    

            is_optimal = self.model.Status == grb.GRB.OPTIMAL
            if is_debug_env():
                local_subtours = 0
                for circle in self.found_circles:
                    verts = [key[1] for key in circle]
                    for v_i in self.v_incident_edges:
                        if self.v_incident_edges[v_i].issuperset(verts):
                            local_subtours += 1
                            break
                print("Overall subtours:", len(self.found_circles), "local subtours:", local_subtours,\
                    "in percent:", local_subtours*100/len(self.found_circles))
            
            try:
                used_edges = {key: self.edges[key] for key in self.edges if not math.isclose(0, self.edges[key].x, abs_tol=10**-6)}
                dep_graph = self._get_dep_graph(used_edges)
                order = calculate_order(dep_graph, calculate_circle_dep=True)
                returned_order = [tuple(self.abstract_graph.vertices[i]) for i in order]
            except (CircularDependencyException, AttributeError) as e:
                # If we have a circular dependency after the time limit we just didnt managed to get a feasable solution in time
                # Else something went wrong and the error should be raised
                if runtime < self.params["TimeLimit"]:
                    raise e
        except Exception as e:
            error_message = str(e)
            if is_debug_env():
                raise e
        #times = calculate_times(returned_order, self.graph)
        sol = AngularGraphSolution(self.graph,
                                    runtime,
                                    solution_type=self.solution_type,
                                    solver=self.__class__.__name__,
                                    is_optimal=is_optimal,
                                    order=returned_order,
                                    error_message=error_message)
        return sol
Example #16
0
 def _add_variables(self, abs_graph: Graph):
     edges, costs = grb.multidict(abs_graph.costs)
     self.edges = self.model.addVars(edges, vtype=grb.GRB.BINARY, name="Abs_graph_edges")
     return costs
Example #17
0
import gurobipy as gp
from gurobipy import GRB

# tested with Python 3.7.0 & Gurobi 9.1.0
# Sample data: values of independent variable x and dependent variable y
observations, x, y = gp.multidict({
    ('1'): [0,1],
    ('2'): [0.5,0.9],
    ('3'): [1,0.7],
    ('4'): [1.5,1.5],
    ('5'): [1.9,2],
    ('6'): [2.5,2.4],
    ('7'): [3,3.2],
    ('8'): [3.5,2],
    ('9'): [4,2.7],
    ('10'): [4.5,3.5],
    ('11'): [5,1],
    ('12'): [5.5,4],
    ('13'): [6,3.6],
    ('14'): [6.6,2.7],
    ('15'): [7,5.7],
    ('16'): [7.6,4.6],
    ('17'): [8.5,6],
    ('18'): [9,6.8],
    ('19'): [10,7.3]
})

model = gp.Model('CurveFitting')

# Constant term of the function f(x). This is a free continuous variable that can take positive and negative values. 
a = model.addVar(lb=-GRB.INFINITY, ub=GRB.INFINITY, vtype=GRB.CONTINUOUS, name="a")
    gp.setParam("NonConvex", 2)

    #### Initialize Data: ####
    '''
    ---- Init data for locomotives ----
    loco_types: The type of locomotive.  Corresponds to a train type
    loco_Cfix: Fixed cost of a loco. i.e. cost to purchase one loco
    loco_Ckm: Cost of loco travelling 1km
    loco_speed: Average speed of locomotive

    e.g. locomotive 'a' costs 1000 to purchase and 2 per km to run, avg speed of 30km/h
    Note: I have set the fixed cost to zero since the locos are already owned, and this does not affect daily
    operation as much.  The millions of dollars in fixed cost overshadows the cost of operating.
    '''
    loco_types, loco_Cfix, loco_Ckm, loco_speed = gp.multidict({
        'a': [1000, 2, 40],
        'b': [2000, 4, 80]
    })
    if debug:
        print("loco_types, loco_Cfix, loco_Ckm, loco_speed:")
        print(loco_types)
        print(loco_Cfix)
        print(loco_Ckm)
        print(loco_speed)
    '''
    ---- Init data for coaches/cars: ----
    car_types: The car type. Corresponds to a train type
    car_Cfix: Fixed cost of a car. i.e. cost to purchase one car
    car_Ckm: Cost of car travelling 1km
    car_cap: Capacity of car.  i.e. number of passengers it can fit
    car_min: Minimum number of this car type allowed on a train
    car_max: Maximum number of this car type allowed on a train
def compute_distance(loc1, loc2):
    # This function determines the Euclidean distance between a facility and an ABS centroid.
    loc1 = loc1[1:-1]
    loc2 = loc2[1:-1]
    loc1 = [float(x.strip()) for x in loc1.split(',')]
    loc2 = [float(x.strip()) for x in loc2.split(',')]
    dx = loc1[0] - loc2[0]
    dy = loc1[1] - loc2[1]
    return sqrt(dx * dx + dy * dy)


# In[15]:

# Create a dictionary to capture the coordinates of an ABS and the demand of COVID-19 treatment
ABS, c_coordinates, demand = gp.multidict(dictionary_demand)

# ## Setting parameters

# In[16]:

# Indices for the ABS
ABS = [*range(0, len(dictionary_demand))]
# Indices for the facilities
facilities = [
    *range(
        0,
        len(dictionary_existing_hospitals) +
        len(temporary_facilities_dictionary))
]
            {'Diamond push ups': 1,
                'bridge': 1,
                'bulgarian split squats': 1,...}
    """
    d = {}
    for key in list(multi_dict):
        d[key[0]] = time
    return d

if __name__ == "__main__":
    # Define your intensities manually
    categories, min_intensity, max_intensity = gp.multidict({
        'shoulders' : [0,GRB.INFINITY],
        'back' : [0,GRB.INFINITY],
        'breast' : [0,GRB.INFINITY],
        'biceps' : [0,GRB.INFINITY],
        'triceps' : [0,GRB.INFINITY],
        'abs' : [0,GRB.INFINITY],
        'butt' : [0.5,0.5],
        'legs' : [2,2]
    })

    # Read exercises and their intensity
    exercises_intensities = build_dict_from_csv_file("exercises.csv", "name")
    # Read exercises and their needed time
    exercises, time = gp.multidict(exercise_and_time_dict(exercises_intensities))
    # Build model
    m = gp.Model("circle_training")
    # Create trainings variables (each exercise is a decision variable)
    training = m.addVars(exercises, vtype=GRB.BINARY, name="training")
    # Objective Function
    m.setObjective(training.prod(time), GRB.MINIMIZE)
Example #21
0
#!/usr/bin/python

# Copyright 2016, Gurobi Optimization, Inc.

# Solve the classic diet model, showing how to add constraints
# to an existing model.
import gurobipy

# Nutrition guidelines, based on
# USDA Dietary Guidelines for Americans, 2005
# http://www.health.gov/DietaryGuidelines/dga2005/

categories, minNutrition, maxNutrition = gurobipy.multidict({
  'calories': [1800, 2200],
  'protein':  [91, gurobipy.GRB.INFINITY],
  'fat':      [0, 65],
  'sodium':   [0, 1779] })

foods, cost = gurobipy.multidict({
  'hamburger': 2.49,
  'chicken':   2.89,
  'hot dog':   1.50,
  'fries':     1.89,
  'macaroni':  2.09,
  'pizza':     1.99,
  'salad':     2.49,
  'milk':      0.89,
  'ice cream': 1.59 })

# Nutrition values for the foods
import numpy as np
import scipy.sparse as sp
import gurobipy as gp
from gurobipy import GRB
import E_Bus_Output as eop

L_test = list(range(1, 13))
Trip, Trip_time, Duration_time = gp.multidict({
    "Trip_start": [0, 0],
    "Trip_1": [1, 2],
    "Trip_2": [2, 2],
    "Trip_3": [3, 2],  #"Trip_4" : [4],"Trip_5" : [5],"Trip_6" : [6],
    #"Trip_7" : [7],"Trip_8" : [8],"Trip_9" : [9],"Trip_10" : [10],"Trip_11" : [11],"Trip_12" : [12],
    "Trip_end": [100, 100]
})
b = [0 for _ in range(len(Trip))]
b[0] = 1
b[-1] = -1

E_Bus, SOC_MIN, SOC_MAX, Battery_Capacity, Energy_per_Trip_Win, Energy_per_Trip_Sum = gp.multidict(
    {
        "JL_1": [30, 100, 160, 47, 65.8],
        "JL_2": [30, 100, 160, 47, 65.8],
        "JL_3": [30, 100, 160, 47, 65.8],
        #"JL_4" : [30,100,160,47,65.8],
        #"JL_5" : [30,100,160,47,65.8],
        #"JL_6" : [30,100,160,47,65.8],
        #"JL_7" : [30,100,160,47,65.8],
        #"JL_8" : [30,100,160,47,65.8],
        #"JL_9" : [30,100,160,47,65.8],
        #"JL_10" : [30,100,160,47,65.8],
Example #23
0
        full_F = tuplelist([])
        for i in range(num_of_task):
            task_i = input_content[3 + num_of_arc + i].split()
            start_node = task_i[0]
            end_node = task_i[1]
            task_period = float(task_i[2])
            task_deadline = float(task_i[3])
            task_length = int(task_i[4])
            full_S[str(i)] = [task_period, task_deadline, task_length]
            route = nx.shortest_path(topology_graph,
                                     source=start_node,
                                     target=end_node)
            for t in range(len(route) - 1):
                full_F.append((route[t], route[t + 1], str(i)))

E, R, LE = multidict(E)
old_κ = tupledict({})
for va, vb in E:
    old_κ[va, vb] = -1
old_φ = tupledict({})
old_ρ = tupledict({})
old_F = tuplelist([])
old_T = tupledict({})
old_e2e = tupledict({})
old_f = tuplelist([])

batch = 0
while len(full_S) > batch * size_of_batch:
    #有序存储帧实例及属性
    S = dict(
        list(full_S.items())[size_of_batch * batch:size_of_batch *
INSTANCE OF PROBLEM USED FOR THE CODE:
    6 students and 3 courses.
    each student has to take 2 courses and the class size for each course is 4
    each students give a preference of 2 courses
    our program allocates courses to students satisfying student preference and batch sizes  
'''

import gurobipy as gp
from gurobipy import *

model = Model("student_to_courses")

students, stud_cap = gp.multidict({
    'stud1': 2,
    'stud2': 2,
    'stud3': 2,
    'stud4': 2,
    'stud5': 2,
    'stud6': 2
})

courses, course_cap = gp.multidict({'crs1': 4, 'crs2': 4, 'crs3': 4})

courses, add_course_cap = gp.multidict({
    'crs1': 2,
    'crs2': 2,
    'crs3': 2
})  #for part 'c'

courses, add_course_cost = gp.multidict({
    'crs1': 10,
    'crs2': 10,
# first, we minimize the linear sum of the slacks. Then, we constrain
# the sum of the slacks, and we minimize a quadratic objective that
# tries to balance the workload among the workers.

import gurobipy as gp
from gurobipy import GRB

# Number of workers required for each shift
shifts, shiftRequirements = gp.multidict({
    "Mon1": 3,
    "Tue2": 2,
    "Wed3": 4,
    "Thu4": 4,
    "Fri5": 5,
    "Sat6": 6,
    "Sun7": 5,
    "Mon8": 2,
    "Tue9": 2,
    "Wed10": 3,
    "Thu11": 4,
    "Fri12": 6,
    "Sat13": 7,
    "Sun14": 5,
})

# Amount each worker is paid to work one shift
workers, pay = gp.multidict({
    "Amy": 10,
    "Bob": 12,
    "Cathy": 10,
    "Dan": 8,
    "Ed": 8,
Example #26
0
import gurobipy as gp
from collections import defaultdict

# define index sets and data coefficients
warehouses, capacity = gp.multidict(
  {'A': 6,
   'B': 5,
   'C': 4,
   'D': 6 })

centers, demand = gp.multidict(
  {'X': 3,
   'Y': 3,
   'Z': 8 })

cost = {
  ('A', 'X'): 8, ('A', 'Y'): 6, ('A', 'Z'): 10,
  ('B', 'X'): 3, ('B', 'Y'): 1, ('B', 'Z'): 8,
  ('C', 'X'): 1, ('C', 'Y'): 8, ('C', 'Z'): 5,
  ('D', 'X'): 6, ('D', 'Y'): 2, ('D', 'Z'): 6 }

# create empty model
m = gp.Model()

ship = defaultdict(dict)
# add decision variables
for w in warehouses:
    for c in centers:
        ship[w][c] = m.addVar(vtype=gp.GRB.INTEGER)

# process pending changes
Example #27
0
# (diet.db) can be recreated using the included SQL script (diet.sql).
#
# Note that this example reads an external data file (..\data\diet.db).
# As a result, it must be run from the Gurobi examples/python directory.

import os
import sqlite3
import dietmodel
import gurobipy as gp

con = sqlite3.connect(os.path.join('..', 'data', 'diet.db'))
cur = con.cursor()

cur.execute('select category,minnutrition,maxnutrition from categories')
result = cur.fetchall()
categories, minNutrition, maxNutrition = gp.multidict(
    (cat, [minv, maxv]) for cat, minv, maxv in result)

cur.execute('select food,cost from foods')
result = cur.fetchall()
foods, cost = gp.multidict(result)

cur.execute('select food,category,value from nutrition')
result = cur.fetchall()
nutritionValues = dict(((f, c), v) for f, c, v in result)

con.close()

dietmodel.solve(categories, minNutrition, maxNutrition, foods, cost,
                nutritionValues)
#
# Flows on the transportation network must respect arc capacity constraints
# ('capacity[i,j]'). The objective is to minimize the sum of the arc
# transportation costs ('cost[i,j]').

import gurobipy as gp
from gurobipy import GRB

# Base data
commodities = ['Pencils', 'Pens']
nodes = ['Detroit', 'Denver', 'Boston', 'New York', 'Seattle']

arcs, capacity = gp.multidict({
    ('Detroit', 'Boston'): 100,
    ('Detroit', 'New York'): 80,
    ('Detroit', 'Seattle'): 120,
    ('Denver', 'Boston'): 120,
    ('Denver', 'New York'): 120,
    ('Denver', 'Seattle'): 120
})

# Cost for triplets commodity-source-destination
cost = {
    ('Pencils', 'Detroit', 'Boston'): 10,
    ('Pencils', 'Detroit', 'New York'): 20,
    ('Pencils', 'Detroit', 'Seattle'): 60,
    ('Pencils', 'Denver', 'Boston'): 40,
    ('Pencils', 'Denver', 'New York'): 40,
    ('Pencils', 'Denver', 'Seattle'): 30,
    ('Pens', 'Detroit', 'Boston'): 20,
    ('Pens', 'Detroit', 'New York'): 20,
    ('Pens', 'Detroit', 'Seattle'): 80,
Example #29
0
        
oldκ = tupledict({})
for va,vb in E:
    oldκ[va,vb] = -1
oldφ = tupledict({})
oldρ = tupledict({})
oldF = tuplelist([])
oldT = tupledict({})
oldL = tupledict({})
oldf = tuplelist([])
    
while len(fullS) > tur*batch: 
    
    #有序存储帧实例及属性
    S = dict(list(fullS.items())[batch*tur:batch*(tur+1)])
    S,e2e,size = multidict(S)
    F = tuplelist([])
    for s in S:
        F += fullF.select('*','*',s)
    f = {}
    for k in F:
        i = 0
        sizek = size[k[2]]
        while sizek > 15:
            f[(k[0],k[1],k[2],i)] = [e2e[k[2]],15.0]
            sizek -= 15
            i += 1
        f[(k[0],k[1],k[2],i)] = [e2e[k[2]],sizek]
    f,T,L =  multidict(f)
     
    md = Model('cyber')
Example #30
0
def min_congestion(G, D, hard_cap=False, verbose=False):
    '''
    Compute the multi-commodity flow which minimizes maximum link
    utilization, through linear programming.
    input parameters:
        G is a networkx graph with nodes and edges. Edges must have a
        'capacity'. Edge capacity denotes the maximum possible traffic
        utilization for an edge. It can be set as a hard or soft optimization
        constraint through the 'hard_cap' parameter. Edges may additionally
        have a 'cost' attribute used for weighting the maximum link utilization.

        D is a |V| x |V| demand matrix, represented as a 2D numpy array. |V|
        here denotes the number of vertices in the graph G.

        hard_cap is a boolean flag which determines whether edge capacities are
        treated as hard or soft optimization constraints.

        verbose is a boolean flag enabling/disabling optimizer printing.

    return values:
        f_sol is a routing policy, represented as a numpy array of size
        |V| x |V| x |E| such that f_sol[s, t, i, j] yields the amount of traffic
        from source s to destination t that goes through edge (i, j).

        l_sol is numpy array of size |E| such that l[i, j] represents the total
        amount of traffic that flows through edge (i, j) under the given flow.

        m_cong is the maximal congestion for any link weighted by cost.
        ie max_{(i, j) in E} cost[i, j] * l[i, j] / cap[i, j].
    '''
    np.fill_diagonal(D, 0)
    nV = G.number_of_nodes()
    nE = G.number_of_edges()

    m = gb.Model('netflow')

    verboseprint = print

    if not verbose:
        verboseprint = lambda *a: None
        m.setParam('OutputFlag', False)
        m.setParam('LogToConsole', False)

    V = np.array([i for i in G.nodes()])

    cost = {}
    for k, e in enumerate(G.edges()):
        if 'cost' in G[e[0]][e[1]]:
            cost[e] = G[e[0]][e[1]]['cost']
        else:
            # If costs aren't specified, make uniform.
            cost[e] = 1.0

    cap = {}
    for k, e in enumerate(G.edges()):
        cap[e] = G[e[0]][e[1]]['capacity']

    arcs, capacity = gb.multidict(cap)

    # Create variables
    f = m.addVars(V, V, arcs, obj=cost, name='flow')
    l = m.addVars(arcs, lb=0.0, name='tot_traf_across_link')

    # Link utilization is sum of flows.
    m.addConstrs(
        (l[i, j] == f.sum('*', '*', i, j) for i, j in arcs),
        'l_sum_traf',
    )

    # Arc capacity constraints
    if hard_cap:
        verboseprint('Capacity constraints set as hard constraints.')
        m.addConstrs(
            (l[i, j] <= capacity[i, j] for i, j in arcs),
            'traf_below_cap',
        )

    # Flow conservation constraints
    for s, t, u in utils.cartesian_product(V, V, V):
        d = D[int(s), int(t)]
        if u == s:
            m.addConstr(
                f.sum(s, t, u, '*') - f.sum(s, t, '*', u) == d, 'conserv')
        elif u == t:
            m.addConstr(
                f.sum(s, t, u, '*') - f.sum(s, t, '*', u) == -d, 'conserv')
        else:
            m.addConstr(
                f.sum(s, t, u, '*') - f.sum(s, t, '*', u) == 0, 'conserv')

    # Set objective to max-link utilization (congestion)
    max_cong = m.addVar(name='congestion')
    m.addConstrs(
        ((cost[i, j] * l[i, j]) / capacity[i, j] <= max_cong for i, j in arcs))
    m.setObjective(max_cong, gb.GRB.MINIMIZE)

    # Compute optimal solution
    m.optimize()

    # Print solution
    if m.status == gb.GRB.Status.OPTIMAL:
        f_sol = m.getAttr('x', f)
        l_sol = m.getAttr('x', l)
        m_cong = float(max_cong.x)

        verboseprint('\nOptimal traffic flows.')
        verboseprint('f_{i -> j}(s, t) denotes amount of traffic from source'
                     ' s to destination t that goes through link (i, j) in E.')

        for s, t in utils.cartesian_product(V, V):
            for i, j in arcs:
                p = f_sol[s, t, i, j]
                if p > 0:
                    verboseprint('f_{%s -> %s}(%s, %s): %g bytes.' %
                                 (i, j, s, t, p))

        verboseprint('\nTotal traffic through link.')
        verboseprint('l(i, j) denotes the total amount of traffic that passes'
                     ' through edge (i, j).')

        for i, j in arcs:
            p = l_sol[i, j]
            if p > 0:
                verboseprint('%s -> %s: %g bytes.' % (i, j, p))

        verboseprint('\nMaximum weighted link utilization (or congestion):',
                     format(m_cong, '.4f'))

    else:
        print(D, m.status)
        np.savetxt("demand.txt", D)
        w = np.zeros(nE)
        cap = np.zeros(nE)
        cost = np.zeros(nE)
        e0 = np.zeros(nE)
        e1 = np.zeros(nE)
        for k, e in enumerate(G.edges()):
            w[k] = G[e[0]][e[1]]['weight']
            cap[k] = G[e[0]][e[1]]['capacity']
            cost[k] = G[e[0]][e[1]]['cost']
            e0[k] = e[0]
            e1[k] = e[1]
            print(e, G[e[0]][e[1]]['cost'], G[e[0]][e[1]]['capacity'],
                  G[e[0]][e[1]]['weight'])

        np.savetxt("w.txt", w)
        np.savetxt("capacity.txt", cap)
        np.savetxt("cost.txt", cost)
        np.savetxt("e0.txt", e0)
        np.savetxt("e1.txt", e1)
        verboseprint('\nERROR: Flow Optimization Failed!', file=sys.stderr)
        return None, None, None

    return f_sol, l_sol, m_cong
import gurobipy as gp

## Time Slot L
L_test = list(range(1, 26))

## Time Table & Trip
# Trip_start and Trip_end are virtual vertex in the graph
Trip, Trip_time, Duration_time = gp.multidict({
    "Trip_start": [0, 0],
    "Trip_1": [1, 3],
    "Trip_2": [3, 3],
    "Trip_3": [5, 3],
    "Trip_4": [7, 3],
    "Trip_5": [9, 3],
    "Trip_6": [11, 3],
    "Trip_7": [13, 3],
    "Trip_8": [15, 3],
    "Trip_9": [17, 3],
    "Trip_10": [19, 3],
    "Trip_11": [21, 3],
    "Trip_12": [23, 3],
    "Trip_end": [26, 0]
})
# Constant b for the constraint
b = [0 for _ in range(len(Trip))]
b[0] = 1
b[-1] = -1

## Bus Fleet K
E_Bus, E_Bus_ID, SOC_MIN, SOC_MAX, Battery_Capacity, Energy_per_Trip_Win, Energy_per_Trip_Sum = gp.multidict(
    {
Example #32
0
combustible, PCI, ratio_sec, cout, prix_vente_elect, emission_GES, dispo_avant2025, dispo_apres2025 = multidict(
    {  #PCI en MWh/t, cout en euros/t, prix_vente_elect en euros/MWh, emission GES en tCO2/t
        'charbon': [25000 / 3600, 1, 30, 43, 3, 1E24, 1E24],
        'torrefie': [
            18000 / 3600, 1, 190, 115,
            (GES_torrefie_prod + GES_torrefie_transport_mar * 7000 +
             GES_torrefie_transport_terr * 250), 700E3, 0
        ],
        'NS_vert': [(18000 - 21000 * 0.4) / 3600, 1, 0, 115,
                    (GES_vert_prod + GES_vert_transport * 80) * 0, 0, 0],
        'AS_vert': [(18000 - 21000 * 0.05) / 3600, 0.65, 0, 115,
                    (GES_vert_prod + GES_vert_transport * 80) * 0, 313E3,
                    313E3],
        'recycle': [(18000 - 21000 * 0.05) / 3600, 1, 0, 115,
                    (GES_vert_prod + GES_vert_transport * 80) * 0, 313E3,
                    313E3],
        'AS_frais_Aigoual': [(18000 - 21000 * 0.05) / 3600, 0.85, 128, 115,
                             (GES_frais_prod + GES_frais_transport * 230) * 0,
                             18E3, 21E3],
        'AS_frais_Cevennes30':
        [(18000 - 21000 * 0.05) / 3600, 0.85, 120, 115,
         (GES_frais_prod + GES_frais_transport * 210) * 0, 21E3, 43E3],
        'AS_frais_Cevennes48':
        [(18000 - 21000 * 0.05) / 3600, 0.85, 128, 115,
         (GES_frais_prod + GES_frais_transport * 230) * 0, 12E3, 75E3],
        'AS_frais_Cevennes07':
        [(18000 - 21000 * 0.05) / 3600, 0.85, 116, 115,
         (GES_frais_prod + GES_frais_transport * 200) * 0, 8E3, 56E3],
        'AS_frais_BoucheDuRhone':
        [(18000 - 21000 * 0.05) / 3600, 0.85, 44, 115,
         (GES_frais_prod + GES_frais_transport * 20) * 0, 47E3, 51E3],
        'AS_frais_Vaucluse': [(18000 - 21000 * 0.05) / 3600, 0.85, 79, 115,
                              (GES_frais_prod + GES_frais_transport * 100) * 0,
                              24E3, 28E3],
        'AS_frais_Var': [(18000 - 21000 * 0.05) / 3600, 0.85, 60, 115,
                         (GES_frais_prod + GES_frais_transport * 60) * 0, 27E3,
                         27E3],
        'AS_frais_HauteAples': [
            (18000 - 21000 * 0.05) / 3600, 0.85, 100, 115,
            (GES_frais_prod + GES_frais_transport * 160) * 0, 15E3, 21E3
        ],
        'AS_frais_AplesHteProvence': [
            (18000 - 21000 * 0.05) / 3600, 0.85, 88, 115,
            (GES_frais_prod + GES_frais_transport * 130) * 0, 26E3, 37E3
        ],
        'AS_frais_Autres1': [(18000 - 21000 * 0.05) / 3600, 0.85, 116, 115,
                             (GES_frais_prod + GES_frais_transport * 200) * 0,
                             27E3, 27E3],
        'AS_frais_Autres2': [(18000 - 21000 * 0.05) / 3600, 0.85, 156, 115,
                             (GES_frais_prod + GES_frais_transport * 300) * 0,
                             56E3, 56E3],
        'AS_frais_Autres3': [(18000 - 21000 * 0.05) / 3600, 0.85, 196, 115,
                             (GES_frais_prod + GES_frais_transport * 400) * 0,
                             56E3, 56E3],
        'NS_frais_Aigoual': [(18000 - 21000 * 0.2) / 3600, 1, 128, 115,
                             (GES_frais_prod + GES_frais_transport * 230) * 0,
                             0, 0],
        'NS_frais_Cevennes30': [
            (18000 - 21000 * 0.2) / 3600, 1, 120, 115,
            (GES_frais_prod + GES_frais_transport * 210) * 0, 0, 0
        ],
        'NS_frais_Cevennes48': [
            (18000 - 21000 * 0.2) / 3600, 1, 128, 115,
            (GES_frais_prod + GES_frais_transport * 230) * 0, 0, 0
        ],
        'NS_frais_Cevennes07': [
            (18000 - 21000 * 0.2) / 3600, 1, 116, 115,
            (GES_frais_prod + GES_frais_transport * 200) * 0, 0, 0
        ],
        'NS_frais_BoucheDuRhone': [
            (18000 - 21000 * 0.2) / 3600, 1, 44, 115,
            (GES_frais_prod + GES_frais_transport * 20) * 0, 0, 0
        ],
        'NS_frais_Vaucluse': [(18000 - 21000 * 0.2) / 3600, 1, 79, 115,
                              (GES_frais_prod + GES_frais_transport * 100) * 0,
                              0, 0],
        'NS_frais_Var': [(18000 - 21000 * 0.2) / 3600, 1, 60, 115,
                         (GES_frais_prod + GES_frais_transport * 60) * 0, 0,
                         0],
        'NS_frais_HauteAples': [
            (18000 - 21000 * 0.2) / 3600, 1, 100, 115,
            (GES_frais_prod + GES_frais_transport * 160) * 0, 0, 0
        ],
        'NS_frais_AplesHteProvence': [
            (18000 - 21000 * 0.2) / 3600, 1, 88, 115,
            (GES_frais_prod + GES_frais_transport * 130) * 0, 0, 0
        ],
        'NS_frais_Autres1': [(18000 - 21000 * 0.2) / 3600, 1, 116, 115,
                             (GES_frais_prod + GES_frais_transport * 200) * 0,
                             0, 0],
        'NS_frais_Autres2': [(18000 - 21000 * 0.2) / 3600, 1, 156, 115,
                             (GES_frais_prod + GES_frais_transport * 300) * 0,
                             0, 0],
        'NS_frais_Autres3': [(18000 - 21000 * 0.2) / 3600, 1, 196, 115,
                             (GES_frais_prod + GES_frais_transport * 400) * 0,
                             0, 0]
    })
Example #33
0
"""
Created on Sun Jun 28 09:37:14 2020

@author: kevin
"""
import gurobipy as gp
from gurobipy import GRB
import sys

# Number of TimeSlots required for each Course
Courses, CourseRequirements = gp.multidict({
    "C1": 2,
    "C2": 2,
    "C3": 2,
    "C4": 2,
    "C5": 2,
    "C6": 2,
    "C7": 2,
    "C8": 2,
    "C9": 2,
    "C10": 2,
})

# Amount each worker is paid to work one Course
TimeSlots, weight = gp.multidict({
    "T11": 1,
    "T12": 1,
    "T13": 1,
    "T14": 1,
    "T15": 1,
    "T21": 1,
    "T22": 1,
# Copyright 2019, Gurobi Optimization, LLC

# Solve the classic diet model, showing how to add constraints
# to an existing model.

import gurobipy as gp
from gurobipy import GRB

# Nutrition guidelines, based on
# USDA Dietary Guidelines for Americans, 2005
# http://www.health.gov/DietaryGuidelines/dga2005/

categories, minNutrition, maxNutrition = gp.multidict({
    'calories': [1800, 2200],
    'protein': [91, GRB.INFINITY],
    'fat': [0, 65],
    'sodium': [0, 1779]
})

foods, cost = gp.multidict({
    'hamburger': 2.49,
    'chicken': 2.89,
    'hot dog': 1.50,
    'fries': 1.89,
    'macaroni': 2.09,
    'pizza': 1.99,
    'salad': 2.49,
    'milk': 0.89,
    'ice cream': 1.59
})