Example #1
0
    def __init__(self,
                 rounding_digits: int = ROUNDING_DIGITS,
                 max_seconds: int = ILP_SOLVER_MAX_SECONDS) -> None:
        """Create an ILPSolver.

        Args:
            rounding_digits: Number of digits to round the charges to.
            max_seconds: Maximum run-time to spend searching for a \
                    solution
        """
        self._rounding_digits = rounding_digits

        if CPLEX_CMD().available():
            self._solver = CPLEX_CMD(timelimit=max_seconds)
        elif GUROBI_CMD().available():
            self._solver = GUROBI_CMD(options=[('timeLimit', max_seconds)])
        elif PULP_CBC_CMD().available():
            self._solver = PULP_CBC_CMD(maxSeconds=max_seconds)
        elif GLPK_CMD().available():
            self._solver = GLPK_CMD(options=['--tmlim %d' % max_seconds])
        elif COIN_CMD().available():
            self._solver = COIN_CMD(maxSeconds=max_seconds)
        else:
            raise RuntimeError(
                'No solver found, there is something wrong with your pulp library setup.'
            )
Example #2
0
    def optimize(self, time_limit, solver, presolve=2):

        # The solver value shall one of the available
        # solver corresponding pulp command

        if 'gurobi' in solver.lower():
            # ignore SIGINT while solver is running
            # => SIGINT is still delivered to the solver, which is what we want
            signal.signal(signal.SIGINT, signal.SIG_IGN)
            self.model.solve(
                GUROBI_CMD(keepFiles=1,
                           msg=True,
                           options=[("TimeLimit", time_limit),
                                    ("Presolve", presolve),
                                    ("MIPGapAbs", 0.2)]))
        else:
            # TODO Use the solver parameter to get
            # the target class by reflection
            self.model.solve(
                PULP_CBC_CMD(keepFiles=1,
                             msg=True,
                             presolve=presolve,
                             maxSeconds=time_limit))
        status = self.model.status
        print(LpStatus[status])
        if status == LpStatusOptimal or (not (solver.lower() == 'gurobi')
                                         and status == LpStatusNotSolved):
            return self.get_obj_coeffs()

        else:
            print('lpfile has been saved in FlOpTT-pulp.lp')
            return None
Example #3
0
    def _solve(self):
        logger.info("Searching for a cover for {}...".format(self.root_object))
        time_start = time()

        if GUROBI_CMD(msg=0).available():
            logger.info("Gurobi installed on system and set as solver")
            solver = GUROBI_CMD(msg=0)
        elif PULP_CBC_CMD(msg=0).available():
            logger.warning("Gurobi not installed on system, instead "
                           "falling back on PuLP's bundled CBC LP solver")
            solver = PULP_CBC_CMD(msg=0)
        else:
            raise RuntimeError("Unable to load PuLP's bundled CBC LP solver")

        problem = LpProblem("CombCov LP minimization problem", LpMinimize)
        X = LpVariable.dicts("x", list(range(len(self.bitstrings))),
                             cat="Binary")

        for i in range(len(self.elmnts_dict)):  # nr. of equations
            constraint = sum(
                int(self.bitstrings[j][-i]) * X[j]
                for j in range(len(self.bitstrings))
            )  # nr. of variables x_j
            problem += constraint == 1

        # Objective function
        problem += sum(X[j] for j in range(len(self.bitstrings)))

        problem.solve(solver=solver)
        self.solution = [
            self.bitstring_to_rules_dict[self.bitstrings[x]][0]
            for x in X if X[x].varValue and int(X[x].varValue) == 1
        ]

        time_end = time()
        elapsed_time = time_end - time_start

        logger.info("...DONE searching for a cover! "
                    "(Running time: {:.2f} sec)".format(elapsed_time))
Example #4
0
         # e peak and all B ions
         model += (Me[e] - (B[i] + lpSum(ma[a] for a in range(i+1))) >= -D*(1-y[e][i]))
         model += (Me[e] - (B[i] + lpSum(ma[a] for a in range(i+1))) <= D*(1-y[e][i])) 
         model += (Me[e] - (B[i] + lpSum(ma[a] for a in range(i+1))) >= c*(1-y[e][i]) - (D+c)*d[e][i])
         model += (Me[e] - (B[i] + lpSum(ma[a] for a in range(i+1))) <= -c*(1-y[e][i]) + (D+c)*(1-d[e][i]))
         
     for i in range(S):
         # e peak and all Y ions
         model += (Me[e] - (Y[i] + lpSum(ma[a] for a in range(i, S))) >= -D*(1-y[e][i+S]))
         model += (Me[e] - (Y[i] + lpSum(ma[a] for a in range(i, S))) <= D*(1-y[e][i+S])) 
         model += (Me[e] - (Y[i] + lpSum(ma[a] for a in range(i, S))) >= c*(1-y[e][i+S]) - (D+c)*d[e][i+S])
         model += (Me[e] - (Y[i] + lpSum(ma[a] for a in range(i, S))) <= -c*(1-y[e][i+S]) + (D+c)*(1-d[e][i]))
 # when the upper two iteration co-exist, model will be infeasible. When any one of them is suspended, it is feasible. They 
 # must have collision
 model.writeLP('/home/slaiad/Code/Backbone/test.lp')
 model.solve(GUROBI_CMD())
 # ['PULP_CBC_CMD', 'PULP_CHOCO_CMD']
 # # ['GLPK_CMD', 'PYGLPK', 'CPLEX_CMD', 'CPLEX_PY', 'CPLEX_DLL', 'GUROBI', 'GUROBI_CMD', 
 # #  'MOSEK', 'XPRESS', 'PULP_CBC_CMD', 'COIN_CMD', 'COINMP_DLL', 'CHOCO_CMD', 'PULP_CHOCO_CMD', 'MIPCL_CMD', 'SCIP_CMD']
 
 print('Status: ', LpStatus[model.status])
 for a in ma:
     print(ma[a].value())
     
 print('--')
 for a in xa:
     print(xa[a].value())
     
 # print(listSolvers(onlyAvailable=True))
 
 countY0 = 0
Example #5
0
def solveLP(tag,
            pep,
            tagPos,
            M,
            oriMe,
            oriIe,
            Nmod=1,
            c=0.01,
            tau=0.01,
            thres=0.8):
    Iave = np.average(oriIe)

    # print(oriMe)
    # print(oriIe)
    tagI = value(lpSum([oriIe[i] for i in tagPos]))
    Me = np.round([
        oriMe[i] for i in range(len(oriMe))
        if i not in tagPos and oriIe[i] >= thres * Iave
    ], 4)
    Ie = np.round([
        oriIe[i] for i in range(len(oriIe))
        if i not in tagPos and oriIe[i] >= thres * Iave
    ], 4)

    Me = np.round(
        [oriMe[i] for i in range(len(oriMe)) if oriIe[i] >= thres * Iave], 4)
    Ie = np.round(
        [oriIe[i] for i in range(len(oriIe)) if oriIe[i] >= thres * Iave], 4)
    # print(Me)
    # print(Ie)
    # print('LP',len(Ie),Iave )
    S = len(pep) - len(tag)
    E = len(Me)
    U = abs(M) + 10
    D = 2000

    B, Y = getBY(pep, S)
    model = LpProblem('PTM', const.LpMaximize)

    ma = LpVariable.dicts('ma', range(S), -abs(M), abs(M))
    xa = LpVariable.dicts('xa', range(S), cat='Binary')
    da = LpVariable.dicts('da', range(S), cat='Binary')

    y = LpVariable.dicts('y', (range(E), range(2 * S)), cat='Binary')
    # d = LpVariable.dicts('d', (range(E), range(2*S)), cat = 'Binary')

    model += lpSum(
        lpSum(y[k][i] for i in range(2 * S)) * Ie[k] for k in range(E))
    # model += lpDot([lpSum(y[k][i] for i in range(2*S)) for k in range(E)], Ie) #or
    # model += lpSum(xa[a] for a in range(S))
    for a in range(S):
        model += (ma[a] >= -U * xa[a])
        model += (ma[a] <= U * xa[a])
        model += (ma[a] >= c * xa[a] - (U + c) * da[a])
        model += (ma[a] <= -c * xa[a] + (U + c) * (1 - da[a]))

    model += (lpSum(xa[a] for a in range(S)) == Nmod)
    model += (lpSum(ma[a] for a in range(S)) == M)

    for e in range(E):
        for i in range(S):
            # e peak and all B ions
            model += (y[e][i] <= 1 + tau / (D - tau) -
                      (Me[e] - (B[i] + lpSum(ma[a]
                                             for a in range(i + 1)))) / D)
            model += (y[e][i] <= 1 + tau / (D - tau) +
                      (Me[e] - (B[i] + lpSum(ma[a]
                                             for a in range(i + 1)))) / D)
            # if pep[i] in 'RKNQ':
            #     model += (y[e][i] <= 1 + tau/(D-tau) - (Me[e] - (B[i] - 17.026549105 + lpSum(ma[a] for a in range(i+1))))/D)
            #     model += (y[e][i] <= 1 + tau/(D-tau) + (Me[e] - (B[i] - 17.026549105 + lpSum(ma[a] for a in range(i+1))))/D)
            # if pep[i] in 'STED':
            #     model += (y[e][i] <= 1 + tau/(D-tau) - (Me[e] - (B[i] - 18.0105647 + lpSum(ma[a] for a in range(i+1))))/D)
            #     model += (y[e][i] <= 1 + tau/(D-tau) + (Me[e] - (B[i] - 18.0105647 + lpSum(ma[a] for a in range(i+1))))/D)

        for i in range(S):
            # e peak and all Y ions
            model += (y[e][i + S] <= 1 + tau / (D - tau) -
                      (Me[e] - (Y[i] + lpSum(ma[a] for a in range(i, S)))) / D)
            model += (y[e][i + S] <= 1 + tau / (D - tau) +
                      (Me[e] - (Y[i] + lpSum(ma[a] for a in range(i, S)))) / D)
            # if pep[i] in 'RKNQ':
            #     model += (y[e][i+S] <= 1 + tau/(D-tau) - (Me[e] - (Y[i]  - 17.026549105 + lpSum(ma[a] for a in range(i, S))))/D)
            #     model += (y[e][i+S] <= 1 + tau/(D-tau) + (Me[e] - (Y[i]  - 17.026549105 + lpSum(ma[a] for a in range(i, S))))/D)
            # if pep[i] in 'STED':
            #     model += (y[e][i+S] <= 1 + tau/(D-tau) - (Me[e] - (Y[i]  - 18.0105647 + lpSum(ma[a] for a in range(i, S))))/D)
            #     model += (y[e][i+S] <= 1 + tau/(D-tau) + (Me[e] - (Y[i]  - 18.0105647 + lpSum(ma[a] for a in range(i, S))))/D)

        model += (lpSum(y[e][i] for i in range(2 * S)) <= 1)
    # model.writeLP('/home/slaiad/Code/Backbone/test.lp')
    # model.solve(GUROBI_CMD(logPath = '', options = [('LogToConsole', 0)]))
    model.solve(GUROBI_CMD(msg=1))
    # ['PULP_CBC_CMD', 'PULP_CHOCO_CMD']

    maVal = []
    xaVal = []
    print('LpStatus[model.status]', LpStatus[model.status])
    if LpStatus[model.status] != 'Optimal':
        return [], [], 0
    # print('Status: ', LpStatus[model.status])
    # print('obj: ', value(model.objective))
    sumY = 0
    for i in range(2 * S):
        sumy = 0
        for e in range(E):
            sumy = sumy + y[e][i].value()
        sumY = sumY + sumy * (1.5 + 0.5 * cos(2 * pi / S * i))
    # sumY = value(lpSum(lpSum(y[e][i].value() for i in range(2*S)) for e in range(E)))
    sumOriI = value(lpSum(oriIe))  # + value(lpSum(oriIe[k] for k in tagPos))
    sumI = value(lpSum(Ie))
    sumTagI = value(lpSum(oriIe[k] for k in tagPos))

    # print(value(lpSum(oriIe[k] for k in tagPos)), value(lpSum(Ie)), value(lpSum(oriIe)))
    i = 0
    ii = -1
    for a in ma:
        if xa[a].value() > 0.1:
            maVal.append(ma[a].value())
            xaVal.append(str(i) + pep[i])
            ii = i
        i += 1

    obj = value(model.objective)

    print('obj', obj)
    final = (obj + tagI) / sumI + (0.5 + sumY) / 20 - abs(M) / 500
    if 1:
        print('pep', pep)
        # print(sumI)
        print(' obj/sumI', (obj + tagI) / sumI)
        print('value(sumY)/S', sumY, S, sumY / S)
        print('M', M, 'at', ii, pep[ii])
        print('final', final)
        print('-------')

    # for a in ma:
    #     print(ma[a].value())

    # print('--')
    # for a in xa:
    #     print(xa[a].value())
    # print('--')
    return maVal, xaVal, final
Example #6
0
            model += (y[e][i] <= 1 + tau/(D-tau) - (Me[e] - (B[i] + lpSum(ma[a] for a in range(i+1))))/D)
            model += (y[e][i] <= 1 + tau/(D-tau) + (Me[e] - (B[i] + lpSum(ma[a] for a in range(i+1))))/D)
            
        for i in range(S):
            # e peak and all Y ions
            model += (y[e][i+S] <= 1 + tau/(D-tau) - (Me[e] - (Y[i] + lpSum(ma[a] for a in range(i, S))))/D)
            model += (y[e][i+S] <= 1 + tau/(D-tau) + (Me[e] - (Y[i] + lpSum(ma[a] for a in range(i, S))))/D)
            
        model += (lpSum(y[e][i] for i in range(2*S)) <= 1)
    # when the upper two iteration co-exist, model will be infeasible. When any one of them is suspended, it is feasible. They 
    # must have collision
    model.writeLP('/home/slaiad/Code/Backbone/test.lp')
    
    t4 = time()

    model.solve(GUROBI_CMD(logPath = '', options = [('LogToConsole', 0)]))
    # ['PULP_CBC_CMD', 'PULP_CHOCO_CMD']
    t5 = time()
    print("finish searching ", t5-t4)
    
    print('Status: ', LpStatus[model.status])
    print(ma.values())
    for a in ma:
        print(ma[a].value())
        
    print('--')
    for a in xa:
        print(xa[a].value())
    print('--')  
    # print(listSolvers(onlyAvailable=True))
    #%%