How to use the pyomo.opt.SolverFactory function in Pyomo

To help you get started, we’ve selected a few Pyomo examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github energyPATHWAYS / EnergyPATHWAYS / energyPATHWAYS / helper_multiprocess.py View on Github external
def run_optimization(params, return_model_instance=False):
    try:
        model, solver_name = params
        instance = model.create_instance()
        solver = SolverFactory(solver_name)
        solution = solver.solve(instance)
        instance.solutions.load_from(solution)
    except Exception as e:
        traceback.print_exc()
        raise e
    return instance if return_model_instance else dispatch_classes.all_results_to_list(instance)
github Pyomo / pyomo / examples / doc / pyomobook / attic / scripts / mimic_pyomo / minimalistic.py View on Github external
from pyomo.core import *
from pyomo.opt import SolverFactory, SolverManagerFactory

from DiseaseEstimation import model

# create the instance
instance = model.create('DiseaseEstimation.dat')

# define the solver and its options
solver = 'ipopt'
opt = SolverFactory( solver )
if opt is None:
    raise ValueError, "Problem constructing solver `"+str(solver)
opt.set_options('max_iter=2')

# create the solver manager
solver_manager = SolverManagerFactory( 'serial' )

# solve
results = solver_manager.solve(instance, opt=opt, tee=True, timelimit=None)
instance.load(results)

# display results
display(instance)
github Pyomo / pyomo / pyomo / contrib / sensitivity_toolbox / examples / m_sipopt_feedbackController.py View on Github external
u_profile = {0:-0.06}

m.u_input = Suffix(direction=Suffix.LOCAL)
m.u_input[m.u]=u_profile

sim = Simulator(m,package='scipy')
tsim, profiles = sim.simulate(numpoints=100, varying_inputs=m.u_input)

discretizer = TransformationFactory('dae.collocation')
discretizer.apply_to(m, nfe=100, ncp=1, scheme='LAGRANGE-RADAU')

sim.initialize_model()

discretizer.reduce_collocation_points(m,var=m.u,ncp=1,contset=m.t)

solver=SolverFactory('ipopt')
results = solver.solve(m, tee=True)
#`

######################################
import matplotlib.pyplot as plt

x=[]
u=[]
F=[]

for ii in m.t:
    x.append(value(m.x[ii]))
    u.append(value(m.u[ii]))
    F.append(value(m.F[ii]))
github Pyomo / pyomo / pyomo / contrib / mindtpy / mip_solve.py View on Github external
sign_adjust = 1 if main_objective.sense == minimize else -1
    MindtPy.MindtPy_penalty_expr = Expression(
        expr=sign_adjust * config.OA_penalty_factor * sum(
            v for v in MindtPy.MindtPy_linear_cuts.slack_vars[...]))

    MindtPy.MindtPy_oa_obj = Objective(
        expr=main_objective.expr + MindtPy.MindtPy_penalty_expr,
        sense=main_objective.sense)

    # Deactivate extraneous IMPORT/EXPORT suffixes
    getattr(m, 'ipopt_zL_out', _DoNothing()).deactivate()
    getattr(m, 'ipopt_zU_out', _DoNothing()).deactivate()

    # m.pprint() #print oa master problem for debugging
    with SuppressInfeasibleWarning():
        results = SolverFactory(config.mip_solver).solve(
            m, **config.mip_solver_args)
    master_terminate_cond = results.solver.termination_condition
    if master_terminate_cond is tc.infeasibleOrUnbounded:
        # Linear solvers will sometimes tell me that it's infeasible or
        # unbounded during presolve, but fails to distinguish. We need to
        # resolve with a solver option flag on.
        results, master_terminate_cond = distinguish_mip_infeasible_or_unbounded(
            m, config)

    # Process master problem result
    if master_terminate_cond is tc.optimal:
        # proceed. Just need integer values
        copy_var_list_values(
            m.MindtPy_utils.variable_list,
            solve_data.working_model.MindtPy_utils.variable_list,
            config)
github Pyomo / pyomo / pyomo / solvers / plugins / solvers / GAMS.py View on Github external
if mode is None:
                mode = 'shell'
            del kwds['solver_io']
        except KeyError:
            mode = 'shell'

        if mode == 'direct' or mode == 'python':
            return SolverFactory('_gams_direct', **kwds)
        if mode == 'shell' or mode == 'gms':
            return SolverFactory('_gams_shell', **kwds)
        else:
            logger.error('Unknown IO type: %s' % mode)
            return


@SolverFactory.register('_gams_direct',
        doc='Direct python interface to the GAMS modeling language')
class GAMSDirect(_GAMSSolver):
    """
    A generic python interface to GAMS solvers.

    Visit Python API page on gams.com for installation help.
    """

    def available(self, exception_flag=True):
        """True if the solver is available."""
        try:
            from gams import GamsWorkspace, DebugLevel
            return True
        except ImportError as e:
            if exception_flag is False:
                return False
github energyPATHWAYS / EnergyPATHWAYS / energyPATHWAYS / dispatch_classes.py View on Github external
def run_pyomo(self, model, data, **kwargs):
        """
        Pyomo optimization steps: create model instance from model formulation and data,
        get solver, solve instance, and load solution.
        """
        logging.debug("Creating model instance...")
        instance = model.create_instance(data)
        logging.debug("Getting solver...")
        solver = SolverFactory(cfg.solver_name)
        logging.debug("Solving...")
        solution = solver.solve(instance, **kwargs)
        logging.debug("Loading solution...")
        instance.solutions.load_from(solution)
        return instance
github Pyomo / pyomo / pyomo / contrib / gdpopt / mip_solve.py View on Github external
# resolve with a solver option flag on.
        results, terminate_cond = distinguish_mip_infeasible_or_unbounded(
            m, config)
    if terminate_cond is tc.unbounded:
        # Solution is unbounded. Add an arbitrary bound to the objective and resolve.
        # This occurs when the objective is nonlinear. The nonlinear objective is moved
        # to the constraints, and deactivated for the linear master problem.
        obj_bound = 1E15
        config.logger.warning(
            'Linear GDP was unbounded. '
            'Resolving with arbitrary bound values of (-{0:.10g}, {0:.10g}) on the objective. '
            'Check your initialization routine.'.format(obj_bound))
        main_objective = next(m.component_data_objects(Objective, active=True))
        GDPopt.objective_bound = Constraint(expr=(-obj_bound, main_objective.expr, obj_bound))
        with SuppressInfeasibleWarning():
            results = SolverFactory(config.mip_solver).solve(
                m, **config.mip_solver_args)
        terminate_cond = results.solver.termination_condition

    # Build and return results object
    mip_result = MasterProblemResult()
    mip_result.feasible = True
    mip_result.var_values = list(v.value for v in GDPopt.variable_list)
    mip_result.pyomo_results = results
    mip_result.disjunct_values = list(
        disj.indicator_var.value for disj in GDPopt.disjunct_list)

    if terminate_cond is tc.optimal or terminate_cond is tc.locallyOptimal:
        pass
    elif terminate_cond is tc.infeasible:
        config.logger.info(
            'Linear GDP is now infeasible. '
github FZJ-IEK3-VSA / FINE / FINE / expansionModules / robustPipelineSizing.py View on Github external
# if arc (u,v) of pathNodes satisfies P(startNode, u) subset P(startNode,v), then coefficient is 1, otherwise -1
    for index in range(0, len(pathNodes) - 1):
        # check which direction of the arc is contained in the graph
        if (pathNodes[index], pathNodes[index + 1]) in model.Arcs:
            dic_arc_coef[(pathNodes[index], pathNodes[index + 1])] = 1
        else:
            dic_arc_coef[(pathNodes[index + 1], pathNodes[index])] = -1

    # we set objective
    def obj_rule(model):
        return sum(dic_arc_coef[arc] * model.Flow[arc] for arc in dic_arc_coef.keys())

    model.Obj = py.Objective(rule=obj_rule, sense=py.maximize)

    # Create a solver
    opt = SolverFactory('gurobi')
    # Solve optimization model
    results = opt.solve(model)
    # status of solver
    status = results.solver.status
    # termination condition
    termCondition = results.solver.termination_condition

    # save the solution of the flows in a dictionary key: arcs, values: flow
    dic_scenario_flow = {}

    if status == SolverStatus.error or status == SolverStatus.aborted or status == SolverStatus.unknown:
        utils.output('Solver status:  ' + str(status) + ', termination condition:  ' + str(termCondition) +
                     '. No output is generated.', 0, 0)
    elif termCondition == TerminationCondition.infeasibleOrUnbounded or \
            termCondition == TerminationCondition.infeasible or \
            termCondition == TerminationCondition.unbounded:
github Pyomo / pyomo / examples / pysp / scripting / ef_duals.py View on Github external
options.model_location = \
    os.path.join(farmer_example_dir, 'models')
options.scenario_tree_location = \
    os.path.join(farmer_example_dir, 'scenariodata')

# 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:

        opt.solve(ef_instance)

        #
        # Print duals of non-anticipaticity constraints
        #
        master_constraint_map = ef_instance.MASTER_CONSTRAINT_MAP
        print("%50s %20s" % ("Variable", "Dual"))
        for scenario in manager.scenario_tree.scenarios:
            instance = scenario._instance
            for i in instance.DevotedAcreage:
                print("%50s %20s" % (instance.DevotedAcreage[i],
                                     ef_instance.dual[master_constraint_map[
                                         instance.DevotedAcreage[i]]]))

            print("")
github Pyomo / pyomo / pyomo / pysp / ef.py View on Github external
def solve_ef(master_instance, options):

    with SolverFactory(options.solver_type) as ef_solver:

        with SolverManagerFactory(options.solver_manager_type) as ef_solver_manager:
            if ef_solver is None:
                raise ValueError("Failed to create solver manager of type="
                                 +options.solver_type+" for use in extensive form solve")
            if len(options.ef_solver_options) > 0:
                print("Initializing ef solver with options="+str(options.ef_solver_options))
                ef_solver.set_options("".join(options.ef_solver_options))
            if options.ef_mipgap is not None:
                if (options.ef_mipgap < 0.0) or \
                   (options.ef_mipgap > 1.0):
                    raise ValueError("Value of the mipgap parameter for the "
                                     "EF solve must be on the unit interval; "
                                     "value specified="+str(options.ef_mipgap))
                else:
                    ef_solver.mipgap = options.ef_mipgap