Ejemplo n.º 1
0
    def solve_temoa_instance(self):
        '''Solve a Temoa instance.'''

        begin = time()
        duration = lambda: time() - begin
        try:
            yield 'Solving.'
            SE.write('[        ] Solving.')
            SE.flush()
            self.txt_file.write('Solving.')
            if self.optimizer:
                if self.options.neos:
                    self.result = self.optimizer.solve(self.instance,
                                                       opt=self.options.solver)
                else:
                    self.result = self.optimizer.solve(
                        self.instance,
                        suffixes=['dual'],  # 'rc', 'slack'],
                        keepfiles=self.options.keepPyomoLP,
                        symbolic_solver_labels=self.options.keepPyomoLP)
                yield '\t\t\t\t\t\t[%8.2f]\n' % duration()
                SE.write('\r[%8.2f]\n' % duration())
                self.txt_file.write('[%8.2f]\n' % duration())
                # return signal handlers to defaults, again
                signal(SIGINT, default_int_handler)

                # ... print the easier-to-read/parse format
                msg = '[        ] Calculating reporting variables and formatting results.'
                yield 'Calculating reporting variables and formatting results.'
                SE.write(msg)
                SE.flush()
                self.txt_file.write(
                    'Calculating reporting variables and formatting results.')
                self.instance.solutions.store_to(self.result)
                formatted_results = pformat_results(self.instance, self.result,
                                                    self.options)
                yield '\t[%8.2f]\n' % duration()
                SE.write('\r[%8.2f\n' % duration())
                self.txt_file.write('[%8.2f]\n' % duration())
                yield formatted_results.getvalue() + '\n'
                #SO.write( formatted_results.getvalue() )
                self.txt_file.write(formatted_results.getvalue())
                if formatted_results.getvalue() == 'No solution found.':
                    SE.write(formatted_results.getvalue() + '\n')
            else:
                yield '\r---------- Not solving: no available solver\n'
                SE.write('\r---------- Not solving: no available solver\n')
                self.txt_file.write(
                    '\r---------- Not solving: no available solver\n')

        except BaseException as model_exc:
            yield "Exception found in solve_temoa_instance\n"
            SE.write("Exception found in solve_temoa_instance\n")
            self.txt_file.write("Exception found in solve_temoa_instance\n")
            yield str(model_exc) + '\n'
            SE.write(str(model_exc))
            self.txt_file.write(str(model_exc))
            raise model_exc
Ejemplo n.º 2
0
def solve_ef(p_model, p_data, temoa_options=None):
    """
    solve_ef(p_model, p_data) -> objective value of the extensive form
    Solves the model in stochastic mode. 
    p_model -> string, the path to the model file (ReferenceModel.py). 
    p_data -> string, the path to the directory of data for the stochastic
    mdoel, where ScenarioStructure.dat should resides.
    Returns a float point number of the value of objective function for the
    stochastic program model.
    """

    options = ScenarioTreeManagerClientSerial.register_options()

    if os.path.basename(p_model) == 'ReferenceModel.py':
        options.model_location = os.path.dirname(p_model)
    else:
        sys.stderr.write(
            '\nModel file should be ReferenceModel.py. Exiting...\n')
        sys.exit(1)
    options.scenario_tree_location = p_data

    # using the 'with' block will automatically call
    # manager.close() and gracefully shutdown
    with ScenarioTreeManagerClientSerial(options) as manager:
        manager.initialize()

        ef_instance = create_ef_instance(manager.scenario_tree,
                                         verbose_output=options.verbose)

        ef_instance.dual = Suffix(direction=Suffix.IMPORT)

        with SolverFactory(temoa_options.solver) as opt:

            ef_result = opt.solve(ef_instance)

        # Write to database
        if hasattr(temoa_options, 'output'):
            sys.path.append(options.model_location)
            from pformat_results import pformat_results
            # from temoa_config import TemoaConfig
            # temoa_options = TemoaConfig()
            # temoa_options.config = temoa_options.config
            # temoa_options.keepPyomoLP = temoa_options.keepPyomoLP
            # temoa_options.saveTEXTFILE = temoa_options.saveTEXTFILE
            # temoa_options.path_to_db_io = temoa_options.path_to_db_io
            # temoa_options.saveEXCEL = temoa_options.saveEXCEL
            ef_result.solution.Status = 'feasible'  # Assume it is feasible
            # Maybe there is a better solution using manager, but now it is a
            # kludge to use return_CP_and_path() function
            s2cd_dict, s2fp_dict = return_CP_and_path(p_data)
            stochastic_run = temoa_options.scenario  # Name of stochastic run
            for s in manager.scenario_tree.scenarios:
                ins = s._instance
                temoa_options.scenario = '.'.join([stochastic_run, s.name])
                temoa_options.dot_dat = list()
                for fname in s2fp_dict[s.name]:
                    temoa_options.dot_dat.append(
                        os.path.join(options.scenario_tree_location, fname))
                # temoa_options.output = os.path.join(
                #     options.scenario_tree_location,
                #     stochastic_output
                #     )
                msg = '\nStoring results from scenario {} to database.\n'.format(
                    s.name)
                sys.stderr.write(msg)
                formatted_results = pformat_results(ins, ef_result,
                                                    temoa_options)

    ef_instance.solutions.store_to(ef_result)
    ef_obj = value(ef_instance.EF_EXPECTED_COST.values()[0])
    return ef_obj
Ejemplo n.º 3
0
def solve_ef(p_model, p_data, dummy_temoa_options=None):
    """
    solve_ef(p_model, p_data) -> objective value of the extensive form
    Solves the model in stochastic mode. 
    p_model -> string, the path to the model file (ReferenceModel.py). 
    p_data -> string, the path to the directory of data for the stochastic
    mdoel, where ScenarioStructure.dat should resides.
    Returns a float point number of the value of objective function for the
    stochastic program model.
    """

    options = ScenarioTreeManagerClientSerial.register_options()

    if os.path.basename(p_model) == 'ReferenceModel.py':
        options.model_location = os.path.dirname(p_model)
    else:
        sys.stderr.write(
            '\nModel file should be ReferenceModel.py. Exiting...\n')
        sys.exit(1)
    options.scenario_tree_location = p_data

    # using the 'with' block will automatically call
    # manager.close() and gracefully shutdown
    with ScenarioTreeManagerClientSerial(options) as manager:
        manager.initialize()

        ef_instance = create_ef_instance(manager.scenario_tree,
                                         verbose_output=options.verbose)

        ef_instance.dual = Suffix(direction=Suffix.IMPORT)

        with SolverFactory('cplex') as opt:

            ef_result = opt.solve(ef_instance)

        # Write to database
        if dummy_temoa_options:
            sys.path.append(options.model_location)
            from pformat_results import pformat_results
            from temoa_config import TemoaConfig
            temoa_options = TemoaConfig()
            temoa_options.config = dummy_temoa_options.config
            temoa_options.keepPyomoLP = dummy_temoa_options.keepPyomoLP
            temoa_options.saveTEXTFILE = dummy_temoa_options.saveTEXTFILE
            temoa_options.path_to_db_io = dummy_temoa_options.path_to_db_io
            temoa_options.saveEXCEL = dummy_temoa_options.saveEXCEL
            ef_result.solution.Status = 'feasible'  # Assume it is feasible
            for s in manager.scenario_tree.scenarios:
                ins = s._instance
                temoa_options.scenario = s.name
                temoa_options.dot_dat = [
                    os.path.join(options.scenario_tree_location,
                                 s.name + '.dat')
                ]
                temoa_options.output = os.path.join(
                    options.scenario_tree_location, dummy_temoa_options.output)
                msg = '\nStoring results from scenario {} to database.\n'.format(
                    s.name)
                sys.stderr.write(msg)
                formatted_results = pformat_results(ins, ef_result,
                                                    temoa_options)

    ef_instance.solutions.store_to(ef_result)
    ef_obj = value(ef_instance.EF_EXPECTED_COST.values()[0])
    return ef_obj