Beispiel #1
0
    def _initialize_model(self):

        problem = Model()
        problem.setParam('OutputFlag', False)

        # edges from source to reviewers, capacity controls maximum reviewer load
        self._source_vars = problem.addVars(self.numrev, vtype=GRB.CONTINUOUS, lb=0.0,
                                            ub=self.ability, name='reviewers')

        # edges from papers to sink, capacity controls a number of reviewers per paper
        self._sink_vars = problem.addVars(self.numpapers, vtype=GRB.CONTINUOUS, lb=0.0,
                                          ub=self.demand, name='papers')

        # edges between reviewers and papers. Initially capacities are set to 0 (no edge is added in the network)
        self._mix_vars = problem.addVars(self.numrev, self.numpapers, vtype=GRB.CONTINUOUS,
                                         lb=0.0, ub=0.0, name='assignment')
        problem.update()

        # flow balance equations for reviewers' nodes
        self._balance_reviewers = problem.addConstrs((self._source_vars[i] == self._mix_vars.sum(i, '*')
                                                      for i in range(self.numrev)))

        # flow balance equations for papers' nodes
        self._balance_papers = problem.addConstrs((self._sink_vars[i] == self._mix_vars.sum('*', i)
                                                   for i in range(self.numpapers)))
        problem.update()

        self._problem = problem
  def _create_model(self, city_ids, map_points):
    depot_id = city_ids[0]
    city_num = len(city_ids)
    ## prepare the index for decision variables
    # index of network flow
    cities = tuple(city_ids)
    # index of MTZ constraint
    MTZ_u = tuple(city_ids[1:])
    # connecting arcs of the cities
    cityArcs = [(i,j) for i in cities for j in cities if i != j]
    
    ## parameters model (dictionary)
    # 1. distance map
    distances_map = self.calculate_distances(city_ids, map_points)

    ## create model
    m = Model('TSP')
    ## create decision variables
    # 1. choice of arcs between cities
    x = m.addVars(cityArcs, vtype=GRB.BINARY, name='route')    
    # 2. for expression of non-subtour: [2,N]
    u = m.addVars(MTZ_u, name='MTZ_u')
    
    ## create objective: minimum route distance
    m.setObjective(quicksum([x[i,j]*distances_map[(i,j)] for (i,j) in cityArcs]), GRB.MINIMIZE) # TOTRY
    ## create constraints
    # 1. MTZ formulation
    m.addConstrs((u[i]-u[j]+city_num*x[i,j] <= city_num-1 for (i,j) in cityArcs if (i>depot_id and j>depot_id)),'MTZ formulation')
    m.addConstrs((u[i]>=0 and u[i]<=city_num-1 for i in MTZ_u), 'MTZ compensation')
    # 2. Network flow
    m.addConstrs((quicksum([x[i,j] for j in cities if i!=j])==1 for i in cities), 'Network flow1')
    m.addConstrs((quicksum([x[i,j] for i in cities if i!=j])==1 for j in cities), 'Network flow2')

    return m, x
Beispiel #3
0
def generate_row_model(row_matrix, b, v, c):
    """
    rows_matrix: The matrix, represented as a list of rows
    b: List of variables in b
    v: The target vector
    c: The weights of each column
    """

    # Initializes a model
    mdl = Model('persistenthomologylocalization')

    # Add matrix variables
    x = mdl.addVars(list(b), vtype=GRB.BINARY)

    # Add the dummy variable needed to do arithmetics mod 2
    y = mdl.addVars(list(range(len(row_matrix))), vtype=GRB.INTEGER)

    # Set model to minimization
    mdl.modelSense = GRB.MINIMIZE

    # Set objective function to minimize
    mdl.setObjective(quicksum(x[j] * c[j] for j in b))

    # Set the constrains
    for i in list(range(len(row_matrix))):
        mdl.addConstr(quicksum(x[j] for j in row_matrix[i]) + v[i] == y[i] * 2)
    return mdl, x, y
Beispiel #4
0
def TWTgurobi():
  jobs = tuple(range(1,5))
  jobPairs = [(i,j) for i in jobs for j in jobs if i < j]
  # job_id as keys and weight as content
  weight = dict(zip(jobs, (4,3,4,5)))
  duration = dict(zip(jobs, (12,8,15,9)))
  deadline = dict(zip(jobs, (16,26,25,27)))
  # Big M for modeling
  M = sum(duration.values())

  try:
    m = Model('TWTexample')
    x = m.addVars(jobPairs, vtype=GRB.BINARY, name='x')
    startTime = m.addVars(jobs, name='startTime')
    tardiness = m.addVars(jobs, name='tardiness')
    m.setObjective(quicksum([weight[j]*tardiness[j] for j in jobs]), GRB.MINIMIZE)
    m.addConstrs((startTime[j] >= startTime[i]+duration[i]-M*(1-x[i,j]) for(i,j) in jobPairs), 'NoOverplap1')
    m.addConstrs((startTime[i] >= startTime[j]+duration[j]-M*x[i,j] for(i,j) in jobPairs), 'NoOverplap2')    
    m.addConstrs((tardiness[j] >= startTime[j]+duration[j]-deadline[j] for j in jobs), 'Deadline')
    m.optimize()
    if m.status == GRB.Status.INF_OR_UNBD:
      m.setParam(GRB.Param.DualReductions, 0)
      m.optimize()
    if m.status == GRB.Status.OPTIMAL:
      for v in m.getVars():
        print('%s:\t%g' %(v.varName, v.x))
      print('Objective:\t%g' % m.objVal)
    else:
      statstr = StatusDict[m.status]
      print('Optimization was stopped with status %s' %statstr)
  except GurobiError as e:
    print('Error code '+str(e.errno)+': '+str(e))
Beispiel #5
0
def max_return(r, risk_threshold, cvar_alpha=0.95):

    r_bar = np.mean(r, axis=0)
    cov = np.cov(r, rowvar=False)
    n = len(r)
    k = len(r[0])
    m = Model('opt_profolio')
    m.params.OutputFlag = 0
    m.params.NumericFocus = 3
    x = m.addVars(k, lb=0, ub=1, vtype=GRB.CONTINUOUS, name='x')
    z = m.addVars(n, lb=0, vtype=GRB.CONTINUOUS, name='z')
    eta = m.addVar(lb=-GRB.INFINITY, vtype=GRB.CONTINUOUS, name='eta')
    m.update()

    #Portfolio contraint
    m.addConstr((x.sum() == 1), 'portfolio_ctr')
    #Risk constraint
    m.addConstr(
        (eta + (1.0 / (n * (1 - cvar_alpha))) * z.sum() <= risk_threshold),
        'cvar_ctr')
    #CVaR linearlization
    m.addConstrs((z[i] >= quicksum(-r[i, j] * x[j] for j in range(k)) - eta
                  for i in range(n)), 'cvar_linear')

    m.setObjective(quicksum(r_bar[j] * x[j] for j in range(k)), GRB.MAXIMIZE)
    m.update()

    m.optimize()
    x_sol = np.array([x[j].X for j in range(k)])
    p_mean = r_bar.dot(x_sol)
    p_var = x_sol.dot(cov.dot(x_sol))
    cvar_loss = (eta + (1.0 / (n * (1 - cvar_alpha))) * z.sum()).getValue()
    #print(m.status, eta.X, (-1+(1+eta.X)**365), cvar_loss , (-1+(1+cvar_loss)**365))
    return x_sol, p_mean, p_var
Beispiel #6
0
def solve():
    model = Model("Enigma Riddle")
    letters = {"E", "N", "I", "G", "M", "A"}
    digits = range(1, 10)
    x = model.addVars(letters, digits, vtype=GRB.BINARY)
    y = model.addVars(letters, vtype=GRB.INTEGER)
    # Stay in digit range
    for i in letters:
        model.addRange(y[i], 1, 9, f"digitRange{i}")
    # Final value for first word
    b = model.addVar(vtype=GRB.INTEGER)
    first_word = "ENIGMA"
    second_word = "IGMAEN"

    # Constraint for the enigma-igmaen numbers
    model.addConstr(quicksum(10 ** (len(first_word) - 1 - i) * y[first_word[i]] for i in range(len(first_word))) == b)
    model.addConstr(
        quicksum(10 ** (len(second_word) - 1 - i) * y[second_word[i]] for i in range(len(second_word))) == b * 1.2)

    # Conflict constraint
    model.addConstrs(x[i_1, j] + x[i_2, j] <= 1 for i_1 in letters for i_2 in letters for j in digits if i_1 != i_2)

    # Linking constraint
    model.addConstrs(j * x[i, j] <= y[i] for i in letters for j in digits)

    # Exactly one digit has to be packed
    model.addConstrs(quicksum(x[i, j] for j in digits) == 1 for i in letters)

    model.optimize()
    return model
Beispiel #7
0
def rocket():
    from gurobipy import Model, GRB
    # Set up data
    Mass = [
        70, 90, 100, 110, 120, 130, 150, 180, 210, 220, 250, 280, 340, 350, 400
    ]
    P = range(len(Mass))

    # A, B, C, D
    Sections = ["A", "B", "C", "D"]
    S = range(len(Sections))

    m = Model('Rocket Payload')
    X = m.addVars(P, S, vtype=GRB.BINARY, name='X')
    Y = m.addVars(P, S, name='Y', obj=1)

    m.addConstrs(Y[p, s] == X[p, s] * Mass[p] for p, s in X.keys())

    m.addConstrs(Y.sum('*', s) <= 1000 for s in S)
    m.addConstrs(X.sum('*', s) >= 3 for s in S)

    m.addConstr(Y.sum('*', 0) == Y.sum('*', 3))
    m.addConstr(Y.sum('*', 1) == Y.sum('*', 2))

    m.setAttr(GRB.Attr.ModelSense, GRB.MAXIMIZE)
    m.optimize()
 def stage_prob_builder(t):
     model = Model('CapExp%i' % t)  # Create a model
     x = model.addVars(data.I, vtype=GRB.CONTINUOUS, lb=0, ub=data.b, obj=1, name='x')
     x0 = model.addVars(data.I, vtype=GRB.CONTINUOUS, lb=0, ub=data.b, obj=0, name='x0')
     d = model.addVars(data.J, vtype=GRB.CONTINUOUS, lb=0, ub=0, obj=0, name='d')
     model.update()
     if t == 0:
         # y = model.addVars(data.I, lb=0, ub=1, obj=5, vtype=GRB.BINARY, name='y')
         # model.addConstrs((x[i] <= data.b * y[i] for i in data.I), 'logic_open')
         model.addConstr(sum(x[i] for i in data.I), GRB.LESS_EQUAL, data.b, 'globalCap')
         model.update()
     else:
         y = model.addVars(data.I, data.J, lb=0, obj=data.c, vtype=GRB.CONTINUOUS, name='y')
         s = model.addVars(data.J, lb=0, obj=data.rho, vtype=GRB.CONTINUOUS, name='s')
         model.update()
         '''Capacity constraints'''
         model.addConstrs((sum(y[i, j] for j in data.J) <= x0[i] for i in data.I), 'CapCtr')
         '''Recourse constraint, subcontracting '''
         model.addConstrs((sum(y[i, j] for i in data.I) + s[j] >= d[j] for j in data.J), 'RecCtr')
         model.update()
     
     in_states = [var.VarName for var in x0.values()]
     out_states = [var.VarName for var in x.values()]
     rhs_vars = [var.VarName for var in d.values()]
     return model, in_states, out_states, rhs_vars
Beispiel #9
0
def polytopic_trajectory_given_modes(x0,list_of_cells,goal,eps=0,order=1):
    """
    Description: 
        Polytopic Trajectory Optimization with the ordered list of polytopes given
        This is a convex program as mode sequence is already given
        list_of_cells: each cell has the following attributes: A,B,c, and polytope(H,h)
    """
    
    model=Model("Fixed Mode Polytopic Trajectory")
    T=len(list_of_cells)
    n,m=list_of_cells[0].B.shape
    q=int(order*n)
    x=model.addVars(range(T+1),range(n),lb=-GRB.INFINITY,ub=GRB.INFINITY,name="x")
    u=model.addVars(range(T),range(m),lb=-GRB.INFINITY,ub=GRB.INFINITY,name="u")
    G=model.addVars(range(T+1),range(n),range(q),lb=-GRB.INFINITY,ub=GRB.INFINITY,name="G")
    theta=model.addVars(range(T),range(m),range(q),lb=-GRB.INFINITY,ub=GRB.INFINITY,name="theta")
    model.update()
    
    for j in range(n):
        model.addConstr(x[0,j]<=x0[j,0]+eps)
        model.addConstr(x[0,j]>=x0[j,0]-eps)

    for t in range(T):
        print "adding constraints of t",t
        cell=list_of_cells[t]
        A,B,c,p=cell.A,cell.B,cell.c,cell.p
        for j in range(n):
            expr_x=LinExpr([(A[j,k],x[t,k]) for k in range(n)])
            expr_u=LinExpr([(B[j,k],u[t,k]) for k in range(m)])
            model.addConstr(x[t+1,j]==expr_x+expr_u+c[j,0])
        for i in range(n):
            for j in range(q):
                expr_x=LinExpr([(A[i,k],G[t,k,j]) for k in range(n)])
                expr_u=LinExpr([(B[i,k],theta[t,k,j]) for k in range(m)])
                model.addConstr(G[t+1,i,j]==expr_x+expr_u)
        x_t=np.array([x[t,j] for j in range(n)]).reshape(n,1)
        u_t=np.array([u[t,j] for j in range(m)]).reshape(m,1)
        G_t=np.array([G[t,i,j] for i in range(n) for j in range(q)]).reshape(n,q)
        theta_t=np.array([theta[t,i,j] for i in range(m) for j in range(q)]).reshape(m,q)
        GT=sp.linalg.block_diag(G_t,theta_t)
        xu=np.vstack((x_t,u_t))
        subset_LP(model,xu,GT,Ball(2*q),p)


    x_T=np.array([x[T,j] for j in range(n)]).reshape(n,1)
    G_T=np.array([G[T,i,j] for i in range(n) for j in range(q)]).reshape(n,q)
    z=zonotope(x_T,G_T)
    subset_zonotopes(model,z,goal)
    J=LinExpr([(1/(t+1.0),G[t,i,i]) for t in range(T+1) for i in range(n)])
    model.setObjective(J)
    model.write("sadra.lp")
    model.setParam('TimeLimit', 150)
    model.optimize()
    x_num,G_num={},{}
    for t in range(T+1):
        x_num[t]=np.array([[x[t,j].X] for j in range(n)]).reshape(n,1)
        G_num[t]=np.array([[G[t,i,j].X] for i in range(n) for j in range(q)]).reshape(n,q)
    return (x_num,G_num)
Beispiel #10
0
class mip_model(object):
    def __init__(self, samples, delta=1.0):
        self.n_nodes = samples.n_nodes
        self.n_samples = samples.n_samples
        self.delta = delta

        self.B = samples.B
        self.T = samples.T
        self.F = samples.F

        self.model = Model('DPSL')
        self.create_model()

    def create_model(self):
        self.U = self.model.addVars(self.n_nodes,
                                    self.n_samples,
                               name='U', lb=0, ub=1,
                               vtype=GRB.CONTINUOUS)
        self.M = self.model.addVars(self.n_nodes,
                               name='M', lb=0, ub=1,
                               vtype=GRB.CONTINUOUS)

        self.y = self.model.addVars(self.n_nodes,
                                    self.n_samples,
                               name='y', lb=0, ub=1,
                               vtype=GRB.CONTINUOUS)

        self.z = self.model.addVars(self.n_nodes,
                                    self.n_nodes,
                                    self.n_samples,
                               name='z', lb=0, ub=1,
                               vtype=GRB.CONTINUOUS)


        self.model.addConstrs((self.y[i, n] >= -1 + self.M[i]
                                          + self.B[i, n]
                                          - self.U[i, n])
                              for i in range(self.n_nodes)
                              for n in range(self.n_samples))

        self.model.addConstrs((self.z[i, j, n] >= -2 + self.T[i, j, n]
                                             + self.F[i, j, n]
                                             + self.U[j, n]
                                             - self.U[i, n])
                              for i in range(self.n_nodes)
                              for j in range(self.n_nodes)
                              for n in range(self.n_samples)
                              if i != j)

        cost_expr = 2 * self.M.sum() - (5 / self.n_samples) * self.U.sum()
        dist_expr = self.y.sum() + self.z.sum() + self.U.sum()

        self.model.setObjective(cost_expr + self.delta * dist_expr,
                                GRB.MINIMIZE)
    def solve(self):
        self.model.optimize()
        for i in range(self.n_nodes):
            print(self.M[i].x)
class optimization_model:
    def __init__(self, scenario):
        self.scenario = scenario
        self.model = Model('network_optimization')

    def create_start_time_variables(self):
        self.S = self.model.addVars(self.scenario.settings.number_of_tasks, 
                               vtype = GRB.INTEGER, 
                               lb = 0, 
                               ub = self.scenario.settings.number_of_time_periods, 
                               name = 'S')
        
    def create_end_time_variables(self):
        self.C = self.model.addVars(self.scenario.settings.number_of_tasks, 
                               vtype = GRB.INTEGER, 
                               lb = 0, 
                               ub = self.scenario.settings.number_of_time_periods, 
                               name = 'C')
        
    def create_work_time_variables(self):
        self.X = self.model.addVars(self.scenario.settings.number_of_tasks,self.scenario.settings.number_of_modes,self.scenario.settings.number_of_time_periods, 
                               vtype = GRB.BINARY, 
                               name = 'X')
        
    def create_tech_assignment_variables(self):
        self.V = self.model.addVars(self.scenario.settings.number_of_techs,self.scenario.settings.number_of_tasks,self.scenario.settings.number_of_time_periods, 
                               vtype = GRB.BINARY, 
                               name = 'V')
        
    def add_precedence_constraints(self):
        for task in self.scenario.task_list:
            for successor in task.successor_list:
                self.model.addConstr(self.S[successor] - self.C[task.task_index],
                                     GRB.GREATER_EQUAL,
                                     1, 
                                     name = "Precedence.%d.%d" % (successor,task.task_index))
    
    def set_objective_makespan(self):
        self.model.setObjective(self.C[self.scenario.task_list[-1].task_index], 
                                sense = GRB.MINIMIZE)       
        
    def create_model_variables(self):
        self.create_start_time_variables()
        self.create_end_time_variables()
        self.create_work_time_variables()
        self.create_tech_assignment_variables()
        
    def add_model_constraints(self):
        self.add_precedence_constraints()
        
    def set_model_objective(self):
        self.set_objective_makespan()
        
    def write_model(self):
        self.model.write("/Users/yashpatil/Desktop/Personal Github Projects/Multimode_Network_Assignment/model_optimizationFiles/model_formulation.lp")
Beispiel #12
0
def TWTgurobi():
    # TWT Problem Data
    jobs = tuple([i + 1 for i in range(4)])
    jobPairs = [(i, j) for i in jobs for j in jobs if i < j]
    weight = dict(zip(jobs, (4, 5, 3, 5)))
    duration = dict(zip(jobs, (12, 8, 15, 9)))
    deadline = dict(zip(jobs, (16, 26, 25, 27)))
    M = sum(duration.values())

    try:
        # Create a new model
        m = Model('TWTexample')

        # Create variables
        # x[(i,j)] = 1 if i << j, else j >> i
        x = m.addVars(jobPairs, vtype=GRB.BINARY, name='x')
        startTime = m.addVars(jobs, name='startTime')
        tardiness = m.addVars(jobs, name='tardiness')

        # Set objective function
        m.setObjective(quicksum([weight[j] * tardiness[j] for j in jobs]),
                       GRB.MINIMIZE)

        # Add constraints
        m.addConstrs(
            (startTime[j] >= startTime[i] + duration[i] - M * (1 - x[(i, j)])
             for (i, j) in jobPairs), 'NoOverlap1')
        m.addConstrs(
            (startTime[i] >= startTime[j] + duration[j] - M * x[(i, j)]
             for (i, j) in jobPairs), 'NoOverlap2')
        m.addConstrs((tardiness[j] >= startTime[j] + duration[j] - deadline[j]
                      for j in jobs), 'Deadline')

        # Solve model
        m.optimize()
        if m.status == GRB.Status.INF_OR_UNBD:
            # Disable dual reductions to determine solve status
            m.setParam(GRB.Param.DualReductions, 0)
            m.optimize()

        # Display solution
        if m.status == GRB.Status.OPTIMAL:
            for v in m.getVars():
                print('%s:\t%g' % (v.varName, v.x))
            print('Objective:\t%g' % m.objVal)
        else:
            statstr = StatusDict[m.status]
            print('Optimization was stopped with status %s' % statstr)

    except GurobiError as e:
        print('Error code ' + str(e.errno) + ": " + str(e))
def point_trajectory_given_modes_and_central_traj(x_traj,list_of_cells,goal,eps=0,scale=[]):
    """
    Description: 
        Point Trajectory Optimization with the ordered list of polytopes given
        This is a convex program as mode sequence is already given
        list_of_cells: each cell has the following attributes: A,B,c, and polytope(H,h)
    """
    model=Model("Fixed Mode Polytopic Trajectory")
    T=len(list_of_cells)
    n,m=list_of_cells[0].B.shape
    x=model.addVars(range(T+1),range(n),lb=-GRB.INFINITY,ub=GRB.INFINITY,name="x")
    u=model.addVars(range(T),range(m),lb=-GRB.INFINITY,ub=GRB.INFINITY,name="u")
    model.update()
    if len(scale)==0:
        scale=np.ones(x_traj[0].shape[0])    
    print "inside function epsilon is",eps
    for j in range(n):
        model.addConstr(x[0,j]<=x_traj[0][j]+eps*scale[j])
        model.addConstr(x[0,j]>=x_traj[0][j]-eps*scale[j])

    for t in range(T):
        cell=list_of_cells[t]
        A,B,c,_p=cell.A,cell.B,cell.c,cell.p
        for j in range(n):
            expr_x=LinExpr([(A[j,k],x[t,k]) for k in range(n)])
            expr_u=LinExpr([(B[j,k],u[t,k]) for k in range(m)])
            model.addConstr(x[t+1,j]==expr_x+expr_u+c[j,0])
        x_t=np.array([x[t,j] for j in range(n)]).reshape(n,1)
        u_t=np.array([u[t,j] for j in range(m)]).reshape(m,1)
        xu=np.vstack((x_t,u_t))
        subset_LP(model,xu,np.zeros((n+m,1)),Ball(1),_p)


    x_T=np.array([x[T,j] for j in range(n)]).reshape(n,1)
    z=zonotope(x_T,np.zeros((n,1)))
    subset_generic(model,z,goal)
    # Cost function
    J=QuadExpr()
    for t in range(T):
        for i in range(n):
            J.add(x[t,i]*x[t,i]-x[t,i]*x_traj[t][i])
    model.setObjective(J)
    model.write("polytopic_trajectory.lp")
    model.setParam('TimeLimit', 150)
    model.optimize()
    x_num,u_num={},{}
    for t in range(T+1):
        x_num[t]=np.array([[x[t,j].X] for j in range(n)])
    for t in range(T):
        u_num[t]=np.array([[u[t,i].X] for i in range(m) ])
    return (x_num,u_num)
Beispiel #14
0
def RCI(sys, q=0, alpha=0, K=5):
    """
    Computes a Robust Control Invariant (RCI) set for LTI system sys
    """
    q = K * sys.n if q == 0 else q
    model = Model("RCI")
    phi = tupledict_to_array(
        model.addVars(range(sys.n),
                      range(q),
                      lb=-GRB.INFINITY,
                      ub=GRB.INFINITY,
                      name="phi"))
    theta = tupledict_to_array(
        model.addVars(range(sys.m),
                      range(q),
                      lb=-GRB.INFINITY,
                      ub=GRB.INFINITY,
                      name="theta"))
    psi = tupledict_to_array(
        model.addVars(range(sys.n),
                      range(sys.w),
                      lb=-GRB.INFINITY,
                      ub=GRB.INFINITY,
                      name="psi"))
    model.update()
    _fat_matrix = np.hstack((psi, phi))
    constraints_list_of_tuples(model, [(sys.A, phi), (sys.B, theta),
                                       (-np.eye(sys.n), _fat_matrix[:, 0:q])],
                               "=")
    constraints_list_of_tuples(model,
                               [(np.eye(sys.n), sys.W),
                                (-np.eye(sys.n), _fat_matrix[:, q:q + sys.w])],
                               "=")
    _outer = zonotope(np.zeros((sys.n, 1)), sys.W * alpha)
    _inner = zonotope(np.zeros((sys.n, 1)), psi)
    subset_generic(model, _inner, _outer)
    if sys.X != None:
        sys.X.G *= (1 - alpha)
        subset_generic(model, zonotope(np.zeros((sys.n, 1)), phi), sys.X)
    if sys.U != None:
        sys.U.G *= (1 - alpha)
        subset_generic(model, zonotope(np.zeros((sys.m, 1)), theta), sys.U)
    model.optimize()
    phi_n = np.array([[phi[i, j].X for i in range(phi.shape[0])]
                      for j in range(phi.shape[1])]).T
    theta_n = np.array([[theta[i, j].X for i in range(theta.shape[0])]
                        for j in range(theta.shape[1])]).T
    #    psi_n=np.array([[psi[i,j].X for i in range(psi.shape[0])] for j in range(psi.shape[1])]).T
    sys.phi = phi_n * 1.0 / (1 - alpha)
    sys.theta = theta_n * 1.0 / (1 - alpha)
    return phi_n, theta_n
Beispiel #15
0
def solve():
    model = Model("Enigma Riddle Binary Program")
    letters = {"E", "N", "I", "G", "M", "A"}
    digits = range(1, 10)
    # x[i, j] == 1 => Letter i uses digit j
    x = model.addVars(letters,
                      digits,
                      vtype=GRB.BINARY,
                      name=(f"x[{l},{d}]" for l in letters for d in digits))
    # Final value for first word
    first_word = "ENIGMA"
    second_word = "IGMAEN"
    factor = 1.2

    # Constraint for the enigma-igmaen numbers
    model.addConstr(factor * quicksum(
        quicksum(10**(len(first_word) - 1 - i) * j * x[first_word[i], j]
                 for j in digits)
        for i in range(len(first_word))) - quicksum(
            quicksum(10**(len(second_word) - 1 - i) * j * x[second_word[i], j]
                     for j in digits) for i in range(len(second_word))) == 0)

    # Conflict constraint, different letters have different digits
    model.addConstrs(quicksum(x[i, j] for i in letters) <= 1 for j in digits)

    # Exactly one digit has to be used per letter
    model.addConstrs(quicksum(x[i, j] for j in digits) == 1 for i in letters)

    model.optimize()
    return model
Beispiel #16
0
    def _construct_max_flow_lp(self, G, edge_to_paths, num_total_paths):
        m = Model('max-flow')

        # Create variables: one for each path
        path_vars = m.addVars(num_total_paths,
                              vtype=GRB.CONTINUOUS,
                              lb=0.0,
                              name='f')

        obj = quicksum(path_vars)
        m.setObjective(obj, GRB.MAXIMIZE)

        # Add demand constraints
        commod_id_to_path_inds = {}
        for k, d_k, path_inds in self.commodities:
            commod_id_to_path_inds[k] = path_inds
            m.addConstr(quicksum(path_vars[p] for p in path_inds) <= d_k)

        # Add edge capacity constraints
        for u, v, c_e in G.edges.data('capacity'):
            paths = edge_to_paths[(u, v)]
            constr_vars = [path_vars[p] for p in paths]
            m.addConstr(quicksum(constr_vars) <= c_e)

        return LpSolver(m, None, self.DEBUG, self.VERBOSE, self.out)
Beispiel #17
0
def initialize_model(cost_matrix, cutoff, model=None):
    #Add dummy detection
    cost_matrix = np.insert(cost_matrix,
                            0,
                            np.ones(cost_matrix.shape[0]) * cutoff,
                            axis=1)
    M, N = cost_matrix.shape
    if model is None:
        model = Model()
    else:
        model.remove(model.getVars())
        model.remove(model.getConstrs())
    model.setParam('OutputFlag', False)
    # y = []
    # for i in range(M):
    #     y.append([])
    #     for j in range(N):
    #         y[i].append(m.addVar(vtype=GRB.BINARY, name = 'y_%d%d'%(i,j)))
    y = model.addVars(M, N, vtype=GRB.BINARY, name='y')
    model.setObjective(
        quicksum(
            quicksum([y[i, j] * cost_matrix[i][j] for j in range(N)])
            for i in range(M)), GRB.MINIMIZE)
    # for i in range(M):
    model.addConstrs(
        (quicksum(y[i, j] for j in range(N)) == 1 for i in range(M)),
        name='constraint for track')
    # for j in range(1,N):
    model.addConstrs(
        (quicksum(y[i, j] for i in range(M)) <= 1 for j in range(1, N)),
        name='constraint for detection')
    y = list(y.values())
    return model, M, N, y
def optimize_pareto(Bw, h, ju_s, ju_l, jn_s, jn_l):
    # create a model
    m = Model('Pareto')
    # create decision variables
    x = m.addVars(an, an, vtype=GRB.BINARY, name='x')
    y = m.addVars(an, dc, vtype=GRB.BINARY, name='y')

    ######### add constraints ##########
    m.addConstrs((x[i, j] == x[j, i] for i in an for j in an),
                 'symmetric constraint')
    # Two service areas cant use the same stateful functions when x[i,j] = 0
    m.addConstrs((y[i, t] + y[j, t] <= x[i, j] + 1 for i in an for j in an
                  for t in dc), 'x = 0 constraint')
    # Two service areas use the same stateful functions when x[i,j] = 1
    m.addConstrs(((y[i, t] - y[j, t] <= 1 - x[i, j]) for i in an for j in an
                  for t in dc), 'x = 1 constraint')
    # Each should be at least managed by one dc
    m.addConstrs((sum(y[i, t] for t in dc) == 1 for i in an),
                 'one dc for access node')
    # high availability constraint
    m.addConstr(
        sum((1 - x[i, j]) for i in an for j in an if i != j) >= 1, 'ha')
    # maximum state transfer frequency
    m.addConstr(
        sum(h * (1 - x[i, j]) for i in an for j in an if i != j) <= jn_s - 1,
        'max state transfer constraint')
    # maximum latency constraint
    m.addConstr(
        sum(y[i, t] * C[i, t] * (Sd / Bw + Lw + Wg) for i in an
            for t in dc) <= jn_l, 'latency maximum constraint')

    ######## Objective function #########
    m.setObjective((sum(y[i, t] * C[i, t] * (Sd / Bw + Lw + Wg) for i in an
                        for t in dc) - ju_l) / (jn_l - ju_l) +
                   (sum(h * (1 - x[i, j]) for i in an
                        for j in an if i != j) - ju_s) / (jn_s - ju_s),
                   GRB.MINIMIZE)

    m.optimize()

    ######## Calculate performance metrics #########
    # latency
    latency = sum(C[i, t] * getattr(y[i, t], 'X') * (Sd / Bw + Lw + Wg)
                  for i in an for t in dc)

    # state transfer frequency
    state_transfer = sum(h * (1 - getattr(x[i, j], 'X')) for i in an
                         for j in an if i != j)

    # total cost
    cost = latency + state_transfer

    # number of functions
    num_func = M_dc - sum(
        prod(1 - getattr(y[i, t], 'X') for i in an) for t in dc)

    # total metrics
    total_metrics = [Bw, h, state_transfer, latency, num_func, cost]

    return total_metrics
def optimize_latency(Bw, h):
    # create a model
    m = Model('latency')
    # create decision variables
    x = m.addVars(an, an, vtype=GRB.BINARY, name='x')
    y = m.addVars(an, dc, vtype=GRB.BINARY, name='y')

    ######### add constraints ##########
    # x is symmetric
    m.addConstrs((x[i, j] == x[j, i] for i in an for j in an),
                 'symmetric constraint')
    # Two service areas cant use the same stateful functions when x[i,j] = 0
    m.addConstrs((y[i, t] + y[j, t] <= x[i, j] + 1 for i in an for j in an
                  for t in dc), 'x = 0 constraint')
    # Two service areas use the same stateful functions when x[i,j] = 1
    m.addConstrs(((y[i, t] - y[j, t] <= 1 - x[i, j]) for i in an for j in an
                  for t in dc), 'x = 1 constraint')
    # One access node connects to only one dc
    m.addConstrs((sum(y[i, t] for t in dc) == 1 for i in an),
                 'one dc for access node')
    # high availability constraint
    m.addConstr(
        sum((1 - x[i, j]) for i in an for j in an if i != j) >= 1, 'ha')
    # maximum state transfer frequency
    m.addConstr(
        sum(h * (1 - x[i, j]) for i in an for j in an if i != j) <= State_max,
        'max state transfer constraint')

    ######## Objective function #########
    # Optimize latency budget
    m.setObjective(
        sum(y[i, t] * C[i, t] * (Sd / Bw + Lw + Wg) for i in an for t in dc),
        GRB.MINIMIZE)

    m.optimize()

    ######## Calculate performance metrics #########
    # latency
    latency = sum(C[i, t] * (Sd / Bw + Lw + Wg) * getattr(y[i, t], 'X')
                  for i in an for t in dc)

    # state transfer frequency
    state_transfer = sum(h * (1 - getattr(x[i, j], 'X')) for i in an
                         for j in an if i != j)

    # number of function
    num_func = M_dc - sum(
        prod(1 - getattr(y[i, t], 'X') for i in an) for t in dc)

    # total cost
    cost = latency + state_transfer

    # total metrics
    total_metrics = [Bw, h, state_transfer, latency, num_func, cost]

    # utopia point, nadir point
    worst_state = state_transfer
    best_latency = latency

    return total_metrics, worst_state, best_latency
Beispiel #20
0
    def _construct_smore_lp(self, G, edge_to_paths, num_total_paths):
        m = Model('min-edge-util')

        # Create variables: one for each path
        path_vars = m.addVars(num_total_paths,
                              vtype=GRB.CONTINUOUS,
                              lb=0.0,
                              ub=1.0,
                              name='f')
        max_link_util_var = m.addVar(vtype=GRB.CONTINUOUS, lb=0.0, name='z')
        m.update()
        m.setObjective(max_link_util_var, GRB.MINIMIZE)

        # Add demand constraints
        for k, d_k, path_ids in self.commodities:
            m.addConstr(quicksum(path_vars[p] for p in path_ids) == 1)

        # Add edge util constraints
        for u, v, c_e in G.edges.data('capacity'):
            paths = edge_to_paths[(u, v)]
            constr_vars = [
                path_vars[p] * self.commodities[self._path_to_commod[p]][-2]
                for p in paths
            ]
            m.addConstr(quicksum(constr_vars) / c_e <= max_link_util_var)

        return LpSolver(m, None, self.DEBUG, self.VERBOSE, self.out)
Beispiel #21
0
def _cut_half(c, P):
    """
    Given polytopen and direction c, cut it into half
    """
    n = c.shape[0]
    assert n == P.H.shape[1]
    model = Model("n")
    x = tupledict_to_array(
        model.addVars(range(n), [0],
                      lb=-GRB.INFINITY,
                      ub=GRB.INFINITY,
                      name="x"))
    model.update()
    constraints_list_of_tuples(model, [(P.H, x), (-np.eye(P.h.shape[0]), P.h)],
                               sign="<")
    J = LinExpr([(c[i, 0], x[i, 0]) for i in range(n)])
    model.setParam('OutputFlag', False)
    model.setObjective(J, GRB.MINIMIZE)
    model.optimize()
    g_min = model.ObjVal
    model.setObjective(J, GRB.MAXIMIZE)
    # Max
    model.reset()
    model.optimize()
    g_max = model.ObjVal
    g = np.array([(g_max + g_min) / 2.0]).reshape(1, 1)
    P1 = polytope(np.vstack((P.H, c.T)), np.vstack((P.h, g)))
    P2 = polytope(np.vstack((P.H, -c.T)), np.vstack((P.h, -g)))
    return P1, P2, (c, g)
def solve():
    model = Model("Enigma Riddle Binary Program")
    letters = {"E", "N", "I", "G", "M", "A"}
    digits = range(1, 10)
    # x[i, j] == 1 => Letter i uses digit j
    x = model.addVars(letters, digits, vtype=GRB.BINARY)
    # Final value for first word
    b = model.addVar(vtype=GRB.INTEGER)
    first_word = "ENIGMA"
    second_word = "IGMAEN"

    # Constraints for the enigma-igmaen numbers
    model.addConstr(
        quicksum(
            quicksum(10**(len(first_word) - 1 - i) * j * x[first_word[i], j]
                     for j in digits) for i in range(len(first_word))) == b)
    model.addConstr(
        quicksum(
            quicksum(10**(len(second_word) - 1 - i) * j * x[second_word[i], j]
                     for j in digits)
            for i in range(len(second_word))) == b * 1.2)

    # Conflict constraint, different letters have different digits
    model.addConstrs(x[i_1, j] + x[i_2, j] <= 1 for i_1 in letters
                     for i_2 in letters for j in digits if i_1 != i_2)

    # Exactly one digit has to be used per letter
    model.addConstrs(quicksum(x[i, j] for j in digits) == 1 for i in letters)

    model.optimize()
    return model
Beispiel #23
0
def optimize(inputFile, outputFile):
    '''Function which takes in two input arguments:
        - inputFile: the path to the input data. (.xlsx format)
        - outputFile: the path to the output data. (.xlsx format)
        The outputFile gives the optimal set of books to carry as well as 
        the minimum number of books needed.'''
    genres = pd.read_excel(inputFile, sheet_name='genres',
                           index_col=0).fillna(0)
    requirements = pd.read_excel(inputFile,
                                 sheet_name='requirements',
                                 index_col=0)

    mod = Model()
    I = genres.index
    J = genres.columns

    x = mod.addVars(I, vtype=GRB.BINARY)
    mod.setObjective(sum(x[i] for i in I))
    for j in J:
        mod.addConstr(
            sum(genres.loc[i, j] * x[i] for i in I) >= requirements.loc[j])
    mod.setParam('outputflag', False)
    mod.optimize()

    writer = pd.ExcelWriter(outputFile)
    carry = []
    for i in I:
        if x[i].x:
            carry.append(i)
    pd.DataFrame(carry,columns=['books'])\
        .to_excel(writer,sheet_name='optimal_decision')
    pd.DataFrame([mod.objVal],columns=['books_needed'])\
        .to_excel(writer,sheet_name='objective',index=False)
    writer.save()
def Distribution_Matching(D):
    mean = np.mean(D)
    moment = [np.var(D), stats.skew(D),
              stats.kurtosis(D)]

    N = len(D)
    T1 = range(N)
    K = range(len(moment))
    #number of moments

    W = np.array([0.5, 0.35, 0.15])
    Omega = np.random.uniform(0, 1, (1, N))
    osum = np.sum(Omega)
    Omega = [i / osum for i in Omega[0]]
    # Gurobi Model: Define variables
    ProbModel = Model()
    P = ProbModel.addVars(N, lb=0, ub=1, vtype=GRB.CONTINUOUS, name="P")
    S1 = ProbModel.addVars(N, lb=0, vtype=GRB.CONTINUOUS, name="S1")
    S2 = ProbModel.addVars(N, lb=0, vtype=GRB.CONTINUOUS, name="S2")

    M1 = ProbModel.addVars(K, lb=0, vtype=GRB.CONTINUOUS, name="M1")
    M2 = ProbModel.addVars(K, lb=0, vtype=GRB.CONTINUOUS, name="M2")

    #  Objective Function
    Z = quicksum(W[k] * (M1[k] + M2[k])
                 for k in K[1:]) + quicksum(Omega[j] * (S1[j] + S2[j])
                                            for j in T1)
    ProbModel.setObjective(Z, GRB.MINIMIZE)

    # Define Constraints

    ProbModel.addConstr(quicksum(P[j] for j in T1) == 1)
    ProbModel.addConstr(quicksum(D[j] * P[j] for j in T1) == mean)
    ProbModel.addConstrs(
        quicksum((D[j] - mean)**(k + 2) * P[j]
                 for j in T1) + M1[k] - M2[k] == moment[k] for k in K)
    ProbModel.addConstrs(
        stats.norm.cdf((D[j] - mean) / moment[0]) -
        quicksum(P[jp] for jp in T1) == S1[j] - S2[j] for j in T1)
    ProbModel.addConstrs(P[j] >= 0.1 for j in T1)
    # Solve and publish
    ProbModel.Params.OutputFlag = 0
    ProbModel.optimize()

    return ProbModel.x[:N]
def optimize(inputFile, outputFile):
    import pandas as pd
    from gurobipy import Model, GRB
    FC = pd.read_excel(inputFile, sheet_name='Fulfilment Centers', index_col=0)
    I = FC.index  ### fulfilment center index
    Q = FC['capacity']  ### capacity at each fulfilment center
    Regions = pd.read_excel(inputFile, sheet_name='Regions', index_col=0)
    J = Regions.index  ### Demand region index
    Distance = pd.read_excel(inputFile, sheet_name='Distances', index_col=0)
    E = Distance
    Items = pd.read_excel(inputFile, sheet_name='Items', index_col=0)
    K = Items.index  ### Items
    W = Items.iloc[:, 0]  ### shipping weight
    S = Items.iloc[:, 1]  ### storage size
    D = pd.read_excel(inputFile, sheet_name='Demand', index_col=0)
    cap = []
    mod = Model()
    x = mod.addVars(I, J, K, vtype=GRB.CONTINUOUS, lb=0, name='x')
    mod.setObjective(
        sum(1.38 * W.loc[k] * E.loc[j, i] * x[i, j, k] for i in I for j in J
            for k in K))
    for j in J:
        for k in K:
            mod.addConstr(sum(x[i, j, k] for i in I) == D.loc[k, j])
    for i in I:
        cap.append(
            mod.addConstr(
                sum(x[i, j, k] * S.loc[k] for j in J for k in K) <= Q.loc[i]))
    mod.optimize()
    mod.setParam('outputflag', False)
    Summary = pd.DataFrame([mod.objVal], columns=['Objective Value'])
    Solution = []
    for i in I:
        for j in J:
            for k in K:
                if x[i, j, k].x:
                    Solution.append([i, j, k, x[i, j, k].x])
    Solution = pd.DataFrame(
        Solution, columns=['FC_name', 'region_ID', 'item_ID', 'shipment'])
    cap = pd.Series(cap, index=I)
    cap1 = []
    for i in range(len(I)):
        cap1.append([I[i], cap[i].pi])
    Capacity_constr = pd.DataFrame(cap1, columns=['FC_name', 'shadow_price'])
    Capacity_constr = Capacity_constr.sort_values('shadow_price',
                                                  ascending=True)
    writer = pd.ExcelWriter(outputFile)
    pd.DataFrame([mod.objVal],
                 columns=['Objective Value']).to_excel(writer,
                                                       sheet_name='Summary',
                                                       index=False)
    Solution.to_excel(writer, sheet_name='Solution', index=False)
    Capacity_constr.to_excel(writer,
                             sheet_name='Capacity Constraints',
                             index=False)
    writer.save()
Beispiel #26
0
def RCI_controller(sys, x):
    """
    Based on zonotopes
    """
    model = Model("Controller")
    q = sys.phi.shape[1]
    zeta = tupledict_to_array(
        model.addVars(range(q), [0], lb=-1, ub=1, name="zeta"))
    zeta_abs = tupledict_to_array(
        model.addVars(range(q), [0], lb=0, ub=1, name="zeta_abs", obj=1))
    model.update()
    constraints_list_of_tuples(model, [(-np.eye(sys.n), x), (sys.phi, zeta)])
    model.addConstrs(zeta_abs[i, 0] >= zeta[i, 0] for i in range(q))
    model.addConstrs(zeta_abs[i, 0] >= -zeta[i, 0] for i in range(q))
    model.setParam('OutputFlag', False)
    model.optimize()
    zeta_n = np.array([zeta[i, 0].X for i in range(q)]).reshape(q, 1)
    print zeta_n.T
    return np.dot(sys.theta, zeta_n)
def depOptimizer(base_schedule, allocations, dep):
    df = base_schedule[base_schedule['department'] == dep].copy()
    #df = df[df['level'] == 'UG']
    #df = df[df['first_days'].isin(['MW', 'TH'])]
    df.index = df['section']
    # Defining J
    J = list(allocations.columns)
    # Defining F
    F = pd.Series(allocations.iloc[0, :], dtype='float64').copy()
    # Defining A
    A = pd.Series(index=J, dtype='float64')
    for j in J:
        val = allocations.loc[allocations[j] == dep, j].count()
        A[j] = 4 * val
    # Defining I
    I = list(df.index)
    # Defining S
    S = pd.Series(df.loc[:, 'seats_offered'], dtype='float64').copy()
    # Defining L
    L = pd.Series(df.loc[:, 'periods'], dtype='float64').copy()
    # Gurobi Optimization
    mod = Model()
    X = mod.addVars(I, J, vtype=GRB.BINARY)
    mod.setObjective(sum(F[j] * X[i, j] - S[i] * X[i, j] for i in I
                         for j in J))
    # i
    for j in J:
        mod.addConstr(sum(L[i] * X[i, j] for i in I) <= A[j])
    # ii
    for i in I:
        for j in J:
            mod.addConstr(S[i] * X[i, j] <= F[j])
    # iii
    for i in I:
        mod.addConstr(sum(X[i, j] for j in J) == 1)
    mod.setParam('outputflag', False)
    mod.optimize()
    # Creating Decision vars dataframe
    output = pd.DataFrame(
        index=I,
        columns=['Class_Section', 'Room', 'Course', 'Students', 'Capacity'])
    output['Class_Section'] = output.index
    for i in I:
        for j in J:
            if X[i, j].x:
                room = j
        output.loc[i, 'Room'] = room
        output.loc[i, 'Course'] = df.loc[i, 'course']
        output.loc[i, 'Students'] = S[i]
        output.loc[i, 'Capacity'] = F[output.loc[i, 'Room']]
    output['Average Empty Seats per Class'] = np.nan
    output = output.reset_index(drop=True)
    output.loc[0, 'Average Empty Seats per Class'] = round(
        mod.objVal / len(I), 2)
    return (output)
Beispiel #28
0
def markovitz_dro_wasserstein(data,
                              delta_param,
                              alpha_param,
                              wasserstein_norm=1):
    '''
    Model from Blanchet et al. 2017
    DRO Markovitz reformulation from Wasserstein distance.
    '''

    r = np.mean(data, axis=0)
    cov = np.cov(data, rowvar=False)
    k = len(r)
    n = len(data)
    m = Model('opt_profolio')
    m.params.OutputFlag = 0
    m.params.NumericFocus = 3
    x = m.addVars(k, lb=0, ub=1, vtype=GRB.CONTINUOUS, name='x')
    norm_p = m.addVar(lb=0, ub=1, vtype=GRB.CONTINUOUS, name='norm')
    p_SD = m.addVar(lb=0, vtype=GRB.CONTINUOUS, name='p_var')
    m.update()

    sqrt_delta = np.sqrt(delta_param)
    m.addConstr((x.sum() == 1), 'portfolio_ctr')
    m.addConstr(
        (quicksum(x[j] * r[j]
                  for j in range(k)) >= alpha_param - sqrt_delta * norm_p),
        'return_ctr')
    m.addConstr((p_SD * p_SD >= quicksum(cov[i, j] * x[i] * x[j]
                                         for i in range(k)
                                         for j in range(k))), 'SD_def')
    objfun = p_SD * p_SD + 2 * p_SD * sqrt_delta * norm_p + delta_param * norm_p * norm_p
    m.setObjective(objfun, GRB.MINIMIZE)

    if wasserstein_norm == 1:
        regularizer_norm = 'inf'
        m.addConstrs((norm_p >= x[j] for j in range(k)), 'norm_def')
    elif wasserstein_norm == 2:
        regularizer_norm = 2
        m.addConstr((norm_p * norm_p >=
                     (quicksum(x[j] * x[j] for j in range(k)))), 'norm_def')
    elif wasserstein_norm == 'inf':
        regularizer_norm = 1
        #Note: this works since x>=0
        m.addConstr((norm_p == (quicksum(x[j] for j in range(k)))), 'norm_def')
    else:
        raise 'wasserstain norm should be 1,2, or inf'

    m.optimize()
    x_sol = np.array([x[j].X for j in range(k)])
    p_mean = r.dot(x_sol)
    p_var = x_sol.dot(cov.dot(x_sol))
    #print(x_sol, p_mean, p_var)
    #print('norms' , np.linalg.norm(x_sol) , norm_p.X)

    return x_sol, p_mean, p_var
    def create_model(self):
        model = Model()
        _A = [(i,t) for i in self.tasks for t in self.periods]
        x = model.addVars(_A, vtype = GRB.BINARY) # create decision variables
        b = model.addVars(_A, vtype = GRB.BINARY) # create decision variables

        # create constraints
        model.addConstrs(quicksum(self.p[i,t] * (1 - x[i,t]) for i in self.tasks) - \
            self.d[t] >= 0 for t in self.periods) # 1
        model.addConstrs(quicksum(b[i,t] for t in self.periods) == 1 \
            for i in self.tasks) # 2
        model.addConstrs(x[i,t] >= b[i,t] for i in self.tasks for t in self.periods) # 3
        model.addConstrs(x[i,t] - x[i,t-1] <= b[i,t] for i in self.tasks \
            for t in self.periods[1:]) # 3, t >= 2
        _tmp =  self.periods[1:]
        # model.addConstrs(x[i,t] <= b[i,t] for t in _tmp \
        #     for i in self.tasks) # 4
        model.addConstrs(x[i,t] + x[i,t-1] + b[i,t] <= 1+self.LP[i] for t in self.periods[1:] \
            for i in self.tasks) # 4
        model.addConstrs(quicksum(x[i,t] for t in self.periods) == self.LP[i] \
            for i in self.tasks) # 5
        model.addConstrs(quicksum(x[i,t] for i in self.tasks) <= self.LT[t] \
            for t in self.periods) # 6
        model.addConstrs(quicksum(b[i,k] for k in self.periods) - b[j,t] >= 0 \
            for t in self.periods for i in self.tasks for j in self.tasks if j!=i) # 7
        model.addConstrs(x[i,t] + x[j,t] <= 1 for t in self.periods \
            for i in self.tasks for j in self.tasks if j!=i) # 8
        model.addConstrs(quicksum(b[i,t] for t in self.periods[:self.L[i]-self.LP[i]+2]) == 1 \
            for i in self.tasks) # 9
        # model.addConstrs(quicksum(x[i,t] == 0 for t in self.U) for i in self.tasks) # 10
        model.addConstrs(x[i,t] == 0 for t in self.U for i in self.tasks) # 10
        model.addConstrs(quicksum((self.MV[i] + self.MH[i] + self.ML[i]) * x[i,t] \
            for i in self.tasks) <= self.AM[t] for t in self.periods) # 11
        model.addConstrs(quicksum(self.V[i] * x[i,t] for i in self.tasks) \
            <= self.AV[t] for t in self.periods) # 12
        model.addConstrs(quicksum(self.H[i] * x[i,t] for i in self.tasks) <= \
            self.AH[t] for t in self.periods) # 13

        # create costs
        C_M, C_T = {}, {}
        for i in self.tasks:
            for t in self.periods:
                C_M[i,t] = self.C_MV[t] * self.MV[i] + self.C_MH[t] * self.MH[i] + \
                    self.C_ML[t] * self.ML[i]
                C_T[i,t] = (self.C_FV * self.V[i] + self.C_FH * self.H[i])/self.LP[i] + \
                    self.C_SV[i,t] * self.V[i] + self.C_SH[i,t] * self.H[i]

        model.modelSense = GRB.MINIMIZE
        # create ojective function
        model.setObjective(quicksum((C_M[i,t] + self.C_EQ[i,t] + self.C_I[i,t] + \
            C_T[i,t]) * x[i,t] for t in self.periods for i in self.tasks))
        # model.setParam('OutputFlag', 0)
        model.optimize()
        return
Beispiel #30
0
def ilp_node_reachability(reachability_dic, max_delay=180, log_path=None):

    # List of nodes ids
    node_ids = sorted(list(reachability_dic.keys()))
    #node_ids = node_ids[:100]

    try:

        # Create a new model
        m = Model("region_centers")

        if log_path:
            m.Params.LogFile = '{}/region_centers_{}.log'.format(
                log_path, max_delay)

        # xi = 1, if vertex Vi is used as a region center and 0 otherwise
        x = m.addVars(node_ids, vtype=GRB.BINARY, name="x")

        # Ensures that every node in the road network graph is reachable
        # within 'max_delay' travel time by at least one region center
        # selected from the nodes in the graph.
        # To extract the region centers, we select from V all vertices
        # V[i] such that x[i] = 1.
        for d in node_ids:
            m.addConstr(
                quicksum(x[o] * is_reachable(reachability_dic, o, d, max_delay)
                         for o in node_ids) >= 1)

        # Set objective
        m.setObjective(quicksum(x), GRB.MINIMIZE)

        # Solve
        m.optimize()

        region_centers = list()

        if m.status == GRB.Status.OPTIMAL:

            var_x = m.getAttr('x', x)
            for n in node_ids:
                if var_x[n] > 0.0001:
                    region_centers.append(n)

            return region_centers

        else:
            print('No solution')
            return None

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

    except AttributeError as e:
        print('Encountered an attribute error:' + str(e))
Beispiel #31
0
    def run_algorithm(self):

        old_M = self.M
        old_items = [i.copy() for i in self.items]
        map_name_to_old_item = dict()
        for i in old_items:
            map_name_to_old_item[i.name] = i
        self.scale_items_by_cost()

        from gurobipy import Model, GRB
        model = Model("NP-Hard")

        print("Setting Model Parameters")
        # set timeout
        model.setParam('TimeLimit', 1600)
        model.setParam('MIPFocus', 3)
        model.setParam('PrePasses', 1)
        model.setParam('Heuristics', 0.01)
        model.setParam('Method', 0)

        map_name_to_item = dict()
        map_name_to_cost = dict()
        map_name_to_weight = dict()
        map_name_to_profit = dict()
        map_class_to_name = dict()
        
        item_names = list()

        print("Preprocessing data for model...")

        for item in self.items:
            item_names.append(item.name)
            map_name_to_item[item.name] = item
            map_name_to_cost[item.name] = item.cost
            map_name_to_weight[item.name] = item.weight
            map_name_to_profit[item.name] = item.profit
            if item.classNumber not in map_class_to_name:
                map_class_to_name[item.classNumber] = list()
            map_class_to_name[item.classNumber].append(item.name)

        class_numbers = list(map_class_to_name.keys())

        print("Setting model variables...")
        # binary variables =1, if use>0
        items = model.addVars(item_names, vtype=GRB.BINARY, name="items")
        classes = model.addVars(class_numbers, vtype=GRB.BINARY, name="class numbers")

        print("Setting model objective...")
        # maximize profit
        objective = items.prod(map_name_to_profit)
        model.setObjective(objective, GRB.MAXIMIZE)

        # constraints
        print("Setting model constraints")
        model.addConstr(items.prod(map_name_to_weight) <= self.P,"weight capacity")
        model.addConstr(items.prod(map_name_to_cost) <= self.M,"cost capacity")
        
        # if any item from a class is chosen, that class variable has to be a binary of 1
        for num in class_numbers:
            model.addGenConstrOr(classes[num], [items[x] for x in map_class_to_name[num]] ,name="class count")

        for c in self.raw_constraints:
            count = model.addVar()
            for n in c:
                if n in classes:
                    count += classes[n]
            model.addConstr(count <= 1, name="constraint")

        print("Start optimizing...")
        model.optimize()
        print("Done! ")

        # Status checking
        status = model.Status
        if status == GRB.Status.INF_OR_UNBD or \
           status == GRB.Status.INFEASIBLE  or \
           status == GRB.Status.UNBOUNDED:
            print('The model cannot be solved because it is infeasible or unbounded')

        if status != GRB.Status.OPTIMAL:
            print('Optimization was stopped with status ' + str(status))
            Problem = True

        try:
            model.write("mps_model/" + self.filename + ".sol")
        except Exception as e:
            pass

        print("Generating solution file...")
        # Display solution
        solution_names = list()
        for i, v in enumerate(items):
            try:
                if items[v].X > 0.9:
                    solution_names.append(item_names[i])
            except Exception as e:
                pass

        self.M = old_M
        self.items = old_items
        solution = [map_name_to_old_item[i] for i in solution_names]
        return solution