Exemple #1
0
def load_external_module(module_name, unique=False, clear_cache=False):
    try:
        # make sure "." is in the PATH.
        original_path = list(sys.path)
        sys.path.insert(0, '.')

        sys_modules_key = None
        module_to_find = None
        #
        # Getting around CPython implementation detail:
        #   sys.modules contains dummy entries set to None.
        #   It is related to relative imports. Long story short,
        #   we must check that both module_name is in sys.modules
        #   AND its entry is not None.
        #
        if (module_name in sys.modules) and \
           (sys.modules[module_name] is not None):
            sys_modules_key = module_name
            if clear_cache:
                if unique:
                    sys_modules_key = _generate_unique_module_name()
                    print("Module=" + module_name + " is already imported - "
                          "forcing re-import using unique module id=" +
                          str(sys_modules_key))
                    module_to_find = import_file(module_name,
                                                 name=sys_modules_key)
                    print("Module successfully loaded")
                else:
                    print("Module=" + module_name + " is already imported - "
                          "forcing re-import")
                    module_to_find = import_file(module_name, clear_cache=True)
                    print("Module successfully loaded")
            else:
                print("Module=" + module_name +
                      " is already imported - skipping")
                module_to_find = sys.modules[module_name]
        else:
            if unique:
                sys_modules_key = _generate_unique_module_name()
                print("Importing module=" + module_name + " using "
                      "unique module id=" + str(sys_modules_key))
                module_to_find = import_file(module_name, name=sys_modules_key)
                print("Module successfully loaded")
            else:
                print("Importing module=" + module_name)
                _context = {}
                module_to_find = import_file(module_name,
                                             context=_context,
                                             clear_cache=clear_cache)
                assert len(_context) == 1
                sys_modules_key = list(_context.keys())[0]
                print("Module successfully loaded")

    finally:
        # restore to what it was
        sys.path[:] = original_path

    return module_to_find, sys_modules_key
Exemple #2
0
def load_external_module(module_name, unique=False, clear_cache=False):
    try:
        # make sure "." is in the PATH.
        original_path = list(sys.path)
        sys.path.insert(0,'.')

        sys_modules_key = None
        module_to_find = None
        #
        # Getting around CPython implementation detail:
        #   sys.modules contains dummy entries set to None.
        #   It is related to relative imports. Long story short,
        #   we must check that both module_name is in sys.modules
        #   AND its entry is not None.
        #
        if (module_name in sys.modules) and \
           (sys.modules[module_name] is not None):
            sys_modules_key = module_name
            if clear_cache:
                if unique:
                    sys_modules_key = _generate_unique_module_name()
                    print("Module="+module_name+" is already imported - "
                          "forcing re-import using unique module id="
                          +str(sys_modules_key))
                    module_to_find = import_file(module_name, name=sys_modules_key)
                    print("Module successfully loaded")
                else:
                    print("Module="+module_name+" is already imported - "
                          "forcing re-import")
                    module_to_find = import_file(module_name, clear_cache=True)
                    print("Module successfully loaded")
            else:
                print("Module="+module_name+" is already imported - skipping")
                module_to_find = sys.modules[module_name]
        else:
            if unique:
                sys_modules_key = _generate_unique_module_name()
                print("Importing module="+module_name+" using "
                      "unique module id="+str(sys_modules_key))
                module_to_find = import_file(module_name, name=sys_modules_key)
                print("Module successfully loaded")
            else:
                print("Importing module="+module_name)
                _context = {}
                module_to_find = import_file(module_name, context=_context, clear_cache=clear_cache)
                assert len(_context) == 1
                sys_modules_key = list(_context.keys())[0]
                print("Module successfully loaded")

    finally:
        # restore to what it was
        sys.path[:] = original_path

    return module_to_find, sys_modules_key
Exemple #3
0
def setUpModule():
    global baa99_basemodel
    global piecewise_model_embedded
    if "baa99_basemodel" in sys.modules:
        del sys.modules["baa99_basemodel"]
    fname = os.path.join(pysp_examples_dir, "baa99", "baa99_basemodel.py")
    if os.path.exists(fname + "c"):
        os.remove(fname + "c")
    baa99_basemodel = import_file(fname)
    if "piecewise_model_embedded" in sys.modules:
        del sys.modules["piecewise_model_embedded"]
    fname = os.path.join(thisdir, "piecewise_model_embedded.py")
    if os.path.exists(fname + "c"):
        os.remove(fname + "c")
    piecewise_model_embedded = import_file(fname)
Exemple #4
0
    def _test_disc_first(self, tname):

        ofile = join(currdir, tname + '.' + self.sim_mod + '.out')
        bfile = join(currdir, tname + '.' + self.sim_mod + '.txt')
        setup_redirect(ofile)

        # create model
        exmod = import_file(join(exdir, tname + '.py'))
        m = exmod.create_model()

        # Discretize model
        discretizer = TransformationFactory('dae.collocation')
        discretizer.apply_to(m, nfe=10, ncp=5)

        # Simulate model
        sim = Simulator(m, package=self.sim_mod)

        if hasattr(m, 'var_input'):
            tsim, profiles = sim.simulate(numpoints=100,
                                          varying_inputs=m.var_input)
        else:
            tsim, profiles = sim.simulate(numpoints=100)

        # Initialize model
        sim.initialize_model()

        self._print(m, profiles)

        reset_redirect()
        if not os.path.exists(bfile):
            os.rename(ofile, bfile)

        # os.system('diff ' + ofile + ' ' + bfile)
        self.assertFileEqualsBaseline(ofile, bfile, tolerance=0.01)
Exemple #5
0
    def test_LOA_8PP_fixed_disjuncts(self):
        """Test LOA with 8PP using fixed disjuncts initialization."""
        exfile = import_file(
            join(exdir, 'eight_process', 'eight_proc_model.py'))
        eight_process = exfile.build_eight_process_flowsheet()
        initialize = [
            # Use units 1, 4, 7, 8
            eight_process.use_unit_1or2.disjuncts[0],
            eight_process.use_unit_3ornot.disjuncts[1],
            eight_process.use_unit_4or5ornot.disjuncts[0],
            eight_process.use_unit_6or7ornot.disjuncts[1],
            eight_process.use_unit_8ornot.disjuncts[0]
        ]
        for disj in eight_process.component_data_objects(Disjunct):
            if disj in initialize:
                disj.indicator_var.set_value(1)
            else:
                disj.indicator_var.set_value(0)
        SolverFactory('gdpopt').solve(eight_process,
                                      strategy='LOA',
                                      init_strategy='fix_disjuncts',
                                      mip_solver=mip_solver,
                                      nlp_solver=nlp_solver)

        self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #6
0
 def test_nine_process(self):
     """Test with the nine process problem model."""
     exfile = import_file(join(exdir, 'nine_process', 'small_process.py'))
     simple_model = exfile.build_model()
     simple_model_size = build_model_size_report(simple_model)
     self.assertEqual(simple_model_size.overall.variables, 34)
     self.assertEqual(simple_model_size.activated.variables, 34)
Exemple #7
0
    def testMethod(obj):

        if not testing_solvers[solver, writer]:
            obj.skipTest("Solver %s (interface=%s) is not available" %
                         (solver, writer))

        m = import_file(os.path.join(thisDir, 'kernel_problems', problem),
                        clear_cache=True)

        model = m.define_model(**kwds)

        opt = SolverFactory(solver, solver_io=writer)
        results = opt.solve(model)

        # non-recursive
        new_results = ((var.name, var.value) for var in model.components(
            ctype=variable.ctype, active=True, descend_into=False))
        baseline_results = getattr(obj, problem + '_results')
        for name, value in new_results:
            if abs(baseline_results[name] - value) > 0.00001:
                raise IOError("Difference in baseline solution values and "
                              "current solution values using:\n" + \
                "Solver: "+solver+"\n" + \
                "Writer: "+writer+"\n" + \
                "Variable: "+name+"\n" + \
                "Solution: "+str(value)+"\n" + \
                "Baseline: "+str(baseline_results[name])+"\n")
Exemple #8
0
def import_install_module(download_dest):
    """
    Imports the path in download_dest (install_idaes_workshop_materials.py module)
    """
    install_module = import_file(download_dest)
    print('... importing install module')
    return install_module
Exemple #9
0
def test_tutorial_3():
    f = import_file(join(example, "Tutorial_3_Dynamic_Flowsheets"))
    m, results = f.main()

    # Check for optimal solution
    assert results.solver.termination_condition == TerminationCondition.optimal
    assert results.solver.status == SolverStatus.ok

    assert degrees_of_freedom(m) == 0

    assert m.fs.time.last() == 20.0
    assert len(m.fs.time) == 51

    assert (m.fs.Tank2.outlet.flow_vol[20.0].value == pytest.approx(1.0,
                                                                    abs=1e-2))
    assert (m.fs.Tank2.outlet.conc_mol_comp[20.0,
                                            "Ethanol"].value == pytest.approx(
                                                43.62, abs=1e-1))
    assert (
        m.fs.Tank2.outlet.conc_mol_comp[20.0,
                                        "EthylAcetate"].value == pytest.approx(
                                            1.65, abs=1e-1))
    assert (m.fs.Tank2.outlet.conc_mol_comp[20.0,
                                            "NaOH"].value == pytest.approx(
                                                6.38, abs=1e-1))
    assert (m.fs.Tank2.outlet.conc_mol_comp[20.0, "SodiumAcetate"].value ==
            pytest.approx(43.62, abs=1e-1))
    assert (m.fs.Tank2.outlet.conc_mol_comp[20.0,
                                            "H2O"].value == pytest.approx(
                                                55388.0, abs=1))
    assert (m.fs.Tank2.outlet.pressure[20.0].value == pytest.approx(101325,
                                                                    abs=1))
    assert (m.fs.Tank2.outlet.temperature[20.0].value == pytest.approx(
        303.66, abs=1e-1))
Exemple #10
0
def test_tutorial_2():
    f = import_file(join(example, "Tutorial_2_Basic_Flowsheet_Optimization"))
    m, results = f.main()

    # Check for optimal solution
    assert results.solver.termination_condition == TerminationCondition.optimal
    assert results.solver.status == SolverStatus.ok

    assert degrees_of_freedom(m) == 1

    assert (m.fs.Tank2.outlet.flow_vol[0].value == pytest.approx(1.0,
                                                                 abs=1e-2))
    assert (m.fs.Tank2.outlet.conc_mol_comp[0,
                                            "Ethanol"].value == pytest.approx(
                                                92.106, abs=1e-2))
    assert (
        m.fs.Tank2.outlet.conc_mol_comp[0,
                                        "EthylAcetate"].value == pytest.approx(
                                            7.894, abs=1e-2))
    assert (m.fs.Tank2.outlet.conc_mol_comp[0, "NaOH"].value == pytest.approx(
        7.894, abs=1e-2))
    assert (m.fs.Tank2.outlet.conc_mol_comp[0, "SodiumAcetate"].value ==
            pytest.approx(92.106, abs=1e-2))
    assert (m.fs.Tank2.outlet.conc_mol_comp[0, "H2O"].value == pytest.approx(
        55388.0, abs=1))
    assert (m.fs.Tank2.outlet.pressure[0].value == pytest.approx(101325,
                                                                 abs=1))
    assert (m.fs.Tank2.outlet.temperature[0].value == pytest.approx(304.23,
                                                                    abs=1e-1))

    assert (m.fs.Tank1.volume[0].value == pytest.approx(1.215, abs=1e-2))
    assert (m.fs.Tank2.volume[0].value == pytest.approx(1.785, abs=1e-2))
Exemple #11
0
    def _test(self, tname):

        ofile = join(currdir, tname + '.' + self.sim_mod + '.out')
        bfile = join(currdir, tname + '.' + self.sim_mod + '.txt')
        setup_redirect(ofile)

        # create model
        exmod = import_file(join(exdir, tname + '.py'))
        m = exmod.create_model()

        # Simulate model
        sim = Simulator(m, package=self.sim_mod)

        if hasattr(m, 'var_input'):
            tsim, profiles = sim.simulate(numpoints=100,
                                          varying_inputs=m.var_input)
        else:
            tsim, profiles = sim.simulate(numpoints=100)

        # Discretize model
        discretizer = TransformationFactory('dae.collocation')
        discretizer.apply_to(m, nfe=10, ncp=5)

        # Initialize model
        sim.initialize_model()

        self._print(m, profiles)

        reset_redirect()
        if not os.path.exists(bfile):
            os.rename(ofile, bfile)

        # os.system('diff ' + ofile + ' ' + bfile)
        self.assertFileEqualsBaseline(ofile, bfile, tolerance=0.01)
Exemple #12
0
 def test_8PP_deactive(self):
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     m = exfile.build_eight_process_flowsheet()
     for djn in m.component_data_objects(ctype=Disjunction):
         djn.deactivate()
     self.assertTrue(satisfiable(m) is not False)
Exemple #13
0
 def test_improper_basic_step_linear(self):
     model_builder = import_file(
         join(exdir, 'two_rxn_lee', 'two_rxn_model.py'))
     m = model_builder.build_model(use_mccormick=True)
     m.basic_step = apply_basic_step([
         m.reactor_choice, m.max_demand, m.mccormick_1, m.mccormick_2])
     for disj in m.basic_step.disjuncts.values():
         self.assertIs(
             disj.improper_constraints[1].body, m.P)
         self.assertEqual(
             disj.improper_constraints[1].lower, None)
         self.assertEqual(
             disj.improper_constraints[1].upper, 2)
         self.assertEqual(
             disj.improper_constraints[2].body.polynomial_degree(), 1)
         self.assertEqual(
             disj.improper_constraints[2].lower, None)
         self.assertEqual(
             disj.improper_constraints[2].upper, 0)
         self.assertEqual(
             disj.improper_constraints[3].body.polynomial_degree(), 1)
         self.assertEqual(
             disj.improper_constraints[3].lower, None)
         self.assertEqual(
             disj.improper_constraints[3].upper, 0)
         self.assertEqual(
             len(disj.improper_constraints), 3)
     self.assertFalse(m.max_demand.active)
     self.assertFalse(m.mccormick_1.active)
     self.assertFalse(m.mccormick_2.active)
Exemple #14
0
 def model_constructor():
     import sys
     # Some larger MINLPlib models are massive single *.py files.
     # These do not build properly unless recursion depth is increased.
     sys.setrecursionlimit(50000)
     model_module = import_file(str(model_file_path.resolve()))
     return model_module.m
Exemple #15
0
def apply_postprocessing(data, instance=None, results=None):
    """
    Apply post-processing steps.

    Required:
        instance:   Problem instance.
        results:    Optimization results object.
    """
    #
    if not data.options.runtime.logging == 'quiet':
        sys.stdout.write('[%8.2f] Applying Pyomo postprocessing actions\n' %
                         (time.time() - start_time))
        sys.stdout.flush()

    # options are of type ConfigValue, not raw strings / atomics.
    for config_value in data.options.postprocess:
        postprocess = import_file(config_value, clear_cache=True)
        if "pyomo_postprocess" in dir(postprocess):
            postprocess.pyomo_postprocess(data.options, instance, results)

    for ep in ExtensionPoint(IPyomoScriptPostprocess):
        ep.apply(options=data.options, instance=instance, results=results)

    if data.options.runtime.profile_memory >= 1 and pympler_available:
        mem_used = pympler.muppy.get_size(pympler.muppy.get_objects())
        if mem_used > data.local.max_memory:
            data.local.max_memory = mem_used
        print("   Total memory = %d bytes upon termination" % mem_used)
Exemple #16
0
 def test_8PP_deactive(self):
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     m = exfile.build_eight_process_flowsheet()
     for djn in m.component_data_objects(ctype=Disjunction):
         djn.deactivate()
     self.assertTrue(satisfiable(m) is not False)
Exemple #17
0
 def test_external_grey_box_react_example_maximize_with_hessian_with_output_pyomo(
         self):
     ex = import_file(
         os.path.join(example_dir, 'external_grey_box', 'react-example',
                      'maximize_cb_ratio_residuals.py'))
     m = ex.maximize_cb_ratio_residuals_with_hessian_with_output_pyomo()
     self.assertAlmostEqual(pyo.value(m.sv), 1.26541996, places=3)
     self.assertAlmostEqual(pyo.value(m.cb), 1071.7410089, places=2)
     self.assertAlmostEqual(pyo.value(m.cb_ratio), 0.15190409266, places=3)
Exemple #18
0
 def test_LOA_strip_pack_default_init(self):
     """Test logic-based outer approximation with strip packing."""
     exfile = import_file(
         join(exdir, 'strip_packing', 'strip_packing_concrete.py'))
     strip_pack = exfile.build_rect_strip_packing_model()
     SolverFactory('gdpopt').solve(strip_pack,
                                   strategy='LOA',
                                   mip_solver=mip_solver,
                                   nlp_solver=nlp_solver)
     self.assertTrue(fabs(value(strip_pack.total_length.expr) - 11) <= 1E-2)
Exemple #19
0
 def test_LBB_ex_633_trespalacios(self):
     """Test LBB with Francisco thesis example."""
     exfile = import_file(join(exdir, 'small_lit', 'ex_633_trespalacios.py'))
     model = exfile.build_simple_nonconvex_gdp()
     SolverFactory('gdpbb').solve(
         model, tee=False,
         solver=minlp_solver,
         solver_args=minlp_args,
     )
     objective_value = value(model.obj.expr)
     self.assertAlmostEqual(objective_value, 4.46, 2)
Exemple #20
0
 def test_LBB_8PP(self):
     """Test the logic-based branch and bound algorithm."""
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     eight_process = exfile.build_eight_process_flowsheet()
     SolverFactory('gdpbb').solve(
         eight_process, tee=False,
         solver=minlp_solver,
         solver_args=minlp_args,
     )
     self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #21
0
 def test_LOA_8PP_force_NLP(self):
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     eight_process = exfile.build_eight_process_flowsheet()
     SolverFactory('gdpopt').solve(
         eight_process, strategy='LOA',
         mip_solver=mip_solver,
         nlp_solver=nlp_solver,
         force_subproblem_nlp=True,
         tee=False)
     self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #22
0
 def test_GLOA_nonconvex_HENS(self):
     exfile = import_file(join(exdir, 'small_lit', 'nonconvex_HEN.py'))
     model = exfile.build_gdp_model()
     SolverFactory('gdpopt').solve(model,
                                   strategy='GLOA',
                                   mip_solver=mip_solver,
                                   nlp_solver=global_nlp_solver,
                                   nlp_solver_args=global_nlp_solver_args,
                                   tee=False)
     objective_value = value(model.objective.expr)
     self.assertAlmostEqual(objective_value * 1E-5, 1.14385, 2)
Exemple #23
0
 def test_LOA_strip_pack_maxBinary(self):
     """Test LOA with strip packing using max_binary initialization."""
     exfile = import_file(
         join(exdir, 'strip_packing', 'strip_packing_concrete.py'))
     strip_pack = exfile.build_rect_strip_packing_model()
     SolverFactory('gdpopt').solve(strip_pack,
                                   strategy='LOA',
                                   init_strategy='max_binary',
                                   mip_solver=mip_solver,
                                   nlp_solver=nlp_solver)
     self.assertTrue(fabs(value(strip_pack.total_length.expr) - 11) <= 1E-2)
Exemple #24
0
 def test_external_grey_box_react_example_maximize_cb_outputs(self):
     ex = import_file(
         os.path.join(example_dir, 'external_grey_box', 'react-example',
                      'maximize_cb_outputs.py'))
     m = ex.maximize_cb_outputs()
     self.assertAlmostEqual(pyo.value(m.reactor.inputs['sv']),
                            1.34381,
                            places=3)
     self.assertAlmostEqual(pyo.value(m.reactor.outputs['cb']),
                            1072.4372,
                            places=2)
Exemple #25
0
 def test_GLOA_nonconvex_HENS(self):
     exfile = import_file(join(exdir, 'small_lit', 'nonconvex_HEN.py'))
     model = exfile.build_gdp_model()
     SolverFactory('gdpopt').solve(
         model, strategy='GLOA',
         mip_solver=mip_solver,
         nlp_solver=global_nlp_solver,
         nlp_solver_args=global_nlp_solver_args,
         tee=False)
     objective_value = value(model.objective.expr)
     self.assertAlmostEqual(objective_value * 1E-5, 1.14385, 2)
Exemple #26
0
    def test_LOA_8PP_maxBinary(self):
        """Test logic-based OA with max_binary initialization."""
        exfile = import_file(
            join(exdir, 'eight_process', 'eight_proc_model.py'))
        eight_process = exfile.build_eight_process_flowsheet()
        SolverFactory('gdpopt').solve(
            eight_process, strategy='LOA', init_strategy='max_binary',
            mip_solver=mip_solver,
            nlp_solver=nlp_solver)

        self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #27
0
 def test_LOA_strip_pack_maxBinary(self):
     """Test LOA with strip packing using max_binary initialization."""
     exfile = import_file(
         join(exdir, 'strip_packing', 'strip_packing_concrete.py'))
     strip_pack = exfile.build_rect_strip_packing_model()
     SolverFactory('gdpopt').solve(
         strip_pack, strategy='LOA', init_strategy='max_binary',
         mip_solver=mip_solver,
         nlp_solver=nlp_solver)
     self.assertTrue(
         fabs(value(strip_pack.total_length.expr) - 11) <= 1E-2)
Exemple #28
0
 def test_LOA_strip_pack_default_init(self):
     """Test logic-based outer approximation with strip packing."""
     exfile = import_file(
         join(exdir, 'strip_packing', 'strip_packing_concrete.py'))
     strip_pack = exfile.build_rect_strip_packing_model()
     SolverFactory('gdpopt').solve(
         strip_pack, strategy='LOA',
         mip_solver=mip_solver,
         nlp_solver=nlp_solver)
     self.assertTrue(
         fabs(value(strip_pack.total_length.expr) - 11) <= 1E-2)
Exemple #29
0
 def test_LOA_8PP_default_init(self):
     """Test logic-based outer approximation with 8PP."""
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     eight_process = exfile.build_eight_process_flowsheet()
     SolverFactory('gdpopt').solve(eight_process,
                                   strategy='LOA',
                                   mip_solver=mip_solver,
                                   nlp_solver=nlp_solver,
                                   tee=False)
     self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #30
0
 def test_LOA_8PP_default_init(self):
     """Test logic-based outer approximation with 8PP."""
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     eight_process = exfile.build_eight_process_flowsheet()
     SolverFactory('gdpopt').solve(
         eight_process, strategy='LOA',
         mip_solver=mip_solver,
         nlp_solver=nlp_solver,
         tee=False)
     self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #31
0
 def test_LOA_8PP_force_NLP(self):
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     eight_process = exfile.build_eight_process_flowsheet()
     SolverFactory('gdpopt').solve(eight_process,
                                   strategy='LOA',
                                   mip_solver=mip_solver,
                                   nlp_solver=nlp_solver,
                                   force_subproblem_nlp=True,
                                   tee=False)
     self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #32
0
 def test_LBB_ex_633_trespalacios(self):
     """Test LBB with Francisco thesis example."""
     exfile = import_file(join(exdir, 'small_lit', 'ex_633_trespalacios.py'))
     model = exfile.build_simple_nonconvex_gdp()
     SolverFactory('gdpopt').solve(
         model, tee=False, check_sat=True,
         strategy='LBB',
         minlp_solver=minlp_solver,
         minlp_solver_args=minlp_args,
     )
     objective_value = value(model.obj.expr)
     self.assertAlmostEqual(objective_value, 4.46, 2)
Exemple #33
0
 def test_GLOA_ex_633_trespalacios(self):
     """Test LOA with Francisco thesis example."""
     exfile = import_file(join(exdir, 'small_lit', 'ex_633_trespalacios.py'))
     model = exfile.build_simple_nonconvex_gdp()
     SolverFactory('gdpopt').solve(
         model, strategy='GLOA',
         mip_solver=mip_solver,
         nlp_solver=global_nlp_solver,
         nlp_solver_args=global_nlp_solver_args,
         tee=False)
     objective_value = value(model.obj.expr)
     self.assertAlmostEqual(objective_value, 4.46, 2)
Exemple #34
0
 def test_GLOA_8PP(self):
     """Test the global logic-based outer approximation algorithm."""
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     eight_process = exfile.build_eight_process_flowsheet()
     SolverFactory('gdpopt').solve(eight_process,
                                   strategy='GLOA',
                                   tee=False,
                                   mip_solver=mip_solver,
                                   nlp_solver=global_nlp_solver,
                                   nlp_solver_args=global_nlp_solver_args)
     self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #35
0
    def test_LOA_8PP_maxBinary(self):
        """Test logic-based OA with max_binary initialization."""
        exfile = import_file(
            join(exdir, 'eight_process', 'eight_proc_model.py'))
        eight_process = exfile.build_eight_process_flowsheet()
        SolverFactory('gdpopt').solve(eight_process,
                                      strategy='LOA',
                                      init_strategy='max_binary',
                                      mip_solver=mip_solver,
                                      nlp_solver=nlp_solver)

        self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #36
0
 def test_LBB_8PP(self):
     """Test the logic-based branch and bound algorithm."""
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     eight_process = exfile.build_eight_process_flowsheet()
     SolverFactory('gdpbb').solve(
         eight_process,
         tee=False,
         solver=minlp_solver,
         solver_args=minlp_args,
     )
     self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #37
0
 def test_LBB_strip_pack(self):
     """Test logic-based branch and bound with strip packing."""
     exfile = import_file(
         join(exdir, 'strip_packing', 'strip_packing_concrete.py'))
     strip_pack = exfile.build_rect_strip_packing_model()
     SolverFactory('gdpbb').solve(
         strip_pack,
         tee=False,
         solver=minlp_solver,
         solver_args=minlp_args,
     )
     self.assertTrue(fabs(value(strip_pack.total_length.expr) - 11) <= 1E-2)
Exemple #38
0
 def test_pyomo_react_example_maximize_with_obj(self):
     ex = import_file(
         os.path.join(example_dir, 'external_grey_box', 'react-example',
                      'maximize_cb_ratio_residuals.py'))
     m = ex.maximize_cb_ratio_residuals_with_obj()
     self.assertAlmostEqual(pyo.value(m.reactor.inputs['sv']),
                            1.26541996,
                            places=3)
     self.assertAlmostEqual(pyo.value(m.reactor.inputs['cb']),
                            1071.7410089,
                            places=2)
     self.assertAlmostEqual(pyo.value(m.obj), 0.15190409266, places=3)
Exemple #39
0
 def test_GLOA_8PP(self):
     """Test the global logic-based outer approximation algorithm."""
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     eight_process = exfile.build_eight_process_flowsheet()
     SolverFactory('gdpopt').solve(
         eight_process, strategy='GLOA', tee=False,
         mip_solver=mip_solver,
         nlp_solver=global_nlp_solver,
         nlp_solver_args=global_nlp_solver_args
     )
     self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #40
0
 def test_LBB_strip_pack(self):
     """Test logic-based branch and bound with strip packing."""
     exfile = import_file(
         join(exdir, 'strip_packing', 'strip_packing_concrete.py'))
     strip_pack = exfile.build_rect_strip_packing_model()
     SolverFactory('gdpbb').solve(
         strip_pack, tee=False,
         solver=minlp_solver,
         solver_args=minlp_args,
     )
     self.assertTrue(
         fabs(value(strip_pack.total_length.expr) - 11) <= 1E-2)
Exemple #41
0
 def test_improper_basic_step(self):
     model_builder = import_file(
         join(exdir, 'two_rxn_lee', 'two_rxn_model.py'))
     m = model_builder.build_model()
     m.basic_step = apply_basic_step([m.reactor_choice, m.max_demand])
     for disj in m.basic_step.disjuncts.values():
         self.assertEqual(
             disj.improper_constraints[1].body.polynomial_degree(), 2)
         self.assertEqual(disj.improper_constraints[1].lower, None)
         self.assertEqual(disj.improper_constraints[1].upper, 2)
         self.assertEqual(len(disj.improper_constraints), 1)
     self.assertFalse(m.max_demand.active)
Exemple #42
0
 def test_LOA_8PP_gams_solver(self):
     # Make sure that the duals are still correct
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     eight_process = exfile.build_eight_process_flowsheet()
     SolverFactory('gdpopt').solve(eight_process,
                                   strategy='LOA',
                                   mip_solver=mip_solver,
                                   nlp_solver='gams',
                                   max_slack=0,
                                   tee=False)
     self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #43
0
 def test_LOA_constrained_layout_default_init(self):
     """Test LOA with constrained layout."""
     exfile = import_file(
         join(exdir, 'constrained_layout', 'cons_layout_model.py'))
     cons_layout = exfile.build_constrained_layout_model()
     SolverFactory('gdpopt').solve(cons_layout,
                                   strategy='LOA',
                                   mip=required_solvers[1],
                                   nlp=required_solvers[0])
     objective_value = value(cons_layout.min_dist_cost.expr)
     self.assertTrue(
         fabs(objective_value - 41573) <= 200,
         "Objective value of %s instead of 41573" % objective_value)
Exemple #44
0
 def test_LBB_constrained_layout(self):
     """Test LBB with constrained layout."""
     exfile = import_file(
         join(exdir, 'constrained_layout', 'cons_layout_model.py'))
     cons_layout = exfile.build_constrained_layout_model()
     SolverFactory('gdpbb').solve(
         cons_layout, tee=False,
         solver=minlp_solver,
         solver_args=minlp_args,
     )
     objective_value = value(cons_layout.min_dist_cost.expr)
     self.assertTrue(
         fabs(objective_value - 41573) <= 200,
         "Objective value of %s instead of 41573" % objective_value)
Exemple #45
0
 def test_improper_basic_step(self):
     model_builder = import_file(
         join(exdir, 'two_rxn_lee', 'two_rxn_model.py'))
     m = model_builder.build_model()
     m.basic_step = apply_basic_step([m.reactor_choice, m.max_demand])
     for disj in m.basic_step.disjuncts.values():
         self.assertEqual(
             disj.improper_constraints[1].body.polynomial_degree(), 2)
         self.assertEqual(
             disj.improper_constraints[1].lower, None)
         self.assertEqual(
             disj.improper_constraints[1].upper, 2)
         self.assertEqual(
             len(disj.improper_constraints), 1)
     self.assertFalse(m.max_demand.active)
Exemple #46
0
 def test_LBB_8PP_max(self):
     """Test the logic-based branch and bound algorithm."""
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     eight_process = exfile.build_eight_process_flowsheet()
     obj = next(eight_process.component_data_objects(Objective, active=True))
     obj.sense = maximize
     obj.set_value(-1 * obj.expr)
     SolverFactory('gdpopt').solve(
         eight_process, tee=False,
         strategy='LBB',
         minlp_solver=minlp_solver,
         minlp_solver_args=minlp_args,
     )
     self.assertAlmostEqual(value(eight_process.profit.expr), -68, places=1)
Exemple #47
0
 def test_LBB_constrained_layout(self):
     """Test LBB with constrained layout."""
     exfile = import_file(
         join(exdir, 'constrained_layout', 'cons_layout_model.py'))
     cons_layout = exfile.build_constrained_layout_model()
     SolverFactory('gdpbb').solve(
         cons_layout,
         tee=False,
         solver=minlp_solver,
         solver_args=minlp_args,
     )
     objective_value = value(cons_layout.min_dist_cost.expr)
     self.assertTrue(
         fabs(objective_value - 41573) <= 200,
         "Objective value of %s instead of 41573" % objective_value)
Exemple #48
0
 def test_GLOA_constrained_layout_default_init(self):
     """Test LOA with constrained layout."""
     exfile = import_file(
         join(exdir, 'constrained_layout', 'cons_layout_model.py'))
     cons_layout = exfile.build_constrained_layout_model()
     SolverFactory('gdpopt').solve(
         cons_layout, strategy='GLOA',
         mip_solver=mip_solver,
         iterlim=36,
         nlp_solver=global_nlp_solver,
         nlp_solver_args=global_nlp_solver_args,
         tee=False)
     objective_value = value(cons_layout.min_dist_cost.expr)
     self.assertTrue(
         fabs(objective_value - 41573) <= 200,
         "Objective value of %s instead of 41573" % objective_value)
Exemple #49
0
 def test_LOA_constrained_layout_default_init(self):
     """Test LOA with constrained layout."""
     exfile = import_file(
         join(exdir, 'constrained_layout', 'cons_layout_model.py'))
     cons_layout = exfile.build_constrained_layout_model()
     SolverFactory('gdpopt').solve(
         cons_layout, strategy='LOA',
         mip_solver=mip_solver,
         nlp_solver=nlp_solver,
         iterlim=120,
         max_slack=5,  # problem is convex, so can decrease slack
     )
     objective_value = value(cons_layout.min_dist_cost.expr)
     self.assertTrue(
         fabs(objective_value - 41573) <= 200,
         "Objective value of %s instead of 41573" % objective_value)
Exemple #50
0
    def test_LOA_custom_disjuncts(self):
        """Test logic-based OA with custom disjuncts initialization."""
        exfile = import_file(
            join(exdir, 'eight_process', 'eight_proc_model.py'))
        eight_process = exfile.build_eight_process_flowsheet()
        initialize = [
            # Use units 1, 4, 7, 8
            [eight_process.use_unit_1or2.disjuncts[0],
             eight_process.use_unit_3ornot.disjuncts[1],
             eight_process.use_unit_4or5ornot.disjuncts[0],
             eight_process.use_unit_6or7ornot.disjuncts[1],
             eight_process.use_unit_8ornot.disjuncts[0]],
            # Use units 2, 4, 6, 8
            [eight_process.use_unit_1or2.disjuncts[1],
             eight_process.use_unit_3ornot.disjuncts[1],
             eight_process.use_unit_4or5ornot.disjuncts[0],
             eight_process.use_unit_6or7ornot.disjuncts[0],
             eight_process.use_unit_8ornot.disjuncts[0]]
        ]

        def assert_correct_disjuncts_active(nlp_model, solve_data):
            if solve_data.master_iteration >= 1:
                return  # only checking initialization
            iter_num = solve_data.nlp_iteration
            disjs_should_be_active = initialize[iter_num - 1]
            for orig_disj, soln_disj in zip(
                solve_data.original_model.GDPopt_utils.disjunct_list,
                nlp_model.GDPopt_utils.disjunct_list
            ):
                if orig_disj in disjs_should_be_active:
                    self.assertTrue(soln_disj.indicator_var.value == 1)

        SolverFactory('gdpopt').solve(
            eight_process, strategy='LOA', init_strategy='custom_disjuncts',
            custom_init_disjuncts=initialize,
            mip_solver=mip_solver,
            nlp_solver=nlp_solver,
            call_after_subproblem_feasible=assert_correct_disjuncts_active)

        self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #51
0
    def test_LOA_8PP_fixed_disjuncts(self):
        """Test LOA with 8PP using fixed disjuncts initialization."""
        exfile = import_file(
            join(exdir, 'eight_process', 'eight_proc_model.py'))
        eight_process = exfile.build_eight_process_flowsheet()
        initialize = [
            # Use units 1, 4, 7, 8
            eight_process.use_unit_1or2.disjuncts[0],
            eight_process.use_unit_3ornot.disjuncts[1],
            eight_process.use_unit_4or5ornot.disjuncts[0],
            eight_process.use_unit_6or7ornot.disjuncts[1],
            eight_process.use_unit_8ornot.disjuncts[0]
        ]
        for disj in eight_process.component_data_objects(Disjunct):
            if disj in initialize:
                disj.indicator_var.set_value(1)
            else:
                disj.indicator_var.set_value(0)
        SolverFactory('gdpopt').solve(
            eight_process, strategy='LOA', init_strategy='fix_disjuncts',
            mip_solver=mip_solver,
            nlp_solver=nlp_solver)

        self.assertTrue(fabs(value(eight_process.profit.expr) - 68) <= 1E-2)
Exemple #52
0
 def test_8PP(self):
     exfile = import_file(
         join(exdir, 'eight_process', 'eight_proc_model.py'))
     m = exfile.build_eight_process_flowsheet()
     self.assertTrue(satisfiable(m) is not False)
Exemple #53
0
 def test_strip_pack(self):
     exfile = import_file(
         join(exdir, 'strip_packing', 'strip_packing_concrete.py'))
     m = exfile.build_rect_strip_packing_model()
     self.assertTrue(satisfiable(m))
Exemple #54
0
 def test_constrained_layout(self):
     exfile = import_file(
         join(exdir, 'constrained_layout', 'cons_layout_model.py'))
     m = exfile.build_constrained_layout_model()
     self.assertTrue(satisfiable(m) is not False)
Exemple #55
0
 def test_ex_633_trespalacios(self):
     exfile = import_file(join(exdir, 'small_lit', 'ex_633_trespalacios.py'))
     m = exfile.build_simple_nonconvex_gdp()
     self.assertTrue(satisfiable(m) is not False)