当前位置: 首页>>代码示例>>Python>>正文


Python Model.write方法代码示例

本文整理汇总了Python中gurobipy.Model.write方法的典型用法代码示例。如果您正苦于以下问题:Python Model.write方法的具体用法?Python Model.write怎么用?Python Model.write使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在gurobipy.Model的用法示例。


在下文中一共展示了Model.write方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: solve

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]
def solve(budget, buses, lines, u, c, b, S, D):
    m = Model('inhibit')
    w, v, y = {}, {}, {}
    for i in buses:
        w[i] = m.addVar(vtype=GRB.BINARY, name="w_%s" % i)
    for i, j in lines:
        v[i, j] = m.addVar(vtype=GRB.BINARY, name='v_%s_%s' % (i, j))
        y[i, j] = m.addVar(vtype=GRB.BINARY, name='y_%s_%s' % (i, j))
    m.update()

    for i, j in lines:
        m.addConstr(w[i]-w[j] <= v[i, j] + y[i, j], 'balance1_%s_%s' % (i, j))
        m.addConstr(w[j]-w[i] <= v[i, j] + y[i, j], 'balance2_%s_%s' % (i, j))
    m.addConstr(quicksum(c[i, j]*y[i, j] for i, j in lines) <= budget, 'budget')
        
    m.setObjective(quicksum(u[i, j]*v[i, j] for i, j in lines) +
                   quicksum(b[i]*(1-w[i]) for i in S) -
                   quicksum(b[i]*w[i] for i in D))
    
    m.setParam('OutputFlag', 0)
    m.optimize()
    m.write('gurobi.lp')
    return w, v, y, m
开发者ID:sharnett,项目名称:power-grid-attack,代码行数:25,代码来源:max_mismatch_heuristic.py

示例2: BFPBackupNetwork_Continuous

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]

#.........这里部分代码省略.........
                elif i == d:
                    self.model.addConstr(
                        quicksum(self.bBackupLink[i, j, s, d] for i, j in self.Links.select(i, "*"))
                        - quicksum(self.bBackupLink[j, i, s, d] for j, i in self.Links.select("*", i))
                        == -1,
                        "Flow2[%s,%s,%s]" % (i, s, d),
                    )
                # Flow conservation constraints
                else:
                    self.model.addConstr(
                        quicksum(self.bBackupLink[i, j, s, d] for i, j in self.Links.select(i, "*"))
                        - quicksum(self.bBackupLink[j, i, s, d] for j, i in self.Links.select("*", i))
                        == 0,
                        "Flow3[%s,%s,%s]" % (i, s, d),
                    )
        self.model.update()

    def Optimize(self, MipGap=None, TimeLimit=None, LogLevel=None):
        """ Optimize the defined  model.
    
        Parameters
        ----------
        MipGap : desired gap
        TimeLimit : time limit
        LogLevel: log level 1 for printing all optimal variables and None otherwise
        
        Returns
        -------
        BackupCapacity: The total capacity assigned per backup link
        BackupRoutes: The set of selected backup links 
           A tuple list with all paths for edge (s,d) that uses (i,j).
    
        """
        self.model.write("bpbackup.lp")

        if MipGap != None:
            self.model.params.MIPGap = MipGap
        if TimeLimit != None:
            self.model.params.timeLimit = TimeLimit
        # Compute optimal solution
        self.model.optimize()

        # Print solution
        if self.model.status == GRB.Status.OPTIMAL:

            if LogLevel == 1:
                for v in self.model.getVars():
                    print("%s %g" % (v.varName, v.x))

            self.BackupCapacitySolution = self.model.getAttr("x", self.BackupCapacity)
            self.BackupRoutesSolution = self.model.getAttr("x", self.bBackupLink)

            self.BackupLinksSolution = {}
            self.HatBackupCapacity = {}
            for link in self.BackupCapacitySolution:
                if self.BackupCapacitySolution[link] < 1 and self.BackupCapacitySolution[link] > 0.001:
                    self.HatBackupCapacity[link] = math.ceil(self.BackupCapacitySolution[link])
                else:
                    self.HatBackupCapacity[link] = math.floor(self.BackupCapacitySolution[link])
                if self.HatBackupCapacity[link] > 0:
                    if len(self.BackupLinksSolution) == 0:
                        self.BackupLinksSolution = [link]
                    else:
                        self.BackupLinksSolution = self.BackupLinksSolution + [link]
        else:
            print("Optimal value not found!\n")
开发者ID:edielsonpf,项目名称:robust-network-optimization,代码行数:70,代码来源:BFPBackupModel_Continuous.py

示例3: Guroby

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]

#.........这里部分代码省略.........
                for sourcePhase in xrange(range_source):  # source/prod/out normaux
                    if sourcePhase > 0:
                        pred_prod += prod_list[sourcePhase - 1]

                    pred_cons = 0
                    cons = 0
                    for targetPhase in xrange(range_target):  # target/cons/in normaux
                        cons += cons_list[targetPhase]
                        if targetPhase > 0:
                            pred_cons += cons_list[targetPhase - 1]

                        w = cons - pred_prod - arc_gcd
                        if self.dataflow.is_pcg:
                            w += pred_cons + threshold_list[targetPhase] - cons

                        str_v1 = str(source) + "/" + str(sourcePhase)
                        str_v2 = str(target) + "/" + str(targetPhase)

                        self.__add_row(str_v1, str_v2, arc, w)
        # END FILL ROW

    def __create_obj(self):
        obj = QuadExpr()

        for arc in self.dataflow.get_arc_list():
            obj += self.col_m0[arc]
        self.prob.setObjective(obj, GRB.MINIMIZE)

    def __solve_prob(self):  # Launch the solver and set preload of the graph
        logging.info("loading matrix ...")
        self.prob.update()

        if self.lp_filename is not None:
            problem_location = str(self.prob.write(self.lp_filename))
            logging.info("Writing problem: " + str(problem_location))

        logging.info("solving problem ...")
        self.prob.optimize()
        logging.info("Integer solving done !")

        self.Z = self.prob.objVal

        for arc in self.dataflow.get_arc_list():
            if not self.dataflow.is_arc_reentrant(arc):
                self.dataflow.set_initial_marking(arc, int(self.col_m0[arc].x))

        logging.info("SC1 MIP Mem tot (no reentrant): " + str(self.Z))

    # Add a variable lamda
    def __add_col_v(self, name):
        var = self.prob.addVar(vtype=GRB.CONTINUOUS, name=name)
        self.col_v[name] = var

    # Add a variable M0
    def __add_col_m0(self, arc):
        var = self.prob.addVar(lb=0, vtype=GRB.INTEGER)
        self.col_m0[arc] = var

    # Add a variable FM0
    def __add_col_fm0(self, arc):
        var = self.prob.addVar(lb=0, vtype=GRB.INTEGER)
        self.col_fm0[arc] = var

    # Add a constraint: lambda1 - lambda2 + M0 > W1
    def __add_row(self, str_v1, str_v2, arc, w):
        expr = LinExpr()
开发者ID:bbodin,项目名称:turbine,代码行数:70,代码来源:solve_SC1_Gurobi_MIP.py

示例4: run_algorithm

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]
    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
#.........这里部分代码省略.........
开发者ID:Michael-Tu,项目名称:ClassWork,代码行数:103,代码来源:solver.py

示例5: Backup

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]

#.........这里部分代码省略.........
        self.__model = Model('Backup')
    
        # Auxiliary variables for SOCP reformulation
        U = {}
        R = {}
      
        # Create variables
        for i,j in self.__links:
            self.__BackupCapacity[i,j] = self.__model.addVar(lb=0, obj=1, name='Backup_Capacity[%s,%s]' % (i, j))
        self.__model.update()
         
        for i,j in self.__links:
            for s,d in self.__links:
                self.__bBackupLink[i,j,s,d] = self.__model.addVar(vtype=GRB.BINARY,obj=1,name='Backup_Link[%s,%s,%s,%s]' % (i, j, s, d))
        self.__model.update()
        
        for i,j in self.__links:
            U[i,j] = self.__model.addVar(obj=1,name='U[%s,%s]' % (i, j))
        self.__model.update()
        
        for i,j in self.__links:
            for s,d in self.__links:
                R[i,j,s,d] = self.__model.addVar(obj=1,name='R[%s,%s,%s,%s]' % (i,j,s,d))
        self.__model.update()
        
        self.__model.modelSense = GRB.MINIMIZE
        #m.setObjective(quicksum([fixedCosts[p]*open[p] for p in plants]))
        self.__model.setObjective(quicksum(self.__BackupCapacity[i,j] for i,j in self.__links))
        self.__model.update()
        
           
        #------------------------------------------------------------------------#
        #                    Constraints definition                              #
        #                                                                        #
        #                                                                        #
        #------------------------------------------------------------------------#
         
        # Link capacity constraints
        for i,j in self.__links:
            self.__model.addConstr(self.__BackupCapacity[i,j] >= quicksum(self.__mean[s,d]*self.__bBackupLink[i,j,s,d] for (s,d) in self.__links) + U[i,j]*self.__invstd,'[CONST]Link_Cap_%s_%s' % (i, j))
        self.__model.update()
            
        # SCOP Reformulation Constraints
        for i,j in self.__links:
            self.__model.addConstr(quicksum(R[i,j,s,d]*R[i,j,s,d] for (s,d) in self.__links) <= U[i,j]*U[i,j],'[CONST]SCOP1[%s][%s]' % (i, j))
        self.__model.update()
            
        # SCOP Reformulation Constraints    
        for i,j in self.__links:
            for s,d in self.__links:
                self.__model.addConstr(self.__std[s,d]*self.__bBackupLink[i,j,s,d] == R[i,j,s,d],'[CONST]SCOP2[%s][%s][%s][%s]' % (i, j,s,d))
        self.__model.update()
        
        for i in self.__nodes:
            for s,d in self.__links:
                # Flow conservation constraints
                if i == s:
                    self.__model.addConstr(quicksum(self.__bBackupLink[i,j,s,d] for i,j in self.__links.select(i,'*')) - 
                                           quicksum(self.__bBackupLink[j,i,s,d] for j,i in self.__links.select('*',i)) == 1,'Flow1[%s,%s,%s,%s]' % (i,j,s, d))
                # Flow conservation constraints
                elif i == d:
                    self.__model.addConstr(quicksum(self.__bBackupLink[i,j,s,d] for i,j in self.__links.select(i,'*')) - 
                                           quicksum(self.__bBackupLink[j,i,s,d] for j,i in self.__links.select('*',i)) == -1,'Flow2[%s,%s,%s,%s]' % (i,j,s, d))
                # Flow conservation constraints
                else:    
                    self.__model.addConstr(quicksum(self.__bBackupLink[i,j,s,d] for i,j in self.__links.select(i,'*')) - 
                                           quicksum(self.__bBackupLink[j,i,s,d] for j,i in self.__links.select('*',i)) == 0,'Flow3[%s,%s,%s,%s]' % (i,j,s, d))
        self.__model.update()
                
        
    def optimize(self,MipGap, TimeLimit):
        
        self.__model.write('backup.lp')
        
        if MipGap != None:
            self.__model.params.timeLimit = TimeLimit
        if TimeLimit != None:
            self.__model.params.MIPGap = MipGap
         
        # Compute optimal solution
        self.__model.optimize()
        
        # Print solution
        if self.__model.status == GRB.Status.OPTIMAL:
            solution = self.__model.getAttr('x', self.__BackupCapacity)
            for i,j in self.__links:
                if solution[i,j] > 0:
                    print('%s -> %s: %g' % (i, j, solution[i,j]))
            
        else:
            print('Optimal value not found!\n')
            solution = []
            
        return solution;    
    
    def reset(self):
        '''
        Reset model solution
        '''
        self.__model.reset()
开发者ID:edielsonpf,项目名称:robust-network-optimization,代码行数:104,代码来源:NormalBackupModel.py

示例6: GurobiSolver

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]
class GurobiSolver(Solver):
    """ Implements the solver interface using gurobipy. """

    def __init__(self):
        Solver.__init__(self)
        self.problem = GurobiModel()
        

    def __getstate__(self):
        tmp_file = tempfile.mktemp(suffix=".lp")
        self.problem.update()
        self.problem.write(tmp_file)
        cplex_form = open(tmp_file).read()
        repr_dict = {'var_ids': self.var_ids, 'constr_ids': self.constr_ids, 'cplex_form': cplex_form}
        return repr_dict

    def __setstate__(self, repr_dict):
        tmp_file = tempfile.mktemp(suffix=".lp")
        open(tmp_file, 'w').write(repr_dict['cplex_form'])
        self.problem = read(tmp_file)
        self.var_ids = repr_dict['var_ids']
        self.constr_ids = repr_dict['constr_ids']

            
    def add_variable(self, var_id, lb=None, ub=None, vartype=VarType.CONTINUOUS, persistent=True, update_problem=True):
        """ Add a variable to the current problem.
        
        Arguments:
            var_id : str -- variable identifier
            lb : float -- lower bound
            ub : float -- upper bound
            vartype : VarType -- variable type (default: CONTINUOUS)
            persistent : bool -- if the variable should be reused for multiple calls (default: true)
            update_problem : bool -- update problem immediately (default: True)
        """
        lb = lb if lb is not None else -GRB.INFINITY
        ub = ub if ub is not None else GRB.INFINITY
        
        map_types = {VarType.BINARY: GRB.BINARY,
                     VarType.INTEGER: GRB.INTEGER,
                     VarType.CONTINUOUS: GRB.CONTINUOUS}

        if var_id in self.var_ids:
            var = self.problem.getVarByName(var_id)
            var.setAttr('lb', lb)
            var.setAttr('ub', ub)
            var.setAttr('vtype', map_types[vartype])
        else:
            self.problem.addVar(name=var_id, lb=lb, ub=ub, vtype=map_types[vartype])
            self.var_ids.append(var_id)
            
        if not persistent:
            self.temp_vars.add(var_id)
        
        if update_problem:
            self.problem.update()

    def add_constraint(self, constr_id, lhs, sense='=', rhs=0, persistent=True, update_problem=True):
        """ Add a variable to the current problem.
        
        Arguments:
            constr_id : str -- constraint identifier
            lhs : list [of (str, float)] -- variables and respective coefficients
            sense : {'<', '=', '>'} -- default '='
            rhs : float -- right-hand side of equation (default: 0)
            persistent : bool -- if the variable should be reused for multiple calls (default: True)
            update_problem : bool -- update problem immediately (default: True)
        """

        grb_sense = {'=': GRB.EQUAL,
                     '<': GRB.LESS_EQUAL,
                     '>': GRB.GREATER_EQUAL}

        if constr_id in self.constr_ids:
            constr = self.problem.getConstrByName(constr_id)
            self.problem.remove(constr)

        expr = quicksum([coeff * self.problem.getVarByName(r_id) for r_id, coeff in lhs if coeff])
        self.problem.addConstr(expr, grb_sense[sense], rhs, constr_id)
        self.constr_ids.append(constr_id)
            
        if not persistent:
            self.temp_constrs.add(constr_id)

        if update_problem:
            self.problem.update()
                                
    def remove_variable(self, var_id):
        """ Remove a variable from the current problem.
        
        Arguments:
            var_id : str -- variable identifier
        """
        if var_id in self.var_ids:
            self.problem.remove(self.problem.getVarByName(var_id))
            self.var_ids.remove(var_id)
    
    def remove_constraint(self, constr_id):
        """ Remove a constraint from the current problem.
        
#.........这里部分代码省略.........
开发者ID:willigott,项目名称:framed,代码行数:103,代码来源:gurobi_wrapper.py

示例7: __optmize_single_project

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]

#.........这里部分代码省略.........
        # y
        y = {}
        for activity_i in project_activities.nodes():
            for activity_j in project_activities.nodes():
                # print(project_activities.node[activity_i])
                # print(dir(project_activities.node[activity_i]))
                if activity_i != activity_j and len(list(
                        set(project_activities.node[activity_i]['rk_resources']).intersection(
                            project_activities.node[activity_j]['rk_resources']))) > 0:
                    y[activity_i, activity_j] = m.addVar(obj=0, vtype=GRB.BINARY,
                                                         name="(y%d,%s,%s)" % (j, activity_i, activity_j))
        m.update()

        #### Create constrains ####
        ## Constrain 2: project complete data>due data
        ## move to annealing objective function

        ## Constrain 3: supplier capacity limit
        ## move to annealing neighbor & random generator

        ## Constrain 4,6: project demand require; each project receive from one supplier for each resource
        ## move to annealing neighbor & random generator

        ## constrain 5: shipping constrain
        ## move to annealing neighbor & random generator

        ## Constrain 7:budget limit
        ## move to annealing constraint valid

        ## Constrain 8: activity starting constrain
        for a in project_activities.nodes():
            for r in project_activities.node[a]['resources']:
                resource_delivered_days = 0
                for s in self.resource_supplier_list[r]:
                    resource_delivered_days += x.get((r, s, project), 0) * \
                                               (self.resource_supplier_release_time[r, s] +
                                                self.supplier_project_shipping[
                                                    r, s, project])
                m.addConstr(resource_delivered_days, GRB.LESS_EQUAL, ST[a],
                            name="constraint_8_project_%d_activity_%s_resource_%s" % (j, a, r))

        ## Constrain 9 activity sequence constrain
        for row1, row2 in project_activities.edges():
            # print(row1, '#', row2, '#', j)
            # print(ST)
            m.addConstr(ST[row1] + project_activities.node[row1]['duration'], GRB.LESS_EQUAL,
                        ST[row2], name="constraint_9_project_%d_activity_%s_activity_%s" % (j, row1, row2))

        ## Constrain 10,11
        for row1 in project_activities.nodes():
            for row2 in project_activities.nodes():
                if row1 != row2 and len(list(
                        set(project_activities.node[row1]['rk_resources']).intersection(
                            project_activities.node[row2]['rk_resources']))) > 0:
                    m.addConstr(ST[row1] + project_activities.node[row1]['duration'] - self.M * (
                        1 - y[row1, row2]), GRB.LESS_EQUAL, ST[row2],
                                name="constraint_10_project_%d_activity_%s_activity_%s" % (j, row1, row2))
                    m.addConstr(
                        ST[row2] + project_activities.node[row2]['duration'] - self.M * (y[row1, row2]),
                        GRB.LESS_EQUAL, ST[row1],
                        name="constraint_11_project_%d_activity_%s_activity_%s" % (j, row1, row2))
                    # m.addConstr(y[j,row1,row2]+y[j,row2,row1],GRB.LESS_EQUAL,1)

        ## Constrain 12
        for row in project_activities.nodes():
            # print(project_activities.node[row]['duration'])
            m.addConstr(CT, GRB.GREATER_EQUAL, ST[row] + project_activities.node[row]['duration'],
                        name="constraint_12_project_%d_activity_%s" % (j, row))

        ## Constrain 13
        ## move to anealing objective function

        ## Constrain 14
        ## move to anealing objective function

        ## Constrain 15
        ## move to anealing objective function

        ## Constrain 16
        ## move to anealing objective function

        ## Constrain 17
        ## move to anealing objective function

        m.update()

        # Set optimization objective - minimize completion time
        expr = LinExpr()
        expr.add(CT)
        m.setObjective(expr, GRB.MINIMIZE)
        m.update()
        ##########################################
        m.params.presolve = 1
        m.update()
        # Solve
        # m.params.presolve=0
        m.optimize()
        m.write(join(self.output_dir, "heuristic_%d.lp" % j))
        m.write(join(self.output_dir, "heuristic_%d.sol" % j))
        return m.objVal
开发者ID:abucus,项目名称:zw_project,代码行数:104,代码来源:heuristic.py

示例8: __objective_function

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]
    def __objective_function(self, x, q):
        m = Model("Overall_Model")

        CT = {}
        DT = {}
        TD = {}

        #### Add Variable ####

        for j in range(self.project_n):
            ## solve individual model get Project complete date
            CT[j] = self.__optmize_single_project(x, j)

            ## Project Tadeness,construction completion time
            DT[j] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="(DT%d)" % j)
            TD[j] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="(TD%d)" % j)

        DT[-1] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="(DT-1)")

        ## Review Sequence z_ij
        z = {}
        for i in range(self.project_n):
            for j in range(self.project_n):
                if i != j:
                    z[i, j] = m.addVar(obj=0, vtype=GRB.BINARY, name="(z%d,%d)" % (i, j))

        for j in range(self.project_n):
            z[-1, j] = m.addVar(obj=0, vtype=GRB.BINARY, name="(z%d,%d)" % (-1, j))
        m.update();

        #### Add Constraint ####
        ## Constrain 2: project complete data>due data ##
        for j in range(self.project_n):
            m.addConstr(DT[j] - TD[j], GRB.LESS_EQUAL, self.DD[j], name="constraint_2_project_%d" % j)

        ## Constraint 13
        for j in range(self.project_n):
            m.addConstr(DT[j], GRB.GREATER_EQUAL, CT[j] + self.review_duration[j], name="constraint_13_project_%d" % j)

        ## Constraint 14
        for i in range(-1, self.project_n):
            for j in range(self.project_n):
                if i != j:
                    m.addConstr(DT[j], GRB.GREATER_EQUAL, DT[i] - self.M * (1 - z[i, j]) + self.review_duration[j],
                                name="constraint_14_project_%d_project_%d" % (i, j))

        ## Constrain 15
        for j in range(self.project_n):
            m.addConstr(quicksum(z[i, j] for i in range(-1, self.project_n) if i != j), GRB.EQUAL, 1,
                        name="constraint_15_project_%d" % j)

        ## Constrain 16
        m.addConstr(quicksum(z[-1, j] for j in range(self.project_n)), GRB.EQUAL, 1, name="constraint_16")

        ## Constrain 17
        for i in range(self.project_n):
            m.addConstr(quicksum(z[i, j] for j in range(self.project_n) if j != i), GRB.LESS_EQUAL, 1,
                        name="constraint_17_project_%d" % i)
        m.update()

        # Set optimization objective - minimize sum of
        expr = LinExpr()
        for j in range(self.project_n):
            expr.add(self.w[j] * TD[j])
        m.setObjective(expr, GRB.MINIMIZE)
        m.update()

        m.params.presolve = 1
        m.update()

        m.optimize()
        m.write(join(self.output_dir, "heuristic_whole.lp"))
        m.write(join(self.output_dir, "heuristic_whole.sol"))
        print([self.w[j] * TD[j].X for j in range(self.project_n)])
        return m.objVal, argmax([self.w[j] * TD[j].X for j in range(self.project_n)])
开发者ID:abucus,项目名称:zw_project,代码行数:77,代码来源:heuristic.py

示例9: __objective_function

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]
    def __objective_function(self, x, q, p_changed=None):
        m = Model("Overall_Model")

        if p_changed is not None:
            j0 = self.project_list.index(p_changed)
            CT = self.last_CT
            CT[j0] = self.optmize_single_project(x, j0, self.project_list, self.project_activity,
                                                 self.resource_supplier_list,
                                                 self.resource_supplier_release_time, self.supplier_project_shipping,
                                                 self.M,
                                                 self.output_dir)
        else:
            CT = {}
            CT_ASYNC = dict()
            for j in range(self.project_n):
                ## solve individual model get Project complete date
                CT_ASYNC[j] = self.pool.apply_async(HeuristicParallelModel.optmize_single_project,
                                                    (x, j, self.project_list, self.project_activity,
                                                     self.resource_supplier_list,
                                                     self.resource_supplier_release_time,
                                                     self.supplier_project_shipping,
                                                     self.M,
                                                     self.output_dir))
            for j in range(self.project_n):
                CT[j] = CT_ASYNC[j].get()

        self.last_CT = deepcopy(CT)
        DT = {}
        TD = {}
        for j in range(self.project_n):
            ## Project Tadeness,construction completion time
            DT[j] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="(DT%d)" % j)
            TD[j] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="(TD%d)" % j)

        DT[-1] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="(DT-1)")

        ## Review Sequence z_ij
        z = {}
        for i in range(self.project_n):
            for j in range(self.project_n):
                if i != j:
                    z[i, j] = m.addVar(obj=0, vtype=GRB.BINARY, name="(z%d,%d)" % (i, j))

        for j in range(self.project_n):
            z[-1, j] = m.addVar(obj=0, vtype=GRB.BINARY, name="(z%d,%d)" % (-1, j))
        m.update();

        #### Add Constraint ####
        ## Constrain 2: project complete data>due data ##
        for j in range(self.project_n):
            m.addConstr(DT[j] - TD[j], GRB.LESS_EQUAL, self.DD[j], name="constraint_2_project_%d" % j)

        ## Constraint 13
        for j in range(self.project_n):
            m.addConstr(DT[j], GRB.GREATER_EQUAL, CT[j] + self.review_duration[j], name="constraint_13_project_%d" % j)

        ## Constraint 14
        for i in range(-1, self.project_n):
            for j in range(self.project_n):
                if i != j:
                    m.addConstr(DT[j], GRB.GREATER_EQUAL, DT[i] - self.M * (1 - z[i, j]) + self.review_duration[j],
                                name="constraint_14_project_%d_project_%d" % (i, j))

        ## Constrain 15
        for j in range(self.project_n):
            m.addConstr(quicksum(z[i, j] for i in range(-1, self.project_n) if i != j), GRB.EQUAL, 1,
                        name="constraint_15_project_%d" % j)

        ## Constrain 16
        m.addConstr(quicksum(z[-1, j] for j in range(self.project_n)), GRB.EQUAL, 1, name="constraint_16")

        ## Constrain 17
        for i in range(self.project_n):
            m.addConstr(quicksum(z[i, j] for j in range(self.project_n) if j != i), GRB.LESS_EQUAL, 1,
                        name="constraint_17_project_%d" % i)
        m.update()

        # Set optimization objective - minimize sum of
        expr = LinExpr()
        for j in range(self.project_n):
            expr.add(self.w[j] * TD[j])
        m.setObjective(expr, GRB.MINIMIZE)
        m.update()

        m.params.presolve = 1
        m.update()

        m.optimize()
        m.write(join(self.output_dir, "heuristic_whole.lp"))
        m.write(join(self.output_dir, "heuristic_whole.sol"))

        self.obj_value_trace.append(m.objVal)
        return m.objVal, argmax([self.w[j] * TD[j].X for j in range(self.project_n)])
开发者ID:abucus,项目名称:zw_project,代码行数:95,代码来源:heuristic_parallel.py

示例10: SQModel

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]
class SQModel(object):
    '''
    classdocs
    '''
    # Private model object
    __model = []
         
    # Private model variables
    __z0 = {}
    __z = {}
    __q = {}
         
    # Private model parameters
    __BackupCapacity = {}
    __bBackupLink = {}
    __links = []
    __nodes = []
    __capacity = []
    __epsilon = 1
    __impSample = {}
    __N = 1
        
    def __init__(self,imp_samp,nodes,links,capacity,epsilon,N,backup_link,link_capacity):
        '''
        Constructor
        '''
        self.__links = links
        self.__nodes = nodes
        self.__capacity = capacity
        self.__epsilon = epsilon
        self.__N = N
        self.__loadModel(imp_samp,backup_link,link_capacity)
                                 
    def __loadModel(self,imp_samp, backup_link,link_capacity):
                 
        # Create optimization model
        self.__model = Model('Backup')
     
        for i,j in self.__links:
            for k in range(self.__N):
                self.__z[k,i,j] = self.__model.addVar(lb=0,name='z[%s][%s][%s]' % (k,i,j))
        self.__model.update()
        
        for i,j in self.__links: 
            self.__z0[i,j] = self.__model.addVar(lb=-GRB.INFINITY,name='z0[%s][%s]' %(i,j))
        self.__model.update()
         
        for i,j in self.__links: 
            self.__q[i,j] = self.__model.addVar(lb=-GRB.INFINITY,name='q[%s][%s]' %(i,j))
        self.__model.update()
        
        self.__model.modelSense = GRB.MINIMIZE
        
        self.__model.setObjective(quicksum(self.__q[i,j] for i,j in self.__links))
        
        self.__model.update()
         
            
        #------------------------------------------------------------------------#
        #                    Constraints definition                              #
        #                                                                        #
        #                                                                        #
        #------------------------------------------------------------------------#
          
        # Buffer probability I
        for i,j in self.__links:
            self.__model.addConstr(self.__z0[i,j] + 1/(self.__N*self.__epsilon)*quicksum(self.__z[k,i,j]*imp_samp[k] for (k) in range(self.__N)) <= self.__q[i,j],'[CONST]Buffer_Prob_I[%s][%s]'%(i,j))
        self.__model.update()
         
        # Link capacity constraints
        for i,j in self.__links:
            for k in range(self.__N):
                self.__model.addConstr((quicksum(backup_link[i,j,s,d]*self.__capacity[k,s,d] for s,d in self.__links) - link_capacity[i,j] - self.__z0[i,j]) <= self.__z[k,i,j],'[CONST]Buffer_Prob_II[%s][%s][%s]' % (k,i,j))
        self.__model.update()
        
        # Link capacity constraints
        for i,j in self.__links:
            for k in range(self.__N):
                self.__model.addConstr(self.__z[k,i,j] >= 0,'[CONST]Buffer_Prob_III[%s][%s][%s]' % (k,i,j))
        self.__model.update()
         
    def optimize(self,MipGap, TimeLimit, LogLevel = None):
         
        self.__model.write('quantile.lp')
         
        if MipGap != None:
            self.__model.params.MIPGap = MipGap
        if TimeLimit != None:
            self.__model.params.timeLimit = TimeLimit
        # Compute optimal solution
        self.__model.optimize()
         
        # Print solution
        if self.__model.status == GRB.Status.OPTIMAL:
            #SuperQuantileSolution = self.__model.getAttr('x', self.__z0)
            SuperQuantileSolution = {}
            OptimalZnot = {}
            for i,j in self.__links:
                name='q[%s][%s]'%(i,j)
                v = self.__model.getVarByName(name)
#.........这里部分代码省略.........
开发者ID:edielsonpf,项目名称:robust-network-optimization,代码行数:103,代码来源:SuperquantileModel.py

示例11: createModel

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]
    def createModel(self):
        w = {}
        self.y = {}
        
        m = Model("Optimization Model")
        
        #part of 6a -- create w variables
        for n in range(1,self.nScenario+1):
            for k in range(1,self.numberOfFinancialAsstValues+1): #I'm not sure how the "paramDF" file will be structured--this is temporary
                for j in range(1,self.nOwners+1):
                    w[j, k, n] = m.addVar(vtype=GRB.CONTINUOUS, name="w_"+str(j)+"_"+str(k)+"_"+str(n))   

        #Constraint 6f
        for k in range(1,self.numberOfFinancialAsstValues+1):
            for j in range(1,self.nOwners+1):
                self.y[j, k] = m.addVar(vtype=GRB.BINARY, name="y_"+str(j)+"_"+str(k))

        m.update()
        
        #6a continued
        #for k in range(1,self.numberOfFinancialAsstValues+1):
        #6a updated
        for n in range(1,self.nScenario+1):
            m.addConstr(quicksum(w[1,k,n] for k in range(1,self.numberOfFinancialAsstValues+1)) == self.SecondStgValues[n-1]*quicksum(self.DecisionProb[n,1,k]*self.y[1, k] for k in range(1,self.numberOfFinancialAsstValues+1)), name = "6a_1_"+str(n))
        #        w[1,k,n] = self.SecondStgValues[n-1]
        
        #6b updated
        for r in range(2,self.nOwners+1):
            for n in range(1,self.nScenario+1):
                #if self.ProbDict["("+str(n)+", 1, 0, "+str(k)+")"] > 0:
        #        for self.ProbDict["("+str(n)+", 1, 0, "+str(k)+")"] > 0:
                    m.addConstr(quicksum(w[r-1,k,n] for k in range(1,self.numberOfFinancialAsstValues+1)) == quicksum(w[r,k,n]*(1/self.DecisionProb[n,r,k]) for k in range(1,self.numberOfFinancialAsstValues+1)), name = "6b_"+str(r)+"_"+str(n))
                #if self.ProbDict["("+str(n)+", 1, 1, "+str(k)+")"] > 0:
                #    m.addConstr(quicksum(w[r-1,k,n] for k in range(1,self.numberOfFinancialAsstValues+1)) == quicksum(w[r,k,n]*(1/self.ProbDict["("+str(n)+", 1, 1, "+str(k)+")"]) for k in range(1,self.numberOfFinancialAsstValues+1)), name = "6b_"+str(r)+"_"+str(n))

        #6b
        #for r in range(2, self.nOwners+1):
        #    for n in range(1,self.nScenario+1):
        #        m.addConstr(quicksum(quicksum(self.ProbDict["("+str(n)+", "+str(r-1)+", "+str(l)+", "+str(k)+")"]*w[r-1,k,n] for l in (0,1))
        #                             for k in range(1,self.numberOfFinancialAsstValues+1)) == quicksum(w[r, k, n] for k in range(1,self.numberOfFinancialAsstValues+1)), name = "6b_"+str(r)+"_"+str(n))
        
        #for n in range(1,self.nScenario+1):
        #    m.addConstr(quicksum(w[r, k, n] for k in range(1,self.numberOfFinancialAsstValues+1)), name = "6b_"+str(r)+"_"+str(n))
        
        
        #for k in range(1,self.numberOfFinancialAsstValues+1):
        #    for r in range(2, self.ownerNums+2):
        #        for n in range(1,self.nScenario+1):
        #            for l in (0,1):
        #                m.addConstr(quicksum(quicksum(self.ProbDict["("+str(n)+", "+str(r-1)+", "+str(l)+", "+str(k)+")"]*w[r-1,k,n]) == quicksum(w[r, k, n]),
        #                                     name = "6b_"+str(r)+"_"+str(k)+"_"+str(n)))
                
                
        #6c
        #Not sure if this is the proper formatting for this constraint
        #Is this the proper use of self.SecondStgValues?
        #for n in range(1,self.nScenario +1):
        #    for k in range(1,self.numberOfFinancialAsstValues+1): #I'm not sure how the "paramDF" file will be structured--this is temporary
        #        for r in range(1,self.ownerNums+2):
        #6c updated            
        for k in range(1,self.numberOfFinancialAsstValues+1):
            for r in range(1, self.nOwners+1):
                for n in range(1,self.nScenario+1):
                    m.addConstr(w[r, k, n] <= self.y[r, k]*self.SecondStgValues[n-1], name = "6c_"+str(r)+"_"+str(k)+"_"+str(n))
                    #print str(r)+"_"+str(k)+"_"+str(n)
                                
                                
                                #for r in range(1, self.ownerNums+2) for k in range(1,self.numberOfFinancialAsstValues+1) for n in range(1,self.nScenario+1))
        
        #Constraint 6d
        #the sum of the financial assistance offered to all landowners is less than or equal to the agency's budget
        #Where does C come from?
        m.addConstr(quicksum(quicksum(self.C_k[k-1]*self.y[j, k] for k in range(1,self.numberOfFinancialAsstValues+1))for j in range(1,self.nOwners+1)) <= self.Budget_param, name = "6d")
        
        #Constraint 6e
        for j in range(1,self.nOwners+1):
            m.addConstr(quicksum(self.y[j, k] for k in range(1,self.numberOfFinancialAsstValues+1)) == 1, name = "6e_"+str(j))
                        
        m.update()
                                              
        #set objective
        lastLandownerIndex = self.nOwners
        
        m.setObjective(quicksum(quicksum(w[lastLandownerIndex, k, n] for k in range(1,self.numberOfFinancialAsstValues+1)) for n in range(1,self.nScenario+1)), GRB.MINIMIZE)        

        m.update()
        
        m.optimize()
        
        if m.status == GRB.Status.OPTIMAL:
            print ('\nOBJECTIVE VALUE: %g' % m.objVal)
            
        for v in m.getVars():
            print('%s %g' % (v.varName, v.x))
       
        m.write('toy results.lp')
        
        return m
开发者ID:hmedal,项目名称:fireopt,代码行数:100,代码来源:toy_optmodel.py

示例12: _objective_function_for_tardiness

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]
def _objective_function_for_tardiness(x, AT, D):
    global _last_CT, _last_x, _pool, _time_limit_per_model
    m = Model("Overall_Model")
    m.params.timelimit = _time_limit_per_model
    # m.setParam('OutputFlag', False)
    # m.params.IntFeasTol = 1e-7

    CT = {}
    # CT_ASYNC = dict()
    # project_to_recompute, project_no_recompute = get_project_to_recompute(x, D.project_n, D.project_list)
    project_suppliers = _get_project_suppliers_map(x, D.project_list)
    critical_project_resource = dict()
    # for j in range(D.project_n):
    #     p = D.project_list[j]
    #     CT_ASYNC[j] = _pool.apply_async(optimize_single_project,
    #                                     (AT, j, D.project_list, D.project_activity, D.M))
    #
    # for j in CT_ASYNC:
    #     p = D.project_list[j]
    #     CT[j], skj = CT_ASYNC[j].get()
    #     _put_CT(p, project_suppliers[p], CT[j])
    #     _put_historical_delta_weight_idx_map(p, project_suppliers[p], skj)
    #     critical_project_resource.update(skj)

    for j in range(D.project_n):
        p = D.project_list[j]
        CT[j], skj = optimize_single_project(AT, j, D.project_list, D.project_activity, D.M)
        _put_CT(p, project_suppliers[p], CT[j])
        _put_historical_delta_weight_idx_map(p, project_suppliers[p], skj)
        critical_project_resource.update(skj)

    DT = {}
    TD = {}
    for j in range(D.project_n):
        ## Project Tadeness,construction completion time
        DT[j] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="DT_%d" % j)
        TD[j] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="TD_%d" % j)

    DT[-1] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="DT_-1")

    ## Review Sequence z_ij
    z = {}
    for i in range(D.project_n):
        for j in range(D.project_n):
            if i != j:
                z[i, j] = m.addVar(obj=0, vtype=GRB.BINARY, name="z_%d_%d" % (i, j))

    for j in range(D.project_n):
        z[-1, j] = m.addVar(obj=0, vtype=GRB.BINARY, name="z_%d_%d" % (-1, j))
    m.update();

    #### Add Constraint ####
    ## Constrain 2: project complete data>due data ##
    # equation 17
    for j in range(D.project_n):
        m.addConstr(DT[j] - TD[j], GRB.LESS_EQUAL, D.DD[j], name="constraint_2_project_%d" % j)

    ## Constraint 13
    # equation 12
    for j in range(D.project_n):
        m.addConstr(DT[j], GRB.GREATER_EQUAL, CT[j] + D.review_duration[j],
                    name="constraint_13_project_%d" % j)

    ## Constraint 14
    # equation 13
    for i in range(-1, D.project_n):
        for j in range(D.project_n):
            if i != j:
                m.addConstr(DT[j], GRB.GREATER_EQUAL, DT[i] - D.M * (1 - z[i, j]) + D.review_duration[j],
                            name="constraint_14_project_%d_project_%d" % (i, j))

    ## Constrain 15
    # equation 14
    for j in range(D.project_n):
        m.addConstr(quicksum(z[i, j] for i in range(-1, D.project_n) if i != j), GRB.EQUAL, 1,
                    name="constraint_15_project_%d" % j)

    ## Constrain 16
    # equation 15
    m.addConstr(quicksum(z[-1, j] for j in range(D.project_n)), GRB.EQUAL, 1, name="constraint_16")

    ## Constrain 17
    # equation 16
    for i in range(D.project_n):
        m.addConstr(quicksum(z[i, j] for j in range(D.project_n) if j != i), GRB.LESS_EQUAL, 1,
                    name="constraint_17_project_%d" % i)
    m.update()

    # Set optimization objective - minimize sum of
    expr = LinExpr()
    for j in range(D.project_n):
        expr.add(D.w[j] * TD[j])
    m.setObjective(expr, GRB.MINIMIZE)
    m.update()

    # m.params.presolve = 1
    m.update()

    m.optimize()
    m.write(join(_result_output_path, 'round_%d_tardiness.sol' % _round))
#.........这里部分代码省略.........
开发者ID:abucus,项目名称:zw_project,代码行数:103,代码来源:heuristic_delta_weight.py

示例13: optimize_single_project

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]
def optimize_single_project(AT, j, project_list, project_activity, M):
    global _time_limit_per_model
    m = Model("SingleProject_%d" % j)
    m.params.timelimit = _time_limit_per_model
    # m.setParam('OutputFlag', False)
    # m.params.IntFeasTol = 1e-7

    #### Create variables ####
    project = project_list[j]

    ## Project complete data,Project Tadeness,construction completion time
    CT = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="CT_%d" % j)

    ## Activity start time
    ST = {}
    project_activities = project_activity[project]
    for row in project_activities.nodes():
        ST[row] = m.addVar(obj=0, vtype=GRB.CONTINUOUS, name="ST_%d_%s" % (j, row))

    ## Review sequence z_ij
    ## move to annealing objective function

    # y
    y = {}
    for activity_i in project_activities.nodes():
        for activity_j in project_activities.nodes():
            if activity_i != activity_j and len(list(
                    set(project_activities.node[activity_i]['rk_resources']).intersection(
                        project_activities.node[activity_j]['rk_resources']))) > 0:
                y[activity_i, activity_j] = m.addVar(obj=0, vtype=GRB.BINARY,
                                                     name="y_%d_%s_%s" % (j, activity_i, activity_j))
    m.update()

    ## Constrain 8: activity starting constrain
    # equation 20
    for a in project_activities.nodes():
        for r in project_activities.node[a]['resources']:
            m.addConstr(AT[j, r], GRB.LESS_EQUAL, ST[a],
                        name="constraint_8_project_%d_activity_%s_resource_%s" % (j, a, r))

    ## Constrain 9 activity sequence constrain
    # equation 21
    for row1, row2 in project_activities.edges():
        m.addConstr(ST[row1] + project_activities.node[row1]['duration'], GRB.LESS_EQUAL,
                    ST[row2], name="constraint_9_project_%d_activity_%s_activity_%s" % (j, row1, row2))

    ## Constrain 10,11
    for row1 in project_activities.nodes():
        for row2 in project_activities.nodes():
            if row1 != row2 and len(list(
                    set(project_activities.node[row1]['rk_resources']).intersection(
                        project_activities.node[row2]['rk_resources']))) > 0:
                # equation 22
                m.addConstr(ST[row1] + project_activities.node[row1]['duration'] - M * (
                    1 - y[row1, row2]), GRB.LESS_EQUAL, ST[row2],
                            name="constraint_10_project_%d_activity_%s_activity_%s" % (j, row1, row2))
                # equation 23
                m.addConstr(
                    ST[row2] + project_activities.node[row2]['duration'] - M * (y[row1, row2]),
                    GRB.LESS_EQUAL, ST[row1],
                    name="constraint_11_project_%d_activity_%s_activity_%s" % (j, row1, row2))
                # m.addConstr(y[j,row1,row2]+y[j,row2,row1],GRB.LESS_EQUAL,1)

    ## Constrain 12
    # equation 24
    for row in project_activities.nodes():
        m.addConstr(CT, GRB.GREATER_EQUAL, ST[row] + project_activities.node[row]['duration'],
                    name="constraint_12_project_%d_activity_%s" % (j, row))

    m.update()

    # Set optimization objective - minimize completion time
    expr = LinExpr()
    expr.add(CT)
    m.setObjective(expr, GRB.MINIMIZE)
    m.update()
    ##########################################
    # m.params.presolve = 1
    m.update()
    # Solve
    # m.params.presolve=0

    m.optimize()
    m.write(join(_result_output_path, "round_%d_optimize_single_project_%d.lp" % (_round, j)))
    m.write(join(_result_output_path, "round_%d_optimize_single_project_%d.sol" % (_round, j)))
    # _logger.info("project %d with optimalVal %r" % (j, m.objVal))
    # m.fixedModel()

    skj = _sensitivity_for_constraints(AT, j, project, y, project_activity, M)
    # for c in m.getConstrs():
    #     if c.ConstrName.startswith('constraint_8_project'):
    #         splits = c.ConstrName.split('_')
    #         if c.Pi == 0:
    #             _logger.info('project %d bind resource:%s Slack:%.4g'%(j, splits[-1],c.Pi))
    #             break
    # else:
    #     _logger.info('project %d not bind'%j)
    _single_project_objective_dataset.loc[_single_project_objective_dataset.shape[0]] = [_round, j, m.objVal]
    return m.objVal, skj
开发者ID:abucus,项目名称:zw_project,代码行数:101,代码来源:heuristic_delta_weight.py

示例14: _objective_function_for_delta_weight

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]
def _objective_function_for_delta_weight(D, delta_weight, d1, d2):
    global _time_limit_per_model, _round, _pr_dataset, _tardiness_objective_dataset
    m = Model("model_for_supplier_assignment")
    m.setParam('OutputFlag', False)
    m.params.timelimit = _time_limit_per_model
    # m.params.IntFeasTol = 1e-7
    x = {}
    q = {}
    for (r, s, p) in D.supplier_project_shipping:
        x[r, s, p] = m.addVar(vtype=GRB.BINARY, name="x_%s_%s_%s" % (r, s, p))
        q[r, s, p] = m.addVar(vtype=GRB.CONTINUOUS, name="q_%s_%s_%s" % (r, s, p))

    AT = {}
    for j in range(D.project_n):
        for k in [r for r, p in D.resource_project_demand if p == D.project_list[j]]:
            AT[j, k] = m.addVar(vtype=GRB.CONTINUOUS, name="AT_%s_%s" % (j, k))
    m.update()

    ## define constraints
    # equation 2
    for (r, s) in D.resource_supplier_capacity:
        m.addConstr(quicksum(q[r, s, D.project_list[j]] for j in range(D.project_n)), GRB.LESS_EQUAL,
                    D.resource_supplier_capacity[r, s],
                    name="constraint_3_resource_%s_supplier_%s" % (r, s))

    # constraint 21(4) 23(6)
    for (r, p) in D.resource_project_demand:
        # equation 5
        m.addConstr(quicksum(x[r, i, p] for i in D.resource_supplier_list[r]), GRB.EQUAL, 1,
                    name="constraint_6_resource_%s_project_%s" % (r, p))
        # equation 3
        m.addConstr(quicksum(q[r, i, p] for i in D.resource_supplier_list[r]), GRB.GREATER_EQUAL,
                    D.resource_project_demand[r, p], name="constraint_4_resource_%s_project_%s" % (r, p))

    # constraint 22(5)
    for (i, j, k) in q:
        # i resource, j supplier, k project
        # equation 4
        m.addConstr(q[i, j, k], GRB.LESS_EQUAL, D.M * x[i, j, k],
                    name="constraint_5_resource_%s_supplier_%s_project_%s" % (i, j, k))
    # constraint 7
    shipping_cost_expr = LinExpr()
    for (i, j, k) in q:
        shipping_cost_expr.addTerms(D.c[i, j, k], q[i, j, k])
    # equation 6
    m.addConstr(shipping_cost_expr, GRB.LESS_EQUAL, D.B, name="constraint_7")

    # constraint 8
    # equation 26
    for j in range(D.project_n):
        p = D.project_list[j]
        project_resources = [r for (r, p_) in D.resource_project_demand.keys() if p_ == p]
        for r in project_resources:
            suppliers = D.resource_supplier_list[r]
            m.addConstr(
                quicksum(
                    x[r, s, p] * (D.resource_supplier_release_time[r, s] + D.supplier_project_shipping[r, s, p]) for
                    s in
                    suppliers), GRB.LESS_EQUAL, AT[j, r],
                name="constraint_8_project_%d_resource_%s_deliver" % (j, r))
    m.update()

    expr = LinExpr()
    for j in range(D.project_n):
        p = D.project_list[j]
        for r in [r for (r, p_) in D.resource_project_demand.keys() if p_ == p]:
            expr.add(delta_weight[j, r] * AT[j, r])
    m.setObjective(expr, GRB.MINIMIZE)
    m.update()
    ##########################################
    # m.params.presolve = 1
    m.update()
    # Solve
    # m.params.presolve=0
    m.optimize()
    _exit_if_infeasible(m)
    m.write(join(_result_output_path, "round_%d_supplier_assign.lp" % _round))
    m.write(join(_result_output_path, "round_%d_supplier_assign.sol" % _round))
    with open(join(log_output_path, 'shipping_cost.txt'), 'a') as fout:
        fout.write('shipping cost: %f\n' % shipping_cost_expr.getValue())
    _logger.info('shipping cost: %f' % shipping_cost_expr.getValue())

    print('status', m.status)
    # m.write(join(_output_path, 'delta_weight.sol'))
    # m.write(join(_output_path, 'delta_weight.lp'))
    X_ = {}
    for (i, j, k) in D.supplier_project_shipping:
        v = m.getVarByName("x_%s_%s_%s" % (i, j, k))
        if v.X == 1:
            X_[i, j, k] = 1

    AT_ = {}
    for j, r in AT:
        val = AT[j, r].X
        if val > 0:
            AT_[j, r] = val

    tardiness_obj_val, skj, sj = _objective_function_for_tardiness(X_, AT_, D)
    new_delta_weight = {}
    # delta_weight_keys = list(delta_weight.keys())
#.........这里部分代码省略.........
开发者ID:abucus,项目名称:zw_project,代码行数:103,代码来源:heuristic_delta_weight.py

示例15: __init__

# 需要导入模块: from gurobipy import Model [as 别名]
# 或者: from gurobipy.Model import write [as 别名]
class HarmonyModel:

    def __init__(self, length):

        """Initialize model, note and chord variables, and constraints for notes
        and chord constraints."""

        self.model = Model("harmony")
        self.length = length

        config = load_source("config",
                join(abspath(dirname(__file__)), "config.py"))

        config.length = self.length

        config.model = self.model

        self.notes = Notes(config)
        config.notes = self.notes

        self.chords = Chords(config)


    def ensure_melody(self, melody):

        """Ensure that the four-part harmony has a complete or partial melody as
        its soprano line."""

        for t, note in enumerate(melody):

            if not note:
                continue

            constraint = self.notes[denote(note), 3, t] == 1

            self.model.addConstr(constraint,
                "melody_t" + str(t))

            self.model.update()


    def ensure_harmony(self, harmony):

        """Ensure that the four-part harmony uses certain chords (and the
        correct inversion) at each time step."""

        for t, chord in enumerate(harmony):

            if not chord:
                continue

            for c in self.chords.chord_notes.keys():

                if c == chord:
                    continue

                for d in self.chords.chord_doublings[c]:

                    constraint = self.chords[c, d, t] == 0

                    self.model.addConstr(constraint,
                        "harmony_c" + c + "_d" + str(d) + "_t" + str(t))

            self.model.update()


    def write(self):

        """Write out LP file of generated model (for debugging)."""

        self.model.write("model.lp")


    def solve(self):

        """Solve the model and provide the solution's notes (x variables) and
        chords (y variables)."""

        self.model.optimize()

        self.solution = []

        try:

            for var in self.model.getVars():
                if var.x == 1 and var.varName[0] in {"x", "y"}:
                    self.solution.append(var.varName)

            return self.solution

        except:

            return []
        

    def lilypond_export(self):

        """Return a Lilypond file to generate a human-readable score based on
        the IP solution."""

#.........这里部分代码省略.........
开发者ID:grusky,项目名称:music-optimization,代码行数:103,代码来源:harmony.py


注:本文中的gurobipy.Model.write方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。