Ejemplo n.º 1
0
	def solve(self,msg=0,**kwarg):
		# kind = 'CBC'
		if 'kind' in kwarg:
			kind = kwarg['kind']
		time_limit = None
		if 'time_limit' in kwarg:
			time_limit = float(kwarg['time_limit'])
		random_seed = None
		if 'random_seed' in kwarg:
			random_seed = kwarg['random_seed']
		ratio_gap = None
		if 'ratio_gap' in kwarg:
			ratio_gap = float(kwarg['ratio_gap'])
		start_time = time.time()
		# select solver for pl
		if kind == 'CPLEX':
			if time_limit is not None:
				# pulp does currently not support a timelimit in 1.5.9
				self.mip.solve(pl.CPLEX_CMD(msg=msg, timelimit=time_limit))
			else:
				self.mip.solve(pl.CPLEX_CMD(msg=msg))
		elif kind == 'GLPK':
			self.mip.solve(pl.GLPK_CMD(msg=msg))
		elif kind == 'SCIP':
			self.mip.solve(SCIP_CMD(msg=msg,time_limit=time_limit,ratio_gap=ratio_gap))
		elif kind == 'CBC' or kind == 'COIN':
			options = []
			if time_limit is not None:
				options.extend(['sec', str(time_limit)])
			if random_seed is not None:
				options.extend(['randomSeed', str(random_seed)])
				options.extend(['randomCbcSeed', str(random_seed)])
			if ratio_gap is not None:
				options.extend(['ratio', str(ratio_gap)])
			if kind == 'CBC':
				self.mip.solve(pl.PULP_CBC_CMD(msg=msg, options=options))
			elif kind == 'COIN':
				self.mip.solve(pl.COIN(msg=msg, options=options))
		elif kind == 'GUROBI':
			# GUROBI_CMD does not support a timelimit or epgap
			# GUROBI cannot dispatch parameters from options correctly
			options=[]
			if time_limit is not None:
				if ratio_gap is not None:
					self.mip.solve(pl.GUROBI(msg=msg,timeLimit=time_limit,epgap=ratio_gap))
			elif time_limit is not None:
				self.mip.solve(pl.GUROBI(msg=msg, timeLimit=time_limit))
			elif ratio_gap is not None:
				self.mip.solve(pl.GUROBI(msg=msg, epgap=ratio_gap))
			else:
				self.mip.solve(pl.GUROBI_CMD(msg=msg))

		else:
			raise Exception('ERROR: solver ' + kind + ' not known')

		if msg:
			print('INFO: execution time for solving mip (sec) = ' + str(time.time() - start_time))
		if self.mip.status == 1 and msg:
			print('INFO: objective = ' + str(pl.value(self.mip.objective)))
Ejemplo n.º 2
0
 def test_threshold(self):
     threshold = covering.create_threshold_model(
         self.binary_coverage_point2, 30)
     threshold_i = covering.create_threshold_model(
         self.binary_coverage_point2, 100)
     threshold.solve(pulp.GUROBI())
     threshold_i.solve(pulp.GUROBI())
     ids = utilities.get_ids(threshold, "facility2_service_areas")
     self.assertEqual(['10', '20', '4'], ids)
     self.assertEqual(threshold_i.status, pulp.constants.LpStatusInfeasible)
Ejemplo n.º 3
0
 def test_traumah(self):
     traumah = covering.create_traumah_model(self.traumah_coverage, 5, 10)
     traumah_i = covering.create_traumah_model(self.traumah_coverage, 100,
                                               100)
     traumah.solve(pulp.GUROBI())
     traumah_i.solve(pulp.GUROBI())
     ad_ids = utilities.get_ids(traumah, "AirDepot")
     tc_ids = utilities.get_ids(traumah, "TraumaCenter")
     self.assertEqual(['0', '1', '2', '4', '5'], ad_ids)
     self.assertEqual(
         ['10', '12', '15', '16', '18', '19', '21', '22', '7', '9'], tc_ids)
     self.assertEqual(traumah_i.status, pulp.constants.LpStatusInfeasible)
Ejemplo n.º 4
0
 def test_cc_threshold(self):
     ccthreshold = covering.create_cc_threshold_model(
         self.partial_coverage2, 80)
     ccthreshold_i = covering.create_cc_threshold_model(
         self.partial_coverage2, 100)
     ccthreshold.solve(pulp.GUROBI())
     ccthreshold_i.solve(pulp.GUROBI())
     ids = utilities.get_ids(ccthreshold, "facility2_service_areas")
     self.assertEqual([
         '1', '10', '11', '13', '15', '17', '19', '20', '21', '22', '3',
         '4', '7', '9'
     ], ids)
     self.assertEqual(ccthreshold_i.status,
                      pulp.constants.LpStatusInfeasible)
Ejemplo n.º 5
0
def convexCombination(points, point):
    '''Calculates if a point is a convex combination of another points in the
    hull, this is done to avoid unecessary point in the hull calculation.
    '''
    points_idx = [i for i in range(len(points))]
    dim_idx = [j for j in range(len(point))]
    prob = lp.LpProblem("max mean", lp.LpMinimize)

    alpha = list(
        lp.LpVariable.dicts('alpha', points_idx, cat='Continuous').values())

    for j in dim_idx:
        prob += (lp.lpSum([alpha[i] * points[i][j]
                           for i in points_idx]) == point[j])

    prob += lp.lpSum([alpha[i] for i in points_idx]) == 1

    for i in points_idx:
        if all(points[i] == point):
            prob += alpha[i] == 0
        else:
            prob += alpha[i] >= 0

    grbs = lp.GUROBI(msg=False, OutputFlag=False, Threads=1)
    if grbs.available():
        prob.solve(grbs)
    else:
        cbcs = lp.PULP_CBC_CMD(threads=1)
        prob.solve(cbcs, use_mps=False)

    feasible = False if prob.status in [-1, -2] else True
    return feasible
Ejemplo n.º 6
0
 def _solve(self):
     if self.solver == "cbc":
         self.prob.solve(
             pulp.PULP_CBC_CMD(
                 msg=0,
                 maxSeconds=self.time_limit,
                 options=["startalg", "barrier", "crossover", "0"],
             ))
     elif self.solver == "cplex":
         self.prob.solve(
             pulp.CPLEX_CMD(
                 msg=0,
                 timelimit=self.time_limit,
                 options=["set lpmethod 4", "set barrier crossover -1"],
             ))
     elif self.solver == "gurobi":
         gurobi_options = [
             ("Method", 2),  # 2 = barrier
             ("Crossover", 0),
         ]
         # Only specify time limit if given (o.w. errors)
         if self.time_limit is not None:
             gurobi_options.append((
                 "TimeLimit",
                 self.time_limit,
             ))
         self.prob.solve(pulp.GUROBI(msg=0, options=gurobi_options))
Ejemplo n.º 7
0
 def test_gurobi(self, ilp):
     """Test method for GUROBI."""
     try:
         ilp.solve(pulp.GUROBI())
         assert round(pulp.value(ilp.objective), 0) == 5
     except pulp.solvers.PulpSolverError:
         pytest.fail(f"Solver not installed")
Ejemplo n.º 8
0
    def __calcFirstW(self, goal=1, eps=0.00):
        oidx = [i for i in range(self.M)]
        Nsols = len(self.solutionsList)
        assert self.M == Nsols, 'only fist W'

        # Create a gurobi model
        prob = lp.LpProblem("max_mean", lp.LpMaximize)
        # prob = mip.Model(sense=mip.MAXIMIZE, solver_name=mip.GRB)

        # Creation of linear integer variables
        w = list(
            lp.LpVariable.dicts('w',
                                oidx,
                                lowBound=0,
                                upBound=1,
                                cat='Continuous').values())
        # w = list(prob.add_var())

        uR = self.__globalL

        v = lp.LpVariable('v', cat='Continuous')
        # v = prob.add_var(name='v', var_type=mip.CONTINUOUS)

        for conN, sols in enumerate(self.solutionsList):
            d, dvec = self.__calcD(sols)
            expr = v - lp.lpDot(w, self.__normf(sols.objs))
            # expr = v-mip.xsum(w[i]*self.__normf(sols.objs)[i] for i in range())
            prob += expr <= 0  #manter

        for i in oidx:
            prob += w[i] >= 0  #manter

        prob += lp.lpSum([w[i] for i in oidx]) == 1
        # prob += mip.xsum([w[i] for i in oidx]) == 1
        prob += v - lp.lpDot(w, self.__normf(uR))
        # prob += v-mip.xsum(w*self.__normf(uR)[i] for i in range())

        try:
            grbs = lp.GUROBI(msg=False, OutputFlag=False)
            prob.solve(grbs)
        except:
            prob.solve()

        # status = prob.optimize()

        feasible = False if prob.status in [-1, -2] else True
        # feasible = status == OptimizationStatus.OPTIMAL or status == OptimizationStatus.FEASIBLE

        if feasible:
            w_ = np.array(
                [lp.value(w[i]) if lp.value(w[i]) >= 0 else 0 for i in oidx])
            # w_ = np.array([w[i].x if w[i].x >= 0 else 0 for i in oidx])
            if self.__norm:
                w_ = w_ / (self.__globalU - self.__globalL)
            fobj = lp.value(prob.objective)
            # fobj = prob.objective_values[0]
            self.__w = np.array(w_)
            self.__importance = fobj
        else:
            raise ('Somethig wrong')
Ejemplo n.º 9
0
    def __calcImportance(self, solutionsList):
        '''Calculates the importance of a weight using Equation 2 to find the
        lower point and Proposition 4 of the referenced work
        to calculate the importance.
        '''
        oidx = [i for i in range(self.M)]
        prob = lp.LpProblem("Lower point", lp.LpMinimize)

        uR = list(lp.LpVariable.dicts('uR', oidx, cat='Continuous').values())

        for value, sols in enumerate(solutionsList):
            expr = lp.lpDot(self.__normw(sols.w), uR)
            cons = self.__normf(sols.objs) @ self.__normw(sols.w)
            prob += expr >= cons

        prob += lp.lpDot(self.__normw(self.w), uR)

        grbs = lp.GUROBI(msg=False, OutputFlag=False, Threads=1)
        if grbs.available():
            prob.solve(grbs)
        else:
            cbcs = lp.PULP_CBC_CMD(threads=1)
            prob.solve(cbcs, use_mps=False)

        feasible = False if prob.status in [-1, -2] else True

        self.__uR = np.array([lp.value(uR[i]) for i in oidx])

        if feasible:
            self.__importance = ((self.__normw(self.w) @ self.__point -
                                  self.__normw(self.w) @ self.__uR) /
                                 (self.__normw(sols.w) @ np.ones(self.M)))
        else:
            raise ('Non-feasible solution')
Ejemplo n.º 10
0
def PathSplitting(sn, vnr_list, node_mapping_list, edge_mapping_list,
                  request_queue):
    # Create the 'prob' object to contain the optimization problem data
    prob = pulp.LpProblem("Multi-commodity Flow", pulp.LpMinimize)
    # Build summation list for the objective function
    objFn = []

    # First create a total integer trailer flow variable, and tie it to the arc
    var = pulp.LpVariable("TrailerFlow(%s,%s)" % (str(i), str(j)),
                          lowBound=0,
                          cat=pulp.LpInteger)
    a_dict['dvTrailerFlow'] = var

    # The objective function is added to 'prob' first
    # lpSum takes a list of coefficients*LpVariables and makes a summation
    prob += pulp.lpSum(objFn), "Allocated BW"

    # Add the constraint for each commodity specific arc
    for vnr in vnr_list:
        prob += pulp.lpSum(objFn) <= vnr.edges[edge]['bw']
        prob += arcs[a]['dvFlows'][k] <= M * arcs[a]['dvIntree'][
            dest], " Consistency Arc (%s,%s) Commodity(%s,%s) " % (
                str(i), str(j), str(k_orig), str(k_dest))

    # Write out as a .LP file
    prob.writeLP("LinkSplitting.lp")

    # The problem is solved, in this case explicitly asking for Gurobi
    prob.solve(pulp.GUROBI())

    # The status of the solution is printed to the screen
    print("Status:", pulp.LpStatus[prob.status])
Ejemplo n.º 11
0
 def _solve(self, relax: bool, time_limit: Optional[int]):
     # Set variable types
     if not relax:
         # Set partitioning constraints and artificial variables to integer
         # (for the periodic case)
         for node in self.G.nodes():
             if (node not in ["Source", "Sink"]
                     and "depot_from" not in self.G.nodes[node]
                     and "depot_to" not in self.G.nodes[node]):
                 for const in self.prob.constraints:
                     # Modify the self.prob object (the
                     # self.set_covering_constrs object cannot be modified
                     # (?))
                     if "visit_node" in const:
                         self.prob.constraints[
                             const].sense = pulp.LpConstraintEQ
             if (self.periodic and self.G.nodes[node]["frequency"] > 1
                     and node != "Source"):
                 self.dummy[node].cat = pulp.LpInteger
         # Set route variables to integer
         for var in self.y.values():
             # Disallow routes that visit multiple nodes
             if "non" in var.name:
                 var.upBound = 0
                 var.lowBound = 0
             var.cat = pulp.LpInteger
         # Force vehicle bound artificial variable to 0
         for var in self.dummy_bound.values():
             if "artificial_bound_" in var.name:
                 var.upBound = 0
                 var.lowBound = 0
     # Solve with appropriate solver
     if self.solver == "cbc":
         self.prob.solve(
             pulp.PULP_CBC_CMD(
                 msg=False,
                 timeLimit=time_limit,
                 options=["startalg", "barrier", "crossover", "0"],
             ))
     elif self.solver == "cplex":
         self.prob.solve(
             pulp.CPLEX_CMD(
                 msg=False,
                 timeLimit=time_limit,
                 # options=["set lpmethod 4", "set barrier crossover -1"], # set barrier crossover -1 is deprecated
                 options=["set lpmethod 4", "set solutiontype 2"],
             ))
     elif self.solver == "gurobi":
         gurobi_options = [
             ("Method", 2),  # 2 = barrier
             ("Crossover", 0),
         ]
         # Only specify time limit if given (o.w. errors)
         if time_limit is not None:
             gurobi_options.append((
                 "TimeLimit",
                 time_limit,
             ))
         self.prob.solve(pulp.GUROBI(msg=False, options=gurobi_options))
Ejemplo n.º 12
0
 def test_lscp(self):
     merged_dict = covering.merge_coverages(
         [self.binary_coverage_point, self.binary_coverage_point2])
     merged_dict = covering.update_serviceable_demand(
         merged_dict, self.serviceable_demand_point)
     lscp = covering.create_lscp_model(merged_dict)
     lscp_i = covering.create_lscp_model(self.binary_coverage_point)
     lscp.solve(pulp.GUROBI())
     lscp_i.solve(pulp.GUROBI())
     ids = utilities.get_ids(lscp, "facility_service_areas")
     ids2 = utilities.get_ids(lscp, "facility2_service_areas")
     self.assertEqual(['1', '3', '4', '5', '6', '7'], ids)
     self.assertEqual([
         '0', '1', '11', '12', '13', '14', '15', '16', '17', '19', '2',
         '20', '22', '4', '5', '6', '7', '9'
     ], ids2)
     self.assertEqual(lscp_i.status, pulp.constants.LpStatusInfeasible)
Ejemplo n.º 13
0
 def test_cc_threshold(self):
     ccthreshold = covering.create_cc_threshold_model(
         self.partial_coverage2, 80, "ccthreshold.lp")
     ccthreshold.solve(pulp.GUROBI())
     ids = utilities.get_ids(ccthreshold, "facility2_service_areas")
     self.assertEqual([
         '1', '10', '11', '13', '15', '17', '19', '20', '21', '22', '3',
         '4', '7', '9'
     ], ids)
Ejemplo n.º 14
0
def problem(alfa, path):
    """Objective (bi)"""
    prob = pulp.LpProblem('1-MRMCSP', pulp.LpMaximize)
    Z1 = pulp.lpSum(
        [m[m_]['weight'] * yrm[r_ + "_" + m_] for r_ in r for m_ in m])
    Z2 = pulp.lpSum([
        zodij["{}_{}_{}_{}".format(o, d, i, j)] * dij["{}_{}".format(i, j)]
        for o in origins for d in destins for i in stops for j in stops
    ])
    # alfa = 0.001
    prob += alfa * Z1 - (1 - alfa) * Z2
    """Constraints"""
    for r_ in r:
        for m_ in m:
            prob += pulp.lpSum([xj[j] for j in Nm[m_]
                                ]) >= yrm[r_ + '_' + m_], "c2_{}-{}".format(
                                    r_, m_)  # (2)
    for o in origins:
        for d in destins:
            prob += pulp.lpSum([
                zodij["{}_{}_{}_{}".format(o, d, o, j)] for j in stops
            ]) == 1, "c3_{}-{}".format(o, d)  # (3)
            prob += pulp.lpSum([
                zodij["{}_{}_{}_{}".format(o, d, j, o)] for j in stops
            ]) == 0, "c3a_{}-{}".format(o, d)  # (3a)
            prob += pulp.lpSum([
                zodij["{}_{}_{}_{}".format(o, d, i, d)] for i in stops
            ]) == 1, "c4_{}-{}".format(o, d)  # (4)
            prob += pulp.lpSum([
                zodij["{}_{}_{}_{}".format(o, d, d, i)] for i in stops
            ]) == 0, "c4a_{}-{}".format(o, d)  # (4a)
            prob += pulp.lpSum([
                zodij["{}_{}_{}_{}".format(o, d, i, i)] for i in stops
            ]) == 0, "cii_{}-{}".format(o, d)  # (4a)

            prob += pulp.lpSum([
                zodij["{}_{}_{}".format(o, d, s_)] for s_ in s_notallowed
            ]) == 0, "ciii_{}-{}".format(o, d)  # (4a)

            for j in stops:
                prob += pulp.lpSum([
                    zodij["{}_{}_{}_{}".format(o, d, i, j)] for i in stops
                ]) == xj[j], "c6_{}-{}-{}-{}".format(o, d, i, j)  # (6)
                if j[0] != 'o' and j[0] != 'd':
                    prob += pulp.lpSum([
                        zodij["{}_{}_{}_{}".format(o, d, i, j)] for i in stops
                    ]) - pulp.lpSum([
                        zodij["{}_{}_{}_{}".format(o, d, j, k)] for k in stops
                    ]) == 0, "c5_{}-{}-{}-{}".format(o, d, i, j)
    print('Solving MRMCSP for alfa = {} \n...'.format(alfa))
    prob.solve(pulp.GUROBI(msg=0))
    print("Objective: ", pulp.value(prob.objective), '\n')
    # print(pulp.LpStatus[prob.status],'\n')
    # print([(z,zodij[z].varValue) for z in zodij if zodij[z].varValue==1])
    # print([(j,xj[j].varValue) for j in xj if xj[j].varValue==1])
    pd.Series([(z, zodij[z].varValue) for z in zodij
               if zodij[z].varValue == 1]).to_csv(path)
Ejemplo n.º 15
0
 def test_bclpcc(self):
     merged_dict = covering.merge_coverages(
         [self.partial_coverage, self.partial_coverage2])
     merged_dict = covering.update_serviceable_demand(
         merged_dict, self.serviceable_demand_polygon)
     bclpcc = covering.create_bclpcc_model(merged_dict, {"total": 3}, 0.2)
     bclpcc.solve(pulp.GUROBI())
     ids = utilities.get_ids(bclpcc, "facility_service_areas")
     ids2 = utilities.get_ids(bclpcc, "facility2_service_areas")
     self.assertEqual(['4'], ids)
     self.assertEqual(['10'], ids2)
Ejemplo n.º 16
0
 def _solve(self, time_limit):
     if self.solver == "cbc":
         self.prob.solve(pulp.PULP_CBC_CMD(msg=False, timeLimit=time_limit))
     elif self.solver == "cplex":
         self.prob.solve(pulp.CPLEX_CMD(msg=False, timeLimit=time_limit))
     elif self.solver == "gurobi":
         gurobi_options = []
         if time_limit is not None:
             gurobi_options.append((
                 "TimeLimit",
                 time_limit,
             ))
         self.prob.solve(pulp.GUROBI(msg=False, options=gurobi_options))
Ejemplo n.º 17
0
    def _get_solver(solver_name, timelimit):
        if solver_name == "cplex":
            return pulp.CPLEX_PY(msg=0, timeLimit=timelimit)
        elif solver_name == "gurobi":
            return pulp.GUROBI(msg=0, timeLimit=timelimit)
        elif solver_name == "glpk":
            return pulp.GLPK(msg=0, options=["--tmlim", str(timelimit)])
        elif solver_name == "cbc":
            return pulp.COIN(msg=0, maxSeconds=timelimit)
        elif solver_name == "scip":
            return pulp.SCIP(msg=0,
                             options=["-c", f"set limits time {timelimit}"])

        raise ValueError("Invalid Solver Name")
Ejemplo n.º 18
0
 def test_backup(self):
     merged_dict = covering.merge_coverages(
         [self.binary_coverage_point, self.binary_coverage_point2])
     merged_dict = covering.update_serviceable_demand(
         merged_dict, self.serviceable_demand_point)
     bclp = covering.create_backup_model(merged_dict, {"total": 30})
     bclp.solve(pulp.GUROBI())
     ids = utilities.get_ids(bclp, "facility_service_areas")
     ids2 = utilities.get_ids(bclp, "facility2_service_areas")
     self.assertEqual(['1', '3', '4', '5', '6', '7'], ids)
     self.assertEqual([
         '0', '1', '10', '12', '13', '14', '15', '16', '17', '18', '19',
         '2', '20', '22', '3', '4', '5', '6', '8', '9'
     ], ids2)
Ejemplo n.º 19
0
    def optimize(self):
        """
        Default solver is 'cbc' unless solver is set to something else.
        You may need to provide a path for any of the solvers using 'path' argument.
        """

        if model_params['write_lp']:
            logger.info('Writing the lp file!')
            self.model.writeLP(self.model.name + '.lp')

        logger.info('Optimization starts!')
        _solver = pulp.PULP_CBC_CMD(keepFiles=model_params['write_log'],
                                    fracGap=model_params['mip_gap'],
                                    maxSeconds=model_params['time_limit'],
                                    msg=model_params['display_log'])

        if model_params['solver'] == 'gurobi':
            _solver = pulp.GUROBI(msg=model_params['write_log'],
                                  timeLimit=model_params['time_limit'],
                                  epgap=model_params['mip_gap'])
        elif model_params['solver'] == 'cplex':
            options = []
            if model_params['mip_gap']:
                set_mip_gap = "set mip tolerances mipgap {}".format(
                    model_params['mip_gap'])
                options.append(set_mip_gap)
            _solver = pulp.CPLEX_CMD(keepFiles=model_params['write_log'],
                                     options=options,
                                     timelimit=model_params['time_limit'],
                                     msg=model_params['display_log'])
        elif model_params['solver'] == 'glpk':
            # Read more about glpk options: https://en.wikibooks.org/wiki/GLPK/Using_GLPSOL
            options = []
            if model_params['mip_gap']:
                set_mip_gap = "--mipgap {}".format(model_params['mip_gap'])
                options.append(set_mip_gap)
            if model_params['time_limit']:
                set_time_limit = "--tmlim {}".format(
                    model_params['time_limit'])
                options.append(set_time_limit)
            _solver = pulp.GLPK_CMD(keepFiles=model_params['write_log'],
                                    options=options,
                                    msg=model_params['display_log'])

        self.model.solve(solver=_solver)

        if self.model.status == pulp.LpStatusOptimal:
            logger.info('The solution is optimal and the objective value '
                        'is ${:,.2f}'.format(pulp.value(self.model.objective)))
Ejemplo n.º 20
0
 def solve_ilp_problem(self,
                       word_num,
                       p,
                       dep_length=None,
                       parents=None,
                       matrix=None,
                       solver='glpk',
                       mx=0.7,
                       mn=0.2,
                       w2=0.5,
                       saved=None):
     max_length = int(mx * word_num)
     min_length = int(mn * word_num)
     prob = pulp.LpProblem('sentence_compression', pulp.LpMaximize)
     # initialize the word binary variables
     c = pulp.LpVariable.dicts(name='c',
                               indexs=range(word_num),
                               lowBound=0,
                               upBound=1,
                               cat='Integer')
     #objective function
     prob += sum((p[i] - w2 * dep_length[i]) * c[i] for i in range(
         word_num))  #p[i] is  the probability for retain the words
     # #constraints
     if parents is not None:
         for j in range(word_num):
             if parents[j] > 0:
                 prob += c[j] <= c[parents[j]]
     if saved is not None:
         for s in saved:
             prob += c[s[0]] >= c[s[1]]
     prob += sum([c[i] for i in range(word_num)]) <= max_length
     prob += sum([c[i] for i in range(word_num)]) >= min_length
     if solver == 'gurobi':
         prob.solve(pulp.GUROBI(msg=0))
     elif solver == 'glpk':
         prob.solve(pulp.GLPK(msg=0))
     elif solver == 'cplex':
         prob.solve(pulp.CPLEX(msg=0))
     else:
         sys.exit('no solver specified')
     values = [c[j].varValue for j in range(word_num)]
     solution = [j for j in range(word_num) if c[j].varValue == 1]
     return (pulp.value(prob.objective), solution, values)
Ejemplo n.º 21
0
    def __calcImportance(self, solutionsList):
        '''Calculates the importance of a weight P2 of referenced work
        to calculate the importance.
        '''
        if any(self.w + 10**-5 >= 1):
            self.__importance = -float('inf')
            return

        oidx = [i for i in range(self.M)]
        prob = lp.LpProblem("xNISE procedure", lp.LpMinimize)

        uR = list(lp.LpVariable.dicts('uR', oidx, cat='Continuous').values())

        for value, sols in enumerate(solutionsList):
            expr = lp.lpDot(self.__normw(sols.w), uR)
            cons = self.__normf(sols.objs) @ self.__normw(sols.w)
            prob += expr >= cons

        for i in oidx:
            prob += uR[i] <= self.__normf(self.__globalU)[i]

        prob += lp.lpDot(self.__normw(self.w), uR)

        grbs = lp.GUROBI(msg=False, OutputFlag=False, Threads=1)
        if grbs.available():
            prob.solve(grbs)
        else:
            cbcs = lp.PULP_CBC_CMD(threads=1)
            prob.solve(cbcs, use_mps=False)

        feasible = False if prob.status in [-1, -2] else True

        self.__uR = np.array([lp.value(uR[i]) for i in oidx])

        if feasible:
            self.__importance = (self.__normw(self.w) @ self.__point -
                                 self.__normw(self.w) @ self.__uR)
        else:
            raise ('Non-feasible solution')
Ejemplo n.º 22
0
 def _solve(self, relax: bool, time_limit: Optional[int]):
     # Set variable types
     for var in self.prob.variables():
         if relax:
             var.cat = pulp.LpContinuous
         else:
             var.cat = pulp.LpInteger
             # Force vehicle bound artificial variable to 0
             if "artificial_bound_" in var.name:
                 var.upBound = 0
                 var.lowBound = 0
     self.prob.writeLP("master.lp")
     # Solve with appropriate solver
     if self.solver == "cbc":
         self.prob.solve(
             pulp.PULP_CBC_CMD(
                 msg=False,
                 timeLimit=time_limit,
                 options=["startalg", "barrier", "crossover", "0"],
             ))
     elif self.solver == "cplex":
         self.prob.solve(
             pulp.CPLEX_CMD(
                 msg=False,
                 timeLimit=time_limit,
                 options=["set lpmethod 4", "set barrier crossover -1"],
             ))
     elif self.solver == "gurobi":
         gurobi_options = [
             ("Method", 2),  # 2 = barrier
             ("Crossover", 0),
         ]
         # Only specify time limit if given (o.w. errors)
         if time_limit is not None:
             gurobi_options.append((
                 "TimeLimit",
                 time_limit,
             ))
         self.prob.solve(pulp.GUROBI(msg=False, options=gurobi_options))
Ejemplo n.º 23
0
    def optimize(self):
        """
        Default solver is 'cbc' unless solver is set to something else.
        You may need to provide a path for any of the solvers using 'path' argument.
        """
        _solver = None
        s_name = model_params['solver']
        w_log = model_params['write_log']
        disp_log = model_params['display_log']
        mip_gap = model_params['mip_gap']
        tl = model_params['time_limit']

        if model_params['write_lp']:
            logger.info('Writing the lp file!')
            self.model.writeLP(self.model.name + '.lp')

        if not s_name or s_name == 'cbc':
            _solver = pulp.PULP_CBC_CMD(keepFiles=w_log, msg=disp_log, gapRel=mip_gap, timeLimit=tl)
        elif s_name == 'gurobi':
            # One can use GUROBI_CMD like CPLEX_CMD and pass mip_gap and time_limit as options
            _solver = pulp.GUROBI(msg=w_log, gapRel=mip_gap, timeLimit=tl)
        elif s_name == 'cplex':
            _solver = pulp.CPLEX_CMD(keepFiles=w_log, msg=disp_log, gapRel=mip_gap, timelimit=tl)
        elif s_name == 'glpk':
            # Read more about glpk options: https://en.wikibooks.org/wiki/GLPK/Using_GLPSOL
            options = []
            if mip_gap:
                set_mip_gap = f'--mipgap {mip_gap}'
                options.append(set_mip_gap)
            _solver = pulp.GLPK_CMD(keepFiles=w_log, msg=disp_log, options=options, timeLimit=tl)
        elif s_name == 'xpress':
            _solver = pulp.XPRESS(keepFiles=w_log, msg=disp_log, gapRel=mip_gap, timeLimit=tl)

        logger.info('Optimization starts!')
        self.model.solve(solver=_solver)

        if self.model.status == pulp.LpStatusOptimal:
            logger.info(f'The solution is optimal and the objective value '
                        f'is ${self.model.objective.value():,.2f}')
Ejemplo n.º 24
0
import pulp as solver
from pulp import *
import time
import gc
z = 0
solvers = [
    solver.CPLEX(timeLimit=30),
    solver.GLPK(),
    solver.GUROBI(),
    solver.PULP_CBC_CMD(),
    solver.COIN()
]
solverUsado = 3


def solver_exact(g, init, final, is_first, is_last, name):
    var = [(i + ',' + str(t)) for i in g.edge for t in range(1, g.z)]
    var2 = [(str(i) + ',' + str(t)) for i in g.vertices for t in range(1, g.z)]

    X = solver.LpVariable.dicts("X", var, cat=solver.LpBinary)
    Y = solver.LpVariable.dicts("Y", var2, cat=solver.LpBinary)
    problem = solver.LpProblem("The_best_Cut", solver.LpMinimize)
    if is_first:
        problem += (solver.lpSum(
            X.get(
                str(i.split(',')[0]) + ',' + str(i.split(',')[1]) + ',' +
                str(t)) * g.mis[i.split(',')[0]][i.split(',')[1]]
            for i in g.edge for t in range(1, g.z)) + solver.lpSum(
                ((g.pis[k.split(',')[0]][k.split(',')[1]])) -
                ((g.mis[k.split(',')[0]][k.split(',')[1]]))
                for k in g.edgeCuts) / 2) + solver.lpSum(
Ejemplo n.º 25
0
    low = []
    high = []
    for a, a_dict in combo.items():
        if combo[a]['customer'] == i:
            low += [combo[a]['dv'][1], combo[a]['dv'][3]]
            high += [combo[a]['dv'][0], combo[a]['dv'][2]]
    prob += pulp.lpSum(sum(low)) == 1
    prob += pulp.lpSum(sum(high)) == 1

#constraint 3
for i in Zip:
    prob += pulp.lpSum(combo[(i, j)]['dv']
                       for j in CustLoc) <= M * FacilityLocations[i]
## #for all j: sum[k,m,i](x[i,j,m,k])<=M[j]

# Write out as a .LP file
prob.writeLP("UPS_network.lp")

# The problem is solved using PuLP's choice of Solver
prob.solve(pulp.GUROBI())
#prob.solve()

print("Status:", pulp.LpStatus[prob.status])

for v in prob.variables():
    if v.varValue > 0:
        print(v.name, "=", v.varValue)

#print out only locations that were planted. also print out #no.

print("Total Cost = ", pulp.value(prob.objective))
Ejemplo n.º 26
0
    # you must chose a team each week

for team in MASTER_NAMES_LIST:
    # you may only use each team once
    problem += pulp.lpSum(results['{team}_var'.format(team=team)]) <= 1

for i in range(1, 18):
    # you may only use one team per week
    problem += pulp.lpSum(results.transpose()[i][32:64]) == 1

# we're looking to maximize the expected value. This is how we do that:
optimize = pulp.LpAffineExpression([])

# i think that the sums of these logs is equivalent to maximizing the expected value in this case.
problem += pulp.lpSum(X)

# solve
problem.solve(pulp.GUROBI())

# Let's go ahead and actually get these things
results = [
    str(i) for i in problem.variables()
    if i.value() != 0 and i.name[0] not in 'LW'
]
results = sorted(results, key=lambda x: kkey(x[-2:]))
for team in results:
    print team

import pdb
pdb.set_trace()
Ejemplo n.º 27
0
    def __lpHeur(self, w=None, uR=None, eps=0.01):
        if type(w) == type(None) and type(uR) == type(None):
            w = np.random.rand(self.M)
            w = w / w.sum()

        if type(w) != type(None) and type(uR) != type(None):
            raise ('w and uR are not None')

        searchw = type(w) == type(None)
        oidx = list(range(self.M))

        # Create a gurobi model
        prob = lp.LpProblem("max mean heur", lp.LpMinimize)

        if searchw:
            w = list(
                lp.LpVariable.dicts('w',
                                    oidx,
                                    lowBound=0,
                                    upBound=1,
                                    cat='Continuous').values())
            prob += lp.lpSum([w[i] for i in oidx]) == 1
        else:
            uR = list(
                lp.LpVariable.dicts('uR',
                                    oidx,
                                    lowBound=0,
                                    upBound=1,
                                    cat='Continuous').values())
        v = lp.LpVariable('v', cat='Continuous')

        muBaux = []
        for value, sols in enumerate(self.solutionsList):
            aux   = lp.lpDot(w,self.__norm(sols.objs))\
                    if searchw else w@self.__norm(sols.objs)
            prob += v - aux <= 0
            muBaux += [v - aux]

        if not searchw:
            for value, sols in enumerate(self.solutionsList):
                expr = lp.lpDot(uR, sols.w)
                cons = self.__norm(sols.objs) @ sols.w
                prob += expr >= cons * (1 - eps)

            for i in oidx:
                prob += uR[i] >= self.__norm(self.__globalL)[i]

        if searchw:
            wuR = lp.lpDot(w, uR)
        else:
            wuR = lp.lpDot(w, uR)

        prob += wuR - v

        try:
            grbs = lp.GUROBI(timeLimit=10, epgap=0.1, msg=False)
            prob.solve(grbs)
        except:
            prob.solve()

        feasible = False if prob.status in [-1, -2, -3] else True

        if feasible:
            muB_ = [0 if lp.value(mu) >= 0 else 1 for mu in muBaux]
            w_ = np.array([lp.value(w[i]) if lp.value(w[i])>=0 else 0 for i in oidx])\
                 if searchw else w
            uR_ = np.array([lp.value(uR[i]) for i in oidx])\
                  if not searchw else uR
            fobj = lp.value(prob.objective)
        else:
            w_, uR_, muB_, fobj = [None, None, None, None]

        return w_, uR_, muB_, fobj
import numpy as np
import pandas as pd
import pulp

from ..unfairness_optimiser import UnfairnessOptimizer
from ..unfairness_optimiser import generate_weights
from ..unfairness import unfairness_progression
from .heuristics import objective_heuristic

try:
    from tqdm.auto import trange
except Exception:
    trange = range

_solver = pulp.GUROBI(mip=True, msg=False)
if _solver.available() is False:
    _solver = None


def single_query(ranking, t, k, p, theta, iterations):
    global _solver

    optimiser = UnfairnessOptimizer(t, k, p, theta, solver=_solver)

    unfairness_track = []
    for i in trange(iterations):
        unfairness = optimiser.optimise_unfairness(ranking)
        unfairness_track.append(unfairness)

    return unfairness_track
Ejemplo n.º 29
0
    #                                       int_timeslots_per_day, int_week, int_max_period_of_week, int_min_period_of_week,
    #                                       int_weight_room_capacity = int_weight_room_capacity, int_weight_curriculum_compactness = int_weight_curriculum_compactness, int_weight_minimum_working_days = int_weight_minimum_working_days, int_weight_room_stability = int_weight_room_stability, int_weight_lecturer_preferences = int_weight_lecturer_preferences, int_weight_double_lecturs = int_weight_double_lecturs, int_weight_unscheduled_lectures= int_weight_unscheduled_lectures, int_weight_lunch_break=int_weight_lunch_break, int_weigth_course_window = int_weigth_course_window,
    #                                       )
    #===========================================================================
    
    print('Problem file (.mps) succesfully built!')  
    
    
    
           
    # ------- Solve--------
    pulp.LpSolverDefault.msg = 1
    prob.writeLP('CurriculumTimetabling.lp', mip=True)
                   
    # Solve problem using Gurobi
    prob.solve(pulp.GUROBI(timeLimit=900, epgap = 0.05, preSolve = 0, Heuristics=0.5))

    print('Current Week:', int_week)
    print('Status:', pulp.LpStatus[prob.status])
                              
    # Print Optimal Solution. Contrary to the standard Gurobi console solution output, this output also considers constant terms from the objective function
    print('Objective Value:', pulp.value(prob.objective))
             
    # Print solution to variables
    #for v in prob.variables():
        #print(v.name, '=', v.varValue)

       
    # ------- Save solution ---------
    # Store solution in dictionary
    Dic_solution = {variables.name: variables.varValue for variables in prob.variables() if variables.varValue > 0}
Ejemplo n.º 30
0
    def solve_ilp_problem(self,
                          summary_size=100,
                          units="WORDS",
                          solver='glpk',
                          excluded_solutions=[],
                          unique=False):
        """Solve the ILP formulation of the concept-based model.

            :param summary_size: the maximum size in words of the summary, defaults to 100.
            :param units: defaults to "WORDS"
            :param solver: the solver used, defaults to glpk
            :param excluded_solutions: (list of list): a list of subsets of sentences that are to be excluded,
                defaults to []
            :param unique: (bool): modify the model so that it produces only one optimal solution, defaults to False

            :return: (value, set) tuple (int, list): the value of the objective function
                and the set of selected sentences as a tuple.

        """
        # initialize container shortcuts
        concepts = self.weights.keys()

        w = self.weights
        L = summary_size
        C = len(concepts)
        S = len(self.sentences)

        if not self.word_frequencies:
            self.compute_word_frequency()

        tokens = self.word_frequencies.keys()
        f = self.word_frequencies
        T = len(tokens)

        # HACK Sort keys
        concepts = sorted(self.weights, key=self.weights.get, reverse=True)

        # formulation of the ILP problem
        prob = pulp.LpProblem(self.input_directory, pulp.LpMaximize)

        # initialize the concepts binary variables
        c = pulp.LpVariable.dicts(name='c',
                                  indexs=range(C),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')

        # initialize the sentences binary variables
        s = pulp.LpVariable.dicts(name='s',
                                  indexs=range(S),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')

        # initialize the word binary variables
        t = pulp.LpVariable.dicts(name='t',
                                  indexs=range(T),
                                  lowBound=0,
                                  upBound=1,
                                  cat='Integer')

        # OBJECTIVE FUNCTION
        prob += pulp.lpSum(w[concepts[i]] * c[i] for i in range(C))

        if unique:
            prob += pulp.lpSum(w[concepts[i]] * c[i] for i in range(C)) + \
                    10e-6 * pulp.lpSum(f[tokens[k]] * t[k] for k in range(T))

        # CONSTRAINT FOR SUMMARY SIZE
        if units == "WORDS":
            prob += pulp.lpSum(s[j] * self.sentences[j].length
                               for j in range(S)) <= L
        if units == "CHARACTERS":
            prob += pulp.lpSum(s[j] * len(self.sentences[j].untokenized_form)
                               for j in range(S)) <= L

        # INTEGRITY CONSTRAINTS
        for i in range(C):
            for j in range(S):
                if concepts[i] in self.sentences[j].concepts:
                    prob += s[j] <= c[i]

        for i in range(C):
            prob += pulp.lpSum(
                s[j] for j in range(S)
                if concepts[i] in self.sentences[j].concepts) >= c[i]

        # WORD INTEGRITY CONSTRAINTS
        if unique:
            for k in range(T):
                for j in self.w2s[tokens[k]]:
                    prob += s[j] <= t[k]

            for k in range(T):
                prob += pulp.lpSum(s[j] for j in self.w2s[tokens[k]]) >= t[k]

        # CONSTRAINTS FOR FINDING OPTIMAL SOLUTIONS
        for sentence_set in excluded_solutions:
            prob += pulp.lpSum([s[j] for j in sentence_set
                                ]) <= len(sentence_set) - 1

        # prob.writeLP('test.lp')

        # solving the ilp problem
        try:
            print('Solving using Cplex')
            prob.solve(pulp.CPLEX(msg=0))
        except:
            print('Fallback to mentioned solver')
            if solver == 'gurobi':
                prob.solve(pulp.GUROBI(msg=0))
            elif solver == 'glpk':
                prob.solve(pulp.GLPK(msg=0))
            else:
                sys.exit('no solver specified')

        # retreive the optimal subset of sentences
        solution = set([j for j in range(S) if s[j].varValue == 1])

        # returns the (objective function value, solution) tuple
        return (pulp.value(prob.objective), solution)