Пример #1
0
    def temoa_setup(self):
        """This function prepares the model to be solved. 

		Inputs:
		model -- the model object
		config_filename -- config filename, non-blank if called from the UI
		There are three possible ways to call the model:
		1. python temoa_model/ /path/to/data_files
		2. python temoa_model/ --config=/path/to/config/file
		3. function call from the UI
		This function discerns which way the model was called and process the 
		inputs accordingly.
		"""
        if self.config_filename == '':  # Called from the command line
            self.options, config_flag = parse_args()
            if config_flag == 1:  # Option 2 (using config file)
                self.options.path_to_lp_files = self.options.path_to_logs + sep + "lp_files"
                TempfileManager.tempdir = self.options.path_to_lp_files
            else:  # Must be Option 1 (no config file)
                pass

        else:  # Config file already specified, so must be an interface call
            available_solvers, default_solver = get_solvers()
            temoa_config = TemoaConfig(d_solver=default_solver)
            temoa_config.build(config=self.config_filename)
            self.options = temoa_config

            self.temp_lp_dest = '/srv/thirdparty/temoa/data_files/'

            self.options.path_to_lp_files = self.options.path_to_logs + sep + "lp_files"
            TempfileManager.tempdir = self.options.path_to_lp_files
Пример #2
0
def parse_args():
    """Parse arguments specfied from command line or in config file."""
    import argparse, sys
    import os, re
    from os.path import dirname, abspath

    available_solvers, default_solver = get_solvers()

    parser = argparse.ArgumentParser()
    parser.prog = path.basename(argv[0].strip('/'))

    parser.add_argument(
        'dot_dat',
        type=str,
        nargs='*',
        help='AMPL-format data file(s) with which to create a model instance. '
        'e.g. "data.dat"')

    parser.add_argument(
        '--path_to_logs',
        help=
        'Path to where debug logs will be generated by default. See folder debug_logs in data_files.',
        action='store',
        dest='path_to_logs',
        default=re.sub('temoa_model$', 'data_files', dirname(
            abspath(__file__))) + os.sep + "debug_logs")

    parser.add_argument(
        '--config',
        help='Path to file containing configuration information.',
        action='store',
        dest='config',
        default=None)

    parser.add_argument(
        '--solver',
        help=
        "Which backend solver to use.  See 'pyomo --help-solvers' for a list "
        'of solvers with which Pyomo can interface.  The list shown here is '
        'what Pyomo can currently find on this system.  [Default: {}]'.format(
            default_solver),
        action='store',
        choices=sorted(available_solvers),
        dest='solver',
        default=default_solver)

    options = parser.parse_args()
    options.neos = False

    # Can't specify keeping the LP file without config file, so set this
    # attribute to false
    options.keepPyomoLP = False

    # If the user specifies the config flag, then call TemoaConfig and overwrite
    # the argument parser above.
    if options.config:
        config_flag = 1  #flag indicates config file was used.
        try:
            temoa_config = TemoaConfig(d_solver=default_solver)
            temoa_config.build(config=options.config)
            SE.write(repr(temoa_config))
            options = temoa_config
            SE.write('\nPlease press enter to continue or Ctrl+C to quit.\n')
            #raw_input() # Give the user a chance to confirm input
            if options.abort_temoa:
                return
        except KeyboardInterrupt:
            SE.write('\n\nUser requested quit.  Exiting Temoa ...\n')
            raise SystemExit()
    else:
        config_flag = 0  #flag indicates config file was not used.

    s_choice = str(options.solver).upper()
    SE.write('Notice: Using the {} solver interface.\n'.format(s_choice))
    SE.flush()

    SE.write(
        "Continue Operation? [Press enter to continue or CTRL+C to abort]\n")
    SE.flush()
    try:  #make compatible with Python 2.7 or 3
        raw_input()  # Give the user a chance to confirm input
    except:
        input()

    return options, config_flag
Пример #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