Python pulp.LpStatusOptimal() Examples

The following are 15 code examples of pulp.LpStatusOptimal(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pulp , or try the search function .
Example #1
Source File: super_efficiency_model.py    From pyDEA with MIT License 6 votes vote down vote up
def _fill_solution_one_dmu(self, dmu_code, model_solution):
        ''' Treats a special case when we want to solve a super efficiency
            model but have only one DMU.

            Args:
                dmu_code (str): DMU code for which the LP was solved.
                model_solution (Solution): object where solution for one DMU
                    will be written.
        '''
        model_solution.orientation = self._concrete_model.get_orientation()
        model_solution.add_lp_status(dmu_code, LpStatusOptimal)

        model_solution.add_efficiency_score(dmu_code, 1)
        model_solution.add_lambda_variables(dmu_code, dict())
        for category in self.input_data.input_categories:
            model_solution.add_input_dual(dmu_code, category, 0)
        for category in self.input_data.output_categories:
            model_solution.add_output_dual(dmu_code, category, 0)

        try:
            model_solution.add_VRS_dual(dmu_code, 0)
        except AttributeError:
            pass 
Example #2
Source File: solution.py    From pyDEA with MIT License 6 votes vote down vote up
def is_efficient(self, dmu_code, lambda_variables=None):
        ''' Checks if a given DMU is efficient.

            Args:
                dmu_code (str): DMU code.
                lambda_variables (dict of str to double, optional): dictionary
                    that maps DMU codes to the corresponding value
                    of lambda variables. If it is not given, it will be loaded
                    from a pickled file.

            Returns:
                bool: True if a given DMU is efficient, False otherwise.
        '''
        if self.lp_status[dmu_code] != LpStatusOptimal:
            return False
        file_name = self._get_pickle_name(dmu_code)
        if not lambda_variables:
            lambda_variables = pickle.load(open(file_name, 'rb'))
        return is_efficient(self.get_efficiency_score(dmu_code),
                            lambda_variables.get(dmu_code, 0)) 
Example #3
Source File: test_solution.py    From pyDEA with MIT License 6 votes vote down vote up
def test_solution_add_lambda_variables(data):
    s = Solution(data)
    s.add_lp_status('dmu_1', LpStatusOptimal)
    s.add_lp_status('dmu_4', LpStatusOptimal)
    s.add_efficiency_score('dmu_1', 0.5)
    s.add_efficiency_score('dmu_4', 0.9999999)
    s.add_lambda_variables('dmu_1', {'dmu_1': 0, 'dmu_4': 1.5})
    assert s.is_efficient(data._DMU_user_name_to_code['dmu1']) is False
    s.add_lambda_variables('dmu_4', {'dmu_1': 0, 'dmu_4': 1.5})
    assert s.is_efficient(data._DMU_user_name_to_code['dmu2']) is True
    l_vars = s.get_lambda_variables('dmu_1')
    assert len(l_vars) == 2
    assert l_vars['dmu_1'] == 0
    assert l_vars['dmu_4'] == 1.5
    with pytest.raises(ValueError) as excinfo:
        s.add_lambda_variables('dmu_1', {'dmu_1': 0, 'dmu_3': 1.5})
    assert str(excinfo.value) == 'DMU code dmu_3 does not exist' 
Example #4
Source File: utils_for_tests.py    From pyDEA with MIT License 6 votes vote down vote up
def check_if_category_is_within_price_ratio_constraints(model_solution, bounds):
    for (category_in_nom, category_in_denom), (lower_bound, upper_bound) in bounds.items():
        if lower_bound:
            for dmu_code in model_solution._input_data.DMU_codes:
                if model_solution.lp_status[dmu_code] == LpStatusOptimal:
                    dual_value = _get_proper_dual(
                        category_in_nom, model_solution, dmu_code)
                    dual_value_denom = _get_proper_dual(
                        category_in_denom, model_solution, dmu_code)
                    assert dual_value + WEIGHT_RESTRICTION_TOLERANCE >= lower_bound * dual_value_denom

        if upper_bound:
            for dmu_code in model_solution._input_data.DMU_codes:
                if model_solution.lp_status[dmu_code] == LpStatusOptimal:
                    dual_value = _get_proper_dual(
                        category_in_nom, model_solution, dmu_code)
                    dual_value_denom = _get_proper_dual(
                        category_in_denom, model_solution, dmu_code)
                    assert dual_value - WEIGHT_RESTRICTION_TOLERANCE <= upper_bound * dual_value_denom 
Example #5
Source File: pulp_solver.py    From pydfs-lineup-optimizer with MIT License 5 votes vote down vote up
def solve(self):
        self.prob.solve(self.LP_SOLVER)
        if self.prob.status == LpStatusOptimal:
            result = []
            for variable in self.prob.variables():
                val = variable.value()
                if val is not None and round(val) == 1.0:
                    result.append(variable)
            return result
        else:
            raise SolverException('Unable to solve') 
Example #6
Source File: envelopment_model_base.py    From pyDEA with MIT License 5 votes vote down vote up
def _fill_solution(self, dmu_code, model_solution):
        ''' Fills given solution with data calculated for one DMU.

            Args:
                dmu_code (str): DMU code for which the LP was solved.
                model_solution (Solution): object where solution for one DMU
                    will be written.
        '''
        model_solution.orientation = self._concrete_model.get_orientation()
        model_solution.add_lp_status(dmu_code, self.lp_model.status)

        if self.lp_model.status == pulp.LpStatusOptimal:
            lambda_variables = dict()
            for dmu in self.input_data.DMU_codes:
                var = self._variables.get(dmu, None)
                if (var is not None and var.varValue is not None and
                        abs(var.varValue) > ZERO_TOLERANCE):
                    lambda_variables[dmu] = var.varValue

            if self._should_add_efficiency:
                model_solution.add_efficiency_score(
                    dmu_code, self._concrete_model.process_obj_var
                    (pulp.value(self.lp_model.objective)))
                
            model_solution.add_lambda_variables(dmu_code, lambda_variables)
            self._process_duals(dmu_code, self.input_data.input_categories,
                                model_solution.add_input_dual)
            self._process_duals(dmu_code, self.input_data.output_categories,
                                model_solution.add_output_dual) 
Example #7
Source File: multiplier_model_base.py    From pyDEA with MIT License 5 votes vote down vote up
def _fill_solution(self, dmu_code, model_solution):
        ''' Fills given solution with data calculated for one DMU.

            Args:
                dmu_code (str): DMU code for which the LP was solved.
                model_solution (Solution): object where solution for one DMU
                    will be written.
        '''
        model_solution.orientation = self._concrete_model.get_orientation()
        model_solution.add_lp_status(dmu_code, self.lp_model.status)
        if self.lp_model.status == pulp.LpStatusOptimal:
            for input_category in self.input_data.input_categories:
                model_solution.add_input_dual(
                    dmu_code, input_category,
                    self._input_variables[input_category].varValue)

            for output_category in self.input_data.output_categories:
                model_solution.add_output_dual(
                    dmu_code, output_category,
                    self._output_variables[output_category].varValue)
            lambda_variables = dict()
            for dmu_constraint, dmu in self._dmu_constraint_names.items():
                if self.lp_model.constraints[dmu_constraint].pi is None:
                    self.lp_model.constraints[dmu_constraint].pi = 0
                # else:
                #     print(self.lp_model.constraints[dmu_constraint].pi)
                if (abs(self.lp_model.constraints[dmu_constraint].pi) >
                        ZERO_TOLERANCE):
                    lambda_variables[dmu] = self._concrete_model.process_dual_value(
                        self.lp_model.constraints[dmu_constraint].pi)
            lambda_var = lambda_variables.get(dmu_code, 0)
            model_solution.add_efficiency_score(
                dmu_code, self._get_efficiency_score(lambda_var))
            # print('lambda_variables: {0}'.format(lambda_variables))
            model_solution.add_lambda_variables(dmu_code, lambda_variables) 
Example #8
Source File: test_solution.py    From pyDEA with MIT License 5 votes vote down vote up
def test_solution_lp_status(data):
    s = Solution(data)
    s.add_lp_status('dmu_1', LpStatusOptimal)
    assert s.lp_status['dmu_1'] == LpStatusOptimal
    with pytest.raises(ValueError) as excinfo:
        s.add_lp_status('dmu_3', LpStatusOptimal)
    assert str(excinfo.value) == 'DMU code dmu_3 does not exist'
    s.add_lp_status('dmu_1', 'Something')
    assert s.lp_status['dmu_1'] == 'Something' 
Example #9
Source File: utils_for_tests.py    From pyDEA with MIT License 5 votes vote down vote up
def _helper_function_for_checking_limits(category, model_solution,
                                         categories, bound, get_dual_func,
                                         bool_func,
                                         process_bound):
    if category in categories:
        for dmu_code in model_solution._input_data.DMU_codes:
            if model_solution.lp_status[dmu_code] == LpStatusOptimal:
                dual_value = get_dual_func(dmu_code, category)
                coeff = model_solution._input_data.coefficients[
                    dmu_code, category]
                bool_func(dual_value, process_bound(bound, coeff)) 
Example #10
Source File: lp_solve.py    From RevPy with MIT License 5 votes vote down vote up
def solve_lp(prob):
    """Solve LP, return min/max."""
    optimization_result = prob.solve()
    assert optimization_result == pulp.LpStatusOptimal
    optimal_value = pulp.value(prob.objective)

    return optimal_value 
Example #11
Source File: optimization_model_pulp.py    From optimization-tutorial with MIT License 4 votes vote down vote up
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)))

    # ================== Output ================== 
Example #12
Source File: peel_the_onion.py    From pyDEA with MIT License 4 votes vote down vote up
def peel_the_onion_method(model):
    ''' Runs the peel the onion model and returns solution that corresponds to
        the first run and ranking of all DMUs.

        Args:
            model (ModelBase): DEA model that must be called in the peel
                the onion.

        Returns:
            tuple of Solution, dict of str to int, bool: tuple with the first
                solution of the problem, dictionary that maps DMU code to peel
                the onion rank, boolean value which is true if all peel the
                onion runs were successful, false otherwise.
    '''
    copy_of_dmu_codes = copy.deepcopy(model.input_data.DMU_codes)
    current_rank = 1
    ranks = dict()
    for dmu_code in model.input_data.DMU_codes:
        ranks[dmu_code] = 'Infeasible/unbounded'

    first_solution = None
    max_slack_solution = None
    while model.input_data.DMU_codes:
        solution = model.run()
        if current_rank == 1:
            first_solution = solution
            try:
                max_slack_solution = model.second_solution
            except AttributeError:
                pass
        dmus_to_remove = []
        not_efficient_dmus = []

        one_is_infeasible = False
        for dmu_code in model.input_data.DMU_codes:
            if solution.lp_status[dmu_code] != LpStatusOptimal:
                one_is_infeasible = True
            elif solution.is_efficient(dmu_code):
                ranks[dmu_code] = current_rank
                dmus_to_remove.append(dmu_code)
            else:
                not_efficient_dmus.append(dmu_code)

        if one_is_infeasible:
            restore_base(model, first_solution, copy_of_dmu_codes,
                         max_slack_solution)
            return first_solution, ranks, False
        for dmu_code in dmus_to_remove:
            model.input_data.DMU_codes.remove(dmu_code)
        if len(dmus_to_remove) == 0 and len(not_efficient_dmus) > 0:
            for dmu in not_efficient_dmus:
                ranks[dmu] = current_rank
            break
        current_rank += 1

    restore_base(model, first_solution, copy_of_dmu_codes, max_slack_solution)
    return first_solution, ranks, True 
Example #13
Source File: write_data_to_xls.py    From pyDEA with MIT License 4 votes vote down vote up
def create_sheet_onion_rank(self, work_sheet, solution, start_row_index,
                                params_str):
        ''' Writes information about peel the onion solution to a given output.

            Args:
                work_sheet: object that has name attribute and implements
                    write method, it actually writes data to some output
                    (like file, screen, etc.).
                solution (Solution): solution.
                start_row_index (int): initial row index (usually used to append
                    data to existing output).
                params_str (str): string that is usually written in the first
                    row.

            Returns:
                int: index of the last row where data were written plus 1.
        '''
        work_sheet.name = 'OnionRank'
        # in case of max_slacks and peel-the-onion we should not
        # write ranks twice
        if self.count < len(self.ranks):

            work_sheet.write(start_row_index, 0, params_str)
            work_sheet.write(
                start_row_index + 1, 0,
                'Tier / Rank is the run in which DMU became efficient')
            work_sheet.write(start_row_index + 2, 0, 'DMU')
            work_sheet.write(start_row_index + 2, 1, 'Efficiency')
            work_sheet.write(start_row_index + 2, 2, 'Tier / Rank')
            ordered_dmu_codes = solution._input_data.DMU_codes_in_added_order
            row_index = start_row_index + 3
            for dmu_code in ordered_dmu_codes:
                work_sheet.write(
                    row_index, 0,
                    solution._input_data.get_dmu_user_name(dmu_code))
                if solution.lp_status[dmu_code] == pulp.LpStatusOptimal:
                    work_sheet.write(row_index, 1,
                                     solution.get_efficiency_score(dmu_code))
                    work_sheet.write(row_index, 2,
                                     self.ranks[self.count][dmu_code])
                else:
                    work_sheet.write(
                        row_index, 1,
                        pulp.LpStatus[solution.lp_status[dmu_code]])
                row_index += 1
            self.count += 1
            return row_index
        return -1 
Example #14
Source File: write_data_to_xls.py    From pyDEA with MIT License 4 votes vote down vote up
def create_sheet_efficiency_scores(self, work_sheet, solution,
                                       start_row_index, params_str):
        ''' Writes efficiency scores to a given output.

            Args:
                work_sheet: object that has name attribute and implements
                    write method, it actually writes data to some output
                    (like file, screen, etc.).
                solution (Solution): solution.
                start_row_index (int): initial row index (usually used to append
                    data to existing output).
                params_str (str): string that is usually written in the first
                    row.

            Returns:
                int: index of the last row where data were written plus 1.
        '''
        work_sheet.name = 'EfficiencyScores'

        work_sheet.write(start_row_index, 0, params_str)
        work_sheet.write(start_row_index + 1, 0, 'DMU')
        work_sheet.write(start_row_index + 1, 1, 'Efficiency')
        if self.categorical is not None:
            work_sheet.write(start_row_index + 1, 2,
                             'Categorical: {0}'.format(self.categorical))

        ordered_dmu_codes = solution._input_data.DMU_codes_in_added_order
        row_index = 0
        for count, dmu_code in enumerate(ordered_dmu_codes):
            row_index = start_row_index + count + 2
            work_sheet.write(
                row_index, 0, solution._input_data.get_dmu_user_name(dmu_code))
            if solution.lp_status[dmu_code] == pulp.LpStatusOptimal:
                work_sheet.write(
                    row_index, 1, solution.get_efficiency_score(dmu_code))
            else:
                work_sheet.write(
                    row_index, 1, pulp.LpStatus[solution.lp_status[dmu_code]])
            if self.categorical is not None:
                work_sheet.write(
                    row_index, 2,
                    int(solution._input_data.coefficients[
                        dmu_code, self.categorical]))
        return row_index 
Example #15
Source File: write_data_to_xls.py    From pyDEA with MIT License 4 votes vote down vote up
def create_sheet_peers(work_sheet, solution, start_row_index, params_str):
    ''' Writes peers to a given output.

        Args:
            work_sheet: object that has name attribute and implements
                write method, it actually writes data to some output
                (like file, screen, etc.).
            solution (Solution): solution.
            start_row_index (int): initial row index (usually used to append
                data to existing output).
            params_str (str): string that is usually written in the first
                row.

        Returns:
            int: index of the last row where data were written plus 1.
    '''
    work_sheet.name = 'Peers'

    work_sheet.write(start_row_index, 0, params_str)
    work_sheet.write(start_row_index + 1, 0, 'DMU')
    work_sheet.write(start_row_index + 1, 2, 'Peer')
    work_sheet.write(start_row_index + 1, 3, 'Lambda')
    write_classification = False
    if bool(solution.return_to_scale):
        work_sheet.write(start_row_index + 1, 4, 'Classification')
        write_classification = True
        
    ordered_dmu_codes = solution._input_data.DMU_codes_in_added_order
    row_index = start_row_index + 2
    for dmu_code in ordered_dmu_codes:
        work_sheet.write(row_index, 0, solution._input_data.get_dmu_user_name(
            dmu_code))
        if solution.lp_status[dmu_code] == pulp.LpStatusOptimal:
            lambda_vars = solution.get_lambda_variables(dmu_code)
#            sum_of_lambda_values = 0
            once = True
#            for dmu, lambda_value in lambda_vars.items():
#                if lambda_value:
#                    sum_of_lambda_values += lambda_value
            
            for dmu, lambda_value in lambda_vars.items():
                if lambda_value:
                    dmu_name = solution._input_data.get_dmu_user_name(dmu)
                    work_sheet.write(row_index, 2, dmu_name)
                    work_sheet.write(row_index, 3, lambda_value)
                    if write_classification and once:
                        work_sheet.write(
                            row_index, 4, solution.return_to_scale[dmu_code]
                            #_calculate_frontier_classification(sum_of_lambda_values)
                                )

                        once = False
                    row_index += 1

        else:
            work_sheet.write(
                row_index, 2, pulp.LpStatus[solution.lp_status[dmu_code]])
        row_index += 1
    return row_index