def test_reclassification(self): m = ConcreteModel() m.t = ContinuousSet(bounds=(0, 1)) m.x = ContinuousSet(bounds=(5, 10)) m.s = Set(initialize=[1, 2, 3]) m.v = Var(m.t) m.v2 = Var(m.s, m.t) m.v3 = Var(m.x, m.t) m.dv = DerivativeVar(m.v) m.dv2 = DerivativeVar(m.v2, wrt=(m.t, m.t)) m.dv3 = DerivativeVar(m.v3, wrt=m.x) TransformationFactory('dae.finite_difference').apply_to(m, wrt=m.t) self.assertTrue(m.dv.type() is Var) self.assertTrue(m.dv2.type() is Var) self.assertTrue(m.dv.is_fully_discretized()) self.assertTrue(m.dv2.is_fully_discretized()) self.assertTrue(m.dv3.type() is DerivativeVar) self.assertFalse(m.dv3.is_fully_discretized()) TransformationFactory('dae.collocation').apply_to(m, wrt=m.x) self.assertTrue(m.dv3.type() is Var) self.assertTrue(m.dv3.is_fully_discretized())
def test_unique_component_name(self): m = ConcreteModel() m.x = 5 m.y = Var() name = unique_component_name(m, 'z') self.assertEqual(name, 'z') name = unique_component_name(m, 'x') self.assertEqual(len(name), 3) self.assertEqual(name[:2], 'x_') self.assertIn(name[2], '0123456789') name = unique_component_name(m, 'y') self.assertEqual(len(name), 3) self.assertEqual(name[:2], 'y_') self.assertIn(name[2], '0123456789') name = unique_component_name(m, 'component') self.assertEqual(len(name), 11) self.assertEqual(name[:10], 'component_') self.assertIn(name[10], '0123456789') for i in range(10): setattr(m, 'y_%s' % i, 0) name = unique_component_name(m, 'y') self.assertEqual(len(name), 4) self.assertEqual(name[:2], 'y_') self.assertIn(name[2], '0123456789') self.assertIn(name[3], '0123456789')
def test_linear(self): m = ConcreteModel() m.x = Var() m.c = Constraint(expr=5*m.x == 10) calculate_variable_from_constraint(m.x, m.c) self.assertEqual(value(m.x), 2)
def _trivial_constraints_ub_conflict(self): m = ConcreteModel() m.v1 = Var(initialize=1) m.c = Constraint(expr=m.v1 <= 0) m.v1.fix() TransformationFactory( 'contrib.deactivate_trivial_constraints').apply_to(m)
def test_None_key(self): """Test keys method""" model = ConcreteModel() model.x = Var() model.c = Constraint(expr=model.x == 1) self.assertEqual(list(model.c.keys()),[None]) self.assertEqual(id(model.c),id(model.c[None]))
def test_not_transform_improperly(self): """Tests that invalid constraints are not transformed.""" m = ConcreteModel() m.v1 = Var(initialize=0, domain=Binary) m.c1 = Constraint(expr=-1 * m.v1 <= 0) TransformationFactory('contrib.propagate_zero_sum').apply_to(m) self.assertFalse(m.v1.fixed)
def test_multiple_obj(self): m = ConcreteModel() m.x = Var() m.o = Objective(expr=m.x) m.o2 = Objective(expr=m.x) with self.assertRaisesRegexp(RuntimeError, "multiple active objectives"): SolverFactory('multistart').solve(m)
def test_multiple_objectives(self): m = ConcreteModel() m.x = Var() m.o = Objective(expr=m.x) m.o2 = Objective(expr=m.x + 1) with self.assertRaisesRegexp(ValueError, "Model has multiple active objectives"): SolverFactory('gdpopt').solve(m)
def test_GDP_nonlinear_objective(self): m = ConcreteModel() m.x = Var(bounds=(-1, 10)) m.y = Var(bounds=(2, 3)) m.d = Disjunction(expr=[ [m.x + m.y >= 5], [m.x - m.y <= 3] ]) m.o = Objective(expr=m.x ** 2) SolverFactory('gdpopt').solve( m, strategy='LOA', mip_solver=mip_solver, nlp_solver=nlp_solver ) self.assertAlmostEqual(value(m.o), 0) m = ConcreteModel() m.x = Var(bounds=(-1, 10)) m.y = Var(bounds=(2, 3)) m.d = Disjunction(expr=[ [m.x + m.y >= 5], [m.x - m.y <= 3] ]) m.o = Objective(expr=-m.x ** 2, sense=maximize) SolverFactory('gdpopt').solve( m, strategy='LOA', mip_solver=mip_solver, nlp_solver=nlp_solver ) self.assertAlmostEqual(value(m.o), 0)
def test_simple_unsat_model(self): m = ConcreteModel() m.x = Var() m.c1 = Constraint(expr=1 == m.x) m.c2 = Constraint(expr=2 == m.x) m.o = Objective(expr=m.x) self.assertFalse(satisfiable(m))
def build_model(): """Simple non-convex model with many local minima""" model = ConcreteModel() model.x1 = Var(initialize=1, bounds=(0, 100)) model.x2 = Var(initialize=5, bounds=(5, 6)) model.x2.fix(5) model.objtv = Objective(expr=model.x1 * sin(model.x1), sense=maximize) return model
def test_invalid_derivative(self): m = ConcreteModel() m.t = ContinuousSet(bounds=(0, 10)) m.v = Var(m.t) m.dv = DerivativeVar(m.v, wrt=(m.t, m.t, m.t)) with self.assertRaises(DAE_Error): TransformationFactory('dae.finite_difference').apply_to(m)
def test_no_objective(self): m = ConcreteModel() m.x = Var(bounds=(-5, 5)) m.c = Constraint(expr=m.x ** 2 >= 1) output = StringIO() with LoggingIntercept(output, 'pyomo.contrib.gdpopt', logging.WARNING): SolverFactory('gdpopt').solve(m, nlp_solver=nlp_solver) self.assertIn("Model has no active objectives. Adding dummy objective.", output.getvalue().strip())
def test_fixed_var_out_of_bounds_ub(self): m = ConcreteModel() m.s = RangeSet(2) m.v = Var(m.s, bounds=(0, 5)) m.c = ConstraintList() m.c.add(expr=m.v[1] == m.v[2]) m.c.add(expr=m.v[1] == 6) with self.assertRaises(ValueError): TransformationFactory('contrib.aggregate_vars').apply_to(m)
def test_set_expr_inline(self): """Test expr= option (inline expression)""" model = ConcreteModel() model.A = RangeSet(1,4) model.x = Var(model.A,initialize=2) model.c = Constraint(expr=(0, sum(model.x[i] for i in model.A), 1)) self.assertEqual(model.c(), 8) self.assertEqual(value(model.c.body), 8)
def test_no_integer(self): m = ConcreteModel() m.x = Var() output = StringIO() with LoggingIntercept(output, 'pyomo.contrib.preprocessing', logging.INFO): xfrm('contrib.integer_to_binary').apply_to(m) expected_message = "Model has no free integer variables." self.assertIn(expected_message, output.getvalue())
def test_var_bound_propagate_crossover(self): """Test for error message when variable bound crosses over.""" m = ConcreteModel() m.v1 = Var(initialize=1, bounds=(1, 3)) m.v2 = Var(initialize=5, bounds=(4, 8)) m.c1 = Constraint(expr=m.v1 == m.v2) xfrm = TransformationFactory('contrib.propagate_eq_var_bounds') with self.assertRaises(ValueError): xfrm.apply_to(m)
def test_PyomoUnit_NumericValueMethods(self): m = ConcreteModel() uc = units kg = uc.kg self.assertEqual(kg.getname(), 'kg') self.assertEqual(kg.name, 'kg') self.assertEqual(kg.local_name, 'kg') m.kg = uc.kg self.assertEqual(m.kg.name, 'kg') self.assertEqual(m.kg.local_name, 'kg') self.assertEqual(kg.is_constant(), False) self.assertEqual(kg.is_fixed(), True) self.assertEqual(kg.is_parameter_type(), False) self.assertEqual(kg.is_variable_type(), False) self.assertEqual(kg.is_potentially_variable(), False) self.assertEqual(kg.is_named_expression_type(), False) self.assertEqual(kg.is_expression_type(), False) self.assertEqual(kg.is_component_type(), False) self.assertEqual(kg.is_relational(), False) self.assertEqual(kg.is_indexed(), False) self.assertEqual(kg._compute_polynomial_degree(None), 0) with self.assertRaises(TypeError): x = float(kg) with self.assertRaises(TypeError): x = int(kg) self.assertTrue(uc.check_units_consistency(kg < m.kg, uc)) self.assertTrue(uc.check_units_consistency(kg > m.kg, uc)) self.assertTrue(uc.check_units_consistency(kg <= m.kg, uc)) self.assertTrue(uc.check_units_consistency(kg >= m.kg, uc)) self.assertTrue(uc.check_units_consistency(kg == m.kg, uc)) self.assertTrue(uc.check_units_consistency(kg + m.kg, uc)) self.assertTrue(uc.check_units_consistency(kg - m.kg, uc)) with self.assertRaises(InconsistentUnitsError): uc.check_units_consistency(kg + 3) with self.assertRaises(InconsistentUnitsError): uc.check_units_consistency(kg - 3) with self.assertRaises(InconsistentUnitsError): uc.check_units_consistency(3 + kg) with self.assertRaises(InconsistentUnitsError): uc.check_units_consistency(3 - kg) # should not assert # check __mul__ self.assertEqual(str(uc.get_units(kg * 3)), 'kg') # check __rmul__ self.assertEqual(str(uc.get_units(3 * kg)), 'kg') # check div / truediv self.assertEqual(str(uc.get_units(kg / 3.0)), 'kg') # check rdiv / rtruediv self.assertEqual(str(uc.get_units(3.0 / kg)), '1 / kg') # check pow self.assertEqual(str(uc.get_units(kg**2)), 'kg ** 2') # check rpow x = 2**kg # creation is allowed, only fails when units are "checked" self.assertFalse(uc.check_units_consistency(x, allow_exceptions=False)) with self.assertRaises(UnitsError): uc.check_units_consistency(x) x = kg x += kg self.assertEqual(str(uc.get_units(x)), 'kg') x = kg x -= 2.0 * kg self.assertEqual(str(uc.get_units(x)), 'kg') x = kg x *= 3 self.assertEqual(str(uc.get_units(x)), 'kg') x = kg x **= 3 self.assertEqual(str(uc.get_units(x)), 'kg ** 3') self.assertEqual(str(uc.get_units(-kg)), 'kg') self.assertEqual(str(uc.get_units(+kg)), 'kg') self.assertEqual(str(uc.get_units(abs(kg))), 'kg') self.assertEqual(str(kg), 'kg') self.assertEqual(kg.to_string(), 'kg') # ToDo: is this really the correct behavior for verbose? self.assertEqual(kg.to_string(verbose=True), 'kg') self.assertEqual(kg.to_string(), 'kg') self.assertEqual(kg.to_string(), 'kg') # check __nonzero__ / __bool__ self.assertEqual(bool(kg), True) # __call__ returns 1.0 self.assertEqual(kg(), 1.0) self.assertEqual(value(kg), 1.0) # test pprint buf = StringIO() kg.pprint(ostream=buf) self.assertEqual('kg', buf.getvalue()) # test str representations for dimensionless dless = uc.dimensionless self.assertEqual('dimensionless', str(dless))
def test_index_by_unhashable_type(self): m = ConcreteModel() m.x = Var([1, 2, 3], initialize=lambda m, x: 2 * x) self.assertRaisesRegex(TypeError, '.*', m.x.__getitem__, {})
def test_fixed_var_sign_gms(self): with SolverFactory("gams", solver_io="gms") as opt: m = ConcreteModel() m.x = Var() m.y = Var() m.z = Var() m.z.fix(-3) m.c1 = Constraint(expr=m.x + m.y - m.z == 0) m.c2 = Constraint(expr=m.z + m.y - m.z >= -10000) m.c3 = Constraint(expr=-3 * m.z + m.y - m.z >= -10000) m.c4 = Constraint(expr=-m.z + m.y - m.z >= -10000) m.c5 = Constraint(expr=m.x <= 100) m.o = Objective(expr=m.x, sense=maximize) results = opt.solve(m) self.assertEqual(results.solver.termination_condition, TerminationCondition.optimal)
def test_build(self): model = ConcreteModel() model.params = GenericParameterBlock(default=configuration) assert isinstance(model.params.phase_list, Set) assert len(model.params.phase_list) == 2 for i in model.params.phase_list: assert i in ["Liq", "Vap"] assert model.params.Liq.is_liquid_phase() assert model.params.Vap.is_vapor_phase() assert isinstance(model.params.component_list, Set) assert len(model.params.component_list) == 2 for i in model.params.component_list: assert i in ['H2O', 'CO2'] assert isinstance(model.params.get_component(i), Component) assert isinstance(model.params._phase_component_set, Set) assert len(model.params._phase_component_set) == 3 for i in model.params._phase_component_set: assert i in [("Liq", "H2O"), ("Vap", "H2O"), ("Vap", "CO2")] assert model.params.config.state_definition == FTPx assertStructuredAlmostEqual( model.params.config.state_bounds, { "flow_mol": (0, 10, 20, pyunits.mol / pyunits.s), "temperature": (273.15, 323.15, 1000, pyunits.K), "pressure": (5e4, 108900, 1e7, pyunits.Pa), "mole_frac_comp": { "H2O": (0, 0.5, 1), "CO2": (0, 0.5, 1) } }, item_callback=_as_quantity, ) assert model.params.config.phase_equilibrium_state == { ("Vap", "Liq"): SmoothVLE } assert isinstance(model.params.phase_equilibrium_idx, Set) assert len(model.params.phase_equilibrium_idx) == 1 for i in model.params.phase_equilibrium_idx: assert i in ["PE1"] assert model.params.phase_equilibrium_list == { "PE1": { "H2O": ("Vap", "Liq") } } assert model.params.pressure_ref.value == 101325 assert model.params.temperature_ref.value == 298.15 assert model.params.H2O.mw.value == 18.0153E-3 assert model.params.H2O.pressure_crit.value == 220.64E5 assert model.params.H2O.temperature_crit.value == 647 assert model.params.CO2.mw.value == 44.0095E-3 assert model.params.CO2.pressure_crit.value == 73.825E5 assert model.params.CO2.temperature_crit.value == 304.23 assert_units_consistent(model)
def create_model(): m = ConcreteModel() m.a = Param(initialize=-0.2, mutable=True) m.H = Param(initialize=0.5, mutable=True) m.T = 15 m.t = ContinuousSet(bounds=(0, m.T)) m.x = Var(m.t) m.F = Var(m.t) m.u = Var(m.t, initialize=0, bounds=(-0.2, 0)) m.dx = DerivativeVar(m.x, wrt=m.t) m.df0 = DerivativeVar(m.F, wrt=m.t) m.x[0].fix(5) m.F[0].fix(0) def _x(m, t): return m.dx[t] == m.a * m.x[t] + m.u[t] m.x_dot = Constraint(m.t, rule=_x) def _f0(m, t): return m.df0[t] == 0.25 * m.u[t]**2 m.FDiffCon = Constraint(m.t, rule=_f0) def _Cost(m): return 0.5 * m.H * m.x[m.T]**2 + m.F[m.T] m.J = Objective(rule=_Cost) return m
def test_GDP_nonlinear_objective(self): m = ConcreteModel() m.x = Var(bounds=(-1, 10)) m.y = Var(bounds=(2, 3)) m.d = Disjunction(expr=[[m.x + m.y >= 5], [m.x - m.y <= 3]]) m.o = Objective(expr=m.x**2) SolverFactory('gdpopt').solve(m, strategy='LOA', mip_solver=mip_solver, nlp_solver=nlp_solver) self.assertAlmostEqual(value(m.o), 0) m = ConcreteModel() m.x = Var(bounds=(-1, 10)) m.y = Var(bounds=(2, 3)) m.d = Disjunction(expr=[[m.x + m.y >= 5], [m.x - m.y <= 3]]) m.o = Objective(expr=-m.x**2, sense=maximize) SolverFactory('gdpopt').solve(m, strategy='LOA', mip_solver=mip_solver, nlp_solver=nlp_solver) self.assertAlmostEqual(value(m.o), 0)
def test_h2_props(): m = ConcreteModel() m.fs = FlowsheetBlock(default={"dynamic": False}) m.fs.props = GenericParameterBlock(default=configuration) m.fs.state = m.fs.props.build_state_block(m.fs.config.time, default={"defined_state": True}) # Fix state m.fs.state[0].flow_mol.fix(1) m.fs.state[0].mole_frac_comp.fix(1) m.fs.state[0].temperature.fix(300) m.fs.state[0].pressure.fix(101325) # Initialize state m.fs.state.initialize() solver = get_solver() results = solver.solve(m.fs) # Check for optimal solution assert results.solver.termination_condition == \ TerminationCondition.optimal assert results.solver.status == SolverStatus.ok # Verify against NIST tables assert value(m.fs.state[0].cp_mol) == pytest.approx(28.85, rel=1e-2) assert value(m.fs.state[0].enth_mol) == pytest.approx(53.51, rel=1e-2) assert value(m.fs.state[0].entr_mol) == pytest.approx(130.9, rel=1e-2) assert (value(m.fs.state[0].gibbs_mol / m.fs.state[0].temperature) == pytest.approx(-130.7, rel=1e-2)) # Try another temeprature m.fs.state[0].temperature.fix(500) results = solver.solve(m.fs) # Check for optimal solution assert results.solver.termination_condition == \ TerminationCondition.optimal assert results.solver.status == SolverStatus.ok assert value(m.fs.state[0].cp_mol) == pytest.approx(29.26, rel=1e-2) assert value(m.fs.state[0].enth_mol) == pytest.approx(5880, rel=1e-2) assert value(m.fs.state[0].entr_mol) == pytest.approx(145.7, rel=1e-2) assert (value(m.fs.state[0].gibbs_mol / m.fs.state[0].temperature) == pytest.approx(-134.0, rel=1e-2)) # Try another temeprature m.fs.state[0].temperature.fix(900) results = solver.solve(m.fs) # Check for optimal solution assert results.solver.termination_condition == \ TerminationCondition.optimal assert results.solver.status == SolverStatus.ok assert value(m.fs.state[0].cp_mol) == pytest.approx(29.88, rel=1e-2) assert value(m.fs.state[0].enth_mol) == pytest.approx(17680, rel=1e-2) assert value(m.fs.state[0].entr_mol) == pytest.approx(163.1, rel=1e-2) assert (value(m.fs.state[0].gibbs_mol / m.fs.state[0].temperature) == pytest.approx(-143.4, rel=1e-2))
def test_non_supported_single_index(self): # Can't simulate a model with no ContinuousSet m = ConcreteModel() with self.assertRaises(DAE_Error): Simulator(m) # Can't simulate a model with multiple ContinuousSets m = ConcreteModel() m.s = ContinuousSet(bounds=(0, 10)) m.t = ContinuousSet(bounds=(0, 5)) with self.assertRaises(DAE_Error): Simulator(m) # Can't simulate a model with no Derivatives m = ConcreteModel() m.t = ContinuousSet(bounds=(0, 10)) with self.assertRaises(DAE_Error): Simulator(m) # Can't simulate a model with multiple RHS for a derivative m = self.m def _diffeq(m, t): return m.dv[t] == m.v[t]**2 + m.v[t] m.con1 = Constraint(m.t, rule=_diffeq) m.con2 = Constraint(m.t, rule=_diffeq) with self.assertRaises(DAE_Error): Simulator(m) m.del_component('con1') m.del_component('con2') # Can't simulate a model with multiple derivatives in an # equation m = self.m def _diffeq(m, t): return m.dv[t] == m.dv[t] + m.v[t]**2 m.con1 = Constraint(m.t, rule=_diffeq) with self.assertRaises(DAE_Error): Simulator(m) m.del_component('con1')
def m(self): m = ConcreteModel() m.a = Var() m.acon = Constraint(rule=m.a >= 10) m.bcon = Constraint(rule=m.a == 5) return m
def m(self): m = ConcreteModel() m.a = Var() m.b = Var() m.abcon = Constraint(rule=m.a + m.b == 10) return m
def runTrimModel(singleInputData, mill): # Generate Raw Data files from input sheet widthDemand = createWidthDemand(singleInputData) [patterns, wasteList] = createPatternsAndWaste(singleInputData, mill) # Reading in Data using the cutstock_util sl = getStockLength(mill) # wasteList = getWasteList() cutcount = getCutCount(widthDemand) patcount = getPatCount(wasteList) Cuts = getCuts(cutcount) Patterns = getPatterns(patcount) PriceSheet = getPriceSheetData() #SheetsAvail = getSheetsAvail() CutDemand = getCutDemand(widthDemand, cutcount) CutsInPattern = getCutsInPattern(patterns, cutcount, patcount) ######################################## #CutsInPattern = makeDict([Cuts,Patterns],CutsInPattern) tmp = {} for i in range(len(Cuts)): tmp[Cuts[i]] = {} for j in range(len(CutsInPattern[i])): tmp[Cuts[i]][Patterns[j]] = CutsInPattern[i][j] CutsInPattern = tmp ######################################## #CutDemand = makeDict([Cuts],CutDemand) tmp = {} for i in range(len(Cuts)): tmp[Cuts[i]] = CutDemand[i] CutDemand = tmp model = ConcreteModel(name="CutStock Problem") #Defining Variables model.SheetsCut = Var() model.TotalCost = Var() model.PatternCount = Var(Patterns, domain=NonNegativeIntegers, bounds=(0, None)) model.ExcessCuts = Var(Cuts, bounds=(0, None)) #objective model.objective = Objective(expr=1.0 * model.TotalCost) #Constraints model.TotCost = Constraint( expr=model.TotalCost == model.SheetsCut) #PriceSheet* model.SheetsCut) #model.RawAvail = Constraint(expr = model.SheetsCut <= SheetsAvail) model.Sheets = Constraint( expr=summation(model.PatternCount) == model.SheetsCut) model.CutReq = Constraint(Cuts, noruleinit=True) for c in Cuts: model.CutReq.add(c, expr=sum(CutsInPattern[c][p] * model.PatternCount[p] for p in Patterns) == CutDemand[c] + model.ExcessCuts[c]) instance = model #.create() solver = 'cbc' # cbc or glpk opt = pyomo.opt.SolverFactory(solver) opt.options[{'cbc': 'seconds', 'glpk': 'tmlim'}[solver]] = 30 results = opt.solve(instance) ##results = opt.solve(model) instance.solutions.load_from(results) # return (results) # print "Status:", results.solver.status # print "Termination Condition:", results.solver[0]['Termination condition'] # print "Minimum total cost:", value(instance.objective) trimWaste = 0 sideRollWaste = 0 cost = 0 for pat in model.PatternCount: v = model.PatternCount[pat].value if v > 0: if wasteList[int(pat[1:]) - 1] < 15: trimWaste += wasteList[int(pat[1:]) - 1] * v if wasteList[int(pat[1:]) - 1] >= 4: cost += wasteList[int(pat[1:]) - 1] * v * (332.17 / 17.5) else: cost += wasteList[int(pat[1:]) - 1] * v * (605 / 17.5) if wasteList[int(pat[1:]) - 1] >= 15: sideRollWaste += wasteList[int(pat[1:]) - 1] * v if wasteList[int(pat[1:]) - 1] <= 24.5: cost += wasteList[int(pat[1:]) - 1] * v * (258.63 / 17.5) else: cost += wasteList[int(pat[1:]) - 1] * v * (196.29 / 17.5) trimWastePer = trimWaste / (value(instance.objective) * sl) return [ round(trimWaste, 2), round(trimWastePer, 3), round(sideRollWaste, 2), round(cost, 2) ]
def __init__(self, cov, occ, groups_4digit, allele_table, beta, t_max_allele=2, solver="glpk", threads=1, verbosity=0): """ Constructor """ self.__allele_table = allele_table self.__beta = float(beta) self.__t_max_allele = t_max_allele self.__solver = SolverFactory(solver) self.__threads = threads self.__opts = {"threads": threads} if threads > 1 else {} self.__verbosity = verbosity self.__changed = True # model needs to know if it changed from last run or not self.__ks = 1 self.__groups_4digit = groups_4digit loci_alleles = defaultdict(list) for type_4digit, group_alleles in groups_4digit.iteritems(): # print type_4digit, group_alleles loci_alleles[type_4digit.split('*')[0]].extend(group_alleles) loci = loci_alleles self.__allele_to_4digit = { allele: type_4digit for type_4digit, group in groups_4digit.iteritems() for allele in group } ''' generates the basic ILP model ''' model = ConcreteModel() # init Sets model.LociNames = Set(initialize=loci.keys()) model.Loci = Set(model.LociNames, initialize=lambda m, l: loci[l]) L = list(itertools.chain(*loci.values())) reconst = {allele_id: 0.01 for allele_id in L if '_' in allele_id} R = set([r for (r, _) in cov.keys()]) model.L = Set(initialize=L) model.R = Set(initialize=R) # init Params model.cov = Param(model.R, model.L, initialize=lambda model, r, a: cov.get((r, a), 0)) model.reconst = Param(model.L, initialize=lambda model, a: reconst.get(a, 0)) model.occ = Param(model.R, initialize=occ) model.t_allele = Param(initialize=self.__t_max_allele, mutable=True) model.beta = Param( initialize=self.__beta, validate=lambda val, model: 0.0 <= float(self.__beta) <= 0.999, mutable=True) model.nof_loci = Param(initialize=len(loci)) # init variables model.x = Var(model.L, domain=Binary) model.y = Var(model.R, domain=Binary) model.re = Var(model.R, bounds=(0.0, None)) model.hetero = Var(bounds=(0.0, model.nof_loci)) # init objective model.read_cov = Objective(rule=lambda model: sum( model.occ[r] * (model.y[r] - model.beta * (model.re[r])) for r in model.R) - sum(model.reconst[a] * model.x[a] for a in model.L), sense=maximize) # init Constraints model.max_allel_selection = Constraint( model.LociNames, rule=lambda model, l: sum(model.x[a] for a in model.Loci[l] ) <= model.t_allele) model.min_allel_selection = Constraint( model.LociNames, rule=lambda model, l: sum(model.x[a] for a in model.Loci[l]) >= 1) model.is_read_cov = Constraint( model.R, rule=lambda model, r: sum(model.cov[r, a] * model.x[a] for a in model.L) >= model.y[r]) model.heterozygot_count = Constraint( rule=lambda model: model.hetero >= sum(model.x[a] for a in model.L ) - model.nof_loci) # regularization constraints model.reg1 = Constraint( model.R, rule=lambda model, r: model.re[r] <= model.nof_loci * model.y[r]) model.reg2 = Constraint( model.R, rule=lambda model, r: model.re[r] <= model.hetero) model.reg3 = Constraint(model.R, rule=lambda model, r: model.re[r] >= model. hetero - model.nof_loci * (1 - model.y[r])) # generate constraint list for solution enumeration model.c = ConstraintList() # Generate instance. Used to be .create() but deprecated since, # as ConcreteModels are instances on their own now. self.__instance = model
def build_model_pyomo(resite, params: Dict): """Model build-up using pyomo""" from pyomo.environ import ConcreteModel, NonNegativeReals, Var from resite.models.pyomo_utils import capacity_bigger_than_existing, minimize_total_cost data = resite.data_dict load = data["load"].values regions = resite.regions technologies = resite.technologies tech_points_tuples = list(resite.tech_points_tuples) time_slices = define_time_slices(params["time_resolution"], resite.timestamps) generation_potential_df = data["cap_factor_df"] * data["cap_potential_ds"] costs_df = get_cost_df(technologies, resite.timestamps) model = ConcreteModel() # - Parameters - # covered_load_perc_per_region = dict(zip(regions, params["perc_per_region"])) covered_load_perc_global = params['perc_global'] # - Variables - # # Energy not served model.ens = Var(list(regions), np.arange(len(resite.timestamps)), within=NonNegativeReals) # Portion of capacity at each location for each technology model.y = Var(tech_points_tuples, within=NonNegativeReals, bounds=(0, 1)) # Generation at each time step model.p = Var(tech_points_tuples, np.arange(len(resite.timestamps)), within=NonNegativeReals) # - Constraints - # # Generation limited by generation potential from pyomo.environ import Constraint def generation_limit(model, tech, lon, lat, t): return model.p[tech, lon, lat, t] <= model.y[ tech, lon, lat] * generation_potential_df.iloc[t][(tech, lon, lat)] model.generation_limit = Constraint(tech_points_tuples, np.arange(len(resite.timestamps)), rule=generation_limit) # Create generation dictionary for building speed up # Compute a sum of generation per time-step per region region_p_dict = dict.fromkeys(regions) for region in regions: # Get generation potential for points in region for each techno region_tech_points = resite.tech_points_regions_ds[ resite.tech_points_regions_ds == region].index region_p_sum = pd.Series([ sum(model.p[tech, lon, lat, t] for tech, lon, lat in region_tech_points) for t in np.arange(len(resite.timestamps)) ], index=np.arange(len(resite.timestamps))) region_p_dict[region] = region_p_sum # Impose a certain percentage of the load to be covered over each time slice # Per region def generation_check_region_rule(model, region, u): return sum(region_p_dict[region][t] for t in time_slices[u]) + \ sum(model.ens[region, t] for t in time_slices[u]) >= \ sum(load[t, regions.index(region)] for t in time_slices[u]) * covered_load_perc_per_region[region] model.generation_check_region = Constraint( regions, np.arange(len(time_slices)), rule=generation_check_region_rule) # Global def generation_check_global_rule(model, u): return sum(region_p_dict[r][t] for t in time_slices[u] for r in regions) + \ sum(model.ens[r, t] for t in time_slices[u] for r in regions) >= \ sum(load[t, regions.index(r)] for t in time_slices[u] for r in regions) * covered_load_perc_global model.generation_check_global = Constraint( np.arange(len(time_slices)), rule=generation_check_global_rule) # Percentage of capacity installed must be bigger than existing percentage existing_cap_percentage_ds = data["existing_cap_ds"].divide( data["cap_potential_ds"]) model.potential_constraint = capacity_bigger_than_existing( model, existing_cap_percentage_ds, tech_points_tuples) # - Objective - # # Minimize the capacity that is deployed model.objective = minimize_total_cost(model, data["cap_potential_ds"], regions, np.arange(len(resite.timestamps)), costs_df) resite.instance = model
def make_model(horizon=6, ntfe=60, ntcp=2, inlet_E=11.91, inlet_S=12.92, steady=False, bounds=False): time_set = [0, horizon] m = ConcreteModel(name='CSTR model for testing') if steady: m.fs = FlowsheetBlock(default={'dynamic': False}) else: m.fs = FlowsheetBlock(default={'dynamic': True, 'time_set': time_set}) m.fs.properties = AqueousEnzymeParameterBlock() m.fs.reactions = EnzymeReactionParameterBlock( default={'property_package': m.fs.properties}) m.fs.cstr = CSTR( default={ 'has_holdup': True, 'property_package': m.fs.properties, 'reaction_package': m.fs.reactions, 'material_balance_type': MaterialBalanceType.componentTotal, 'energy_balance_type': EnergyBalanceType.enthalpyTotal, 'momentum_balance_type': MomentumBalanceType.none, 'has_heat_of_reaction': True }) m.fs.mixer = Mixer( default={ 'property_package': m.fs.properties, 'material_balance_type': MaterialBalanceType.componentTotal, 'momentum_mixing_type': MomentumMixingType.none, 'num_inlets': 2, 'inlet_list': ['S_inlet', 'E_inlet'] }) # Allegedly the proper energy balance is being used... # Time discretization if not steady: disc = TransformationFactory('dae.collocation') disc.apply_to(m, wrt=m.fs.time, nfe=ntfe, ncp=ntcp, scheme='LAGRANGE-RADAU') # Fix geometry variables m.fs.cstr.volume[0].fix(1.0) # Fix initial conditions: if not steady: for p, j in m.fs.properties.phase_list * m.fs.properties.component_list: if j == 'Solvent': continue m.fs.cstr.control_volume.material_holdup[0, p, j].fix(0.001) # Note: Model does not solve when initial conditions are empty tank m.fs.mixer.E_inlet.conc_mol.fix(0) m.fs.mixer.S_inlet.conc_mol.fix(0) for t, j in m.fs.time * m.fs.properties.component_list: if j == 'E': m.fs.mixer.E_inlet.conc_mol[t, j].fix(inlet_E) elif j == 'S': m.fs.mixer.S_inlet.conc_mol[t, j].fix(inlet_S) m.fs.mixer.E_inlet.flow_vol.fix(0.1) m.fs.mixer.S_inlet.flow_vol.fix(2.1) m.fs.mixer.E_inlet.conc_mol[:, 'Solvent'].fix(1.) m.fs.mixer.S_inlet.conc_mol[:, 'Solvent'].fix(1.) m.fs.mixer.E_inlet.temperature.fix(290) m.fs.mixer.S_inlet.temperature.fix(310) m.fs.inlet = Arc(source=m.fs.mixer.outlet, destination=m.fs.cstr.inlet) # This constraint is in lieu of tracking the CSTR's level and allowing # the outlet flow rate to be another degree of freedom. # ^ Not sure how to do this in IDAES. @m.fs.cstr.Constraint(m.fs.time, doc='Total flow rate balance') def total_flow_balance(cstr, t): return (cstr.inlet.flow_vol[t] == cstr.outlet.flow_vol[t]) # Specify initial condition for energy if not steady: m.fs.cstr.control_volume.energy_holdup[m.fs.time.first(), 'aq'].fix(300) TransformationFactory('network.expand_arcs').apply_to(m.fs) if bounds: m.fs.mixer.E_inlet.flow_vol.setlb(0.01) m.fs.mixer.E_inlet.flow_vol.setub(1.0) m.fs.mixer.S_inlet.flow_vol.setlb(0.5) m.fs.mixer.S_inlet.flow_vol.setub(5.0) m.fs.cstr.control_volume.material_holdup.setlb(0) holdup = m.fs.cstr.control_volume.material_holdup for t in m.fs.time: holdup[t, 'aq', 'S'].setub(20) holdup[t, 'aq', 'E'].setub(1) holdup[t, 'aq', 'P'].setub(5) holdup[t, 'aq', 'C'].setub(5) return m
def test_boiler_hx(): m = ConcreteModel() m.fs = FlowsheetBlock(default={"dynamic": False}) m.fs.properties = PhysicalParameterTestBlock() m.fs.prop_steam = iapws95.Iapws95ParameterBlock() m.fs.prop_fluegas = FlueGasParameterBlock() m.fs.unit = BoilerHeatExchanger(default={ "side_1_property_package": m.fs.prop_steam, "side_2_property_package": m.fs.prop_fluegas, "has_pressure_change": True, "has_holdup": False, "delta_T_method": DeltaTMethod.counterCurrent, "tube_arrangement": TubeArrangement.inLine, "side_1_water_phase": "Liq", "has_radiation": True}) # Set inputs h = value(iapws95.htpx(773.15*pyunits.K, 2.5449e7*pyunits.Pa)) print(h) m.fs.unit.side_1_inlet.flow_mol[0].fix(24678.26) # mol/s m.fs.unit.side_1_inlet.enth_mol[0].fix(h) # J/mol m.fs.unit.side_1_inlet.pressure[0].fix(2.5449e7) # Pascals # FLUE GAS Inlet from Primary Superheater FGrate = 28.3876e3*0.18 # mol/s equivalent of ~1930.08 klb/hr # Use FG molar composition to set component flow rates (baseline report) m.fs.unit.side_2_inlet.flow_mol_comp[0, "H2O"].fix(FGrate*8.69/100) m.fs.unit.side_2_inlet.flow_mol_comp[0, "CO2"].fix(FGrate*14.49/100) m.fs.unit.side_2_inlet.flow_mol_comp[0, "N2"].fix(FGrate*74.34/100) m.fs.unit.side_2_inlet.flow_mol_comp[0, "O2"].fix(FGrate*2.47/100) m.fs.unit.side_2_inlet.flow_mol_comp[0, "NO"].fix(FGrate*0.0006) m.fs.unit.side_2_inlet.flow_mol_comp[0, "SO2"].fix(FGrate*0.002) m.fs.unit.side_2_inlet.temperature[0].fix(1102.335) m.fs.unit.side_2_inlet.pressure[0].fix(100145) # Primary Superheater ITM = 0.0254 # inch to meter conversion m.fs.unit.tube_di.fix((2.5-2*0.165)*ITM) m.fs.unit.tube_thickness.fix(0.165*ITM) m.fs.unit.pitch_x.fix(3*ITM) # gas path transverse width 54.78 ft / number of columns m.fs.unit.pitch_y.fix(54.78/108*12*ITM) m.fs.unit.tube_length.fix(53.13*12*ITM) m.fs.unit.tube_nrow.fix(20*2) m.fs.unit.tube_ncol.fix(108) m.fs.unit.nrow_inlet.fix(4) m.fs.unit.delta_elevation.fix(50) m.fs.unit.tube_r_fouling = 0.000176 # (0.001 h-ft^2-F/BTU) m.fs.unit.tube_r_fouling = 0.003131 # (0.03131 - 0.1779 h-ft^2-F/BTU) if m.fs.unit.config.has_radiation is True: m.fs.unit.emissivity_wall.fix(0.7) # wall emissivity # correction factor for overall heat transfer coefficient m.fs.unit.fcorrection_htc.fix(1.5) # correction factor for pressure drop calc tube side m.fs.unit.fcorrection_dp_tube.fix(1.0) # correction factor for pressure drop calc shell side m.fs.unit.fcorrection_dp_shell.fix(1.0) assert degrees_of_freedom(m) == 0 m.fs.unit.initialize() results = solver.solve(m) # Check for optimal solution assert results.solver.termination_condition == \ TerminationCondition.optimal assert results.solver.status == SolverStatus.ok assert value(m.fs.unit.side_1.properties_out[0].temperature) == \ pytest.approx(588.07, 1) assert value(m.fs.unit.side_2.properties_out[0].temperature) == \ pytest.approx(573.07, 1)
def test_var_not_in_model(model): m2 = ConcreteModel() with pytest.raises(ConfigurationError): homotopy(m2, [model.x], [20])
def test_keys_empty(self): """Test keys method""" model = ConcreteModel() model.o = Objective() self.assertEqual(list(model.o.keys()), [])
def test_is_feasible_function(self): m = ConcreteModel() m.x = Var(bounds=(0, 3), initialize=2) m.c = Constraint(expr=m.x == 2) self.assertTrue(is_feasible(m, GDPoptSolver.CONFIG())) m.c2 = Constraint(expr=m.x <= 1) self.assertFalse(is_feasible(m, GDPoptSolver.CONFIG())) m = ConcreteModel() m.x = Var(bounds=(0, 3), initialize=2) m.c = Constraint(expr=m.x >= 5) self.assertFalse(is_feasible(m, GDPoptSolver.CONFIG())) m = ConcreteModel() m.x = Var(bounds=(3, 3), initialize=2) self.assertFalse(is_feasible(m, GDPoptSolver.CONFIG())) m = ConcreteModel() m.x = Var(bounds=(0, 1), initialize=2) self.assertFalse(is_feasible(m, GDPoptSolver.CONFIG())) m = ConcreteModel() m.x = Var(bounds=(0, 1), initialize=2) m.d = Disjunct() with self.assertRaisesRegexp(NotImplementedError, "Found active disjunct"): is_feasible(m, GDPoptSolver.CONFIG())
def main(): """ Make the flowsheet object, fix some variables, and solve the problem """ # Create a Concrete Model as the top level object m = ConcreteModel() # Add a flowsheet object to the model m.fs = FlowsheetBlock(default={"dynamic": False}) # Add property packages to flowsheet library m.fs.thermo_params = thermo_props.SaponificationParameterBlock() m.fs.reaction_params = reaction_props.SaponificationReactionParameterBlock( default={"property_package": m.fs.thermo_params}) # Create unit models m.fs.Tank1 = CSTR( default={ "property_package": m.fs.thermo_params, "reaction_package": m.fs.reaction_params, "has_equilibrium_reactions": False, "has_heat_of_reaction": True, "has_heat_transfer": True, "has_pressure_change": False }) m.fs.Tank2 = CSTR( default={ "property_package": m.fs.thermo_params, "reaction_package": m.fs.reaction_params, "has_equilibrium_reactions": False, "has_heat_of_reaction": True, "has_heat_transfer": True, "has_pressure_change": False }) # Make Streams to connect units m.fs.stream = Arc(source=m.fs.Tank1.outlet, destination=m.fs.Tank2.inlet) TransformationFactory("network.expand_arcs").apply_to(m) # Set inlet and operating conditions, and some initial conditions. m.fs.Tank1.inlet.flow_vol[0].fix(1.0) m.fs.Tank1.inlet.conc_mol_comp[0, "H2O"].fix(55388.0) m.fs.Tank1.inlet.conc_mol_comp[0, "NaOH"].fix(100.0) m.fs.Tank1.inlet.conc_mol_comp[0, "EthylAcetate"].fix(100.0) m.fs.Tank1.inlet.conc_mol_comp[0, "SodiumAcetate"].fix(0.0) m.fs.Tank1.inlet.conc_mol_comp[0, "Ethanol"].fix(0.0) m.fs.Tank1.inlet.temperature.fix(303.15) m.fs.Tank1.inlet.pressure.fix(101325.0) m.fs.Tank1.volume.fix(1.0) m.fs.Tank1.heat_duty.fix(0.0) m.fs.Tank2.volume.fix(1.0) m.fs.Tank2.heat_duty.fix(0.0) # Initialize Units m.fs.Tank1.initialize() m.fs.Tank2.initialize( state_args={ "flow_vol": 1.0, "conc_mol_comp": { "H2O": 55388.0, "NaOH": 100.0, "EthylAcetate": 100.0, "SodiumAcetate": 0.0, "Ethanol": 0.0 }, "temperature": 303.15, "pressure": 101325.0 }) # Create a solver solver = SolverFactory('ipopt') results = solver.solve(m, tee=False) # Print results # print(results) # print() # print("Results") # print() # print("Tank 1 Outlet") # m.fs.Tank1.outlet.display() # print() # print("Tank 2 Outlet") # m.fs.Tank2.outlet.display() report_statistics(m) # For testing purposes return (m, results)
def test_len_empty(self): """Test len method""" model = ConcreteModel() model.o = Objective() self.assertEqual(len(model.o), 0)
def create_model(self): model = ConcreteModel() model.A = Set(initialize=[1, 2, 3, 4]) return model
def test_rule(self): def rule1(model): return [] model = ConcreteModel() try: model.o = Objective(rule=rule1) self.fail("Error generating objective") except Exception: pass # model = ConcreteModel() def rule1(model): return 1.1 model = ConcreteModel() model.o = Objective(rule=rule1) self.assertEqual(model.o(), 1.1) # model = ConcreteModel() def rule1(model, i): return 1.1 model = ConcreteModel() model.a = Set(initialize=[1, 2, 3]) try: model.o = Objective(model.a, rule=rule1) except Exception: self.fail("Error generating objective")
def __init__(self, y, x, Cutactive, cet='addi', fun='prod', rts='vrs'): """ y : Output variable x : Input variables cet = "addi" : Additive composite error term = "mult" : Multiplicative composite error term fun = "prod" : Production frontier = "cost" : Cost frontier rts = "vrs" : Variable returns to scale = "crs" : Constant returns to scale """ # TODO(error/warning handling): Check the configuration of the model exist self.x = x.tolist() self.y = y.tolist() self.cet = cet self.fun = fun self.rts = rts if type(self.x[0]) != list: self.x = [] for x_value in x.tolist(): self.x.append([x_value]) self.Cutactive = Cutactive # Initialize the CNLS model self.__model__ = ConcreteModel() # Initialize the sets self.__model__.I = Set(initialize=range(len(self.y))) self.__model__.J = Set(initialize=range(len(self.x[0]))) # Initialize the variables self.__model__.alpha1 = Var(self.__model__.I, doc='alpha1') self.__model__.beta1 = Var(self.__model__.I, self.__model__.J, bounds=(0.0, None), doc='beta1') self.__model__.epsilon1 = Var(self.__model__.I, doc='residual1') self.__model__.frontier1 = Var(self.__model__.I, bounds=(0.0, None), doc='estimated frontier1') # Setup the objective function and constraints self.__model__.objective1 = Objective(rule=self.__objective_rule1(), sense=minimize, doc='objective function1') self.__model__.regression_rule1 = Constraint( self.__model__.I, rule=self.__regression_rule1(), doc='regression equation1') if self.cet == "mult": self.__model__.log_rule1 = Constraint( self.__model__.I, rule=self.__log_rule1(), doc='log-transformed regression equation1') self.__model__.afriat_rule1 = Constraint( self.__model__.I, rule=self.__afriat_rule1(), doc='elementary Afriat approach1') self.__model__.sweet_rule1 = Constraint(self.__model__.I, self.__model__.I, rule=self.__sweet_rule1(), doc='sweet spot approach1') # Optimize model self.optimization_status = 0 self.problem_status = 0
def __init__(self, y, x, tau, cutactive, cet=CET_ADDI, fun=FUN_PROD, rts=RTS_VRS): """CQR+G model Args: y (float): output variable. x (float): input variables. tau (float): quantile. cutactive (float): active concavity constraint. cet (String, optional): CET_ADDI (additive composite error term) or CET_MULT (multiplicative composite error term). Defaults to CET_ADDI. fun (String, optional): FUN_PROD (production frontier) or FUN_COST (cost frontier). Defaults to FUN_PROD. rts (String, optional): RTS_VRS (variable returns to scale) or RTS_CRS (constant returns to scale). Defaults to RTS_VRS. """ # TODO(error/warning handling): Check the configuration of the model exist self.x = x self.y = y self.tau = tau self.cet = cet self.fun = fun self.rts = rts self.cutactive = cutactive # Initialize the CNLS model self.__model__ = ConcreteModel() # Initialize the sets self.__model__.I = Set(initialize=range(len(self.y))) self.__model__.J = Set(initialize=range(len(self.x[0]))) # Initialize the variables self.__model__.alpha = Var(self.__model__.I, doc='alpha') self.__model__.beta = Var(self.__model__.I, self.__model__.J, bounds=(0.0, None), doc='beta') self.__model__.epsilon = Var(self.__model__.I, doc='residual') self.__model__.epsilon_plus = Var(self.__model__.I, bounds=(0.0, None), doc='positive error term') self.__model__.epsilon_minus = Var(self.__model__.I, bounds=(0.0, None), doc='negative error term') self.__model__.frontier = Var(self.__model__.I, bounds=(0.0, None), doc='estimated frontier') # Setup the objective function and constraints self.__model__.objective = Objective(rule=self.__objective_rule(), sense=minimize, doc='objective function') self.__model__.error_decomposition = Constraint( self.__model__.I, rule=self.__error_decomposition(), doc='decompose error term') self.__model__.regression_rule = Constraint( self.__model__.I, rule=self.__regression_rule(), doc='regression equation') if self.cet == CET_MULT: self.__model__.log_rule = Constraint( self.__model__.I, rule=self.__log_rule(), doc='log-transformed regression equation') self.__model__.afriat_rule = Constraint( self.__model__.I, rule=self.__afriat_rule(), doc='elementary Afriat approach') self.__model__.sweet_rule = Constraint(self.__model__.I, self.__model__.I, rule=self.__sweet_rule(), doc='sweet spot approach') # Optimize model self.optimization_status = 0 self.problem_status = 0
def test_temp_swing(self): # Create a flash model with the CO2-H2O property package m = ConcreteModel() m.fs = FlowsheetBlock(default={"dynamic": False}) m.fs.properties = GenericParameterBlock(default=configuration) m.fs.flash = Flash(default={"property_package": m.fs.properties}) # Fix inlet stream state variables m.fs.flash.inlet.flow_mol.fix(9.89433124673833) # mol/s m.fs.flash.inlet.mole_frac_comp[0, 'CO2'].fix(0.13805801934749645) m.fs.flash.inlet.mole_frac_comp[0, 'H2O'].fix(0.8619419806525035) m.fs.flash.inlet.pressure.fix(183430) # Pa m.fs.flash.inlet.temperature.fix(396.79057912844183) # K # Fix flash and its outlet conditions m.fs.flash.deltaP.fix(0) m.fs.flash.vap_outlet.temperature.fix(313.15) # Initialize the flash model m.fs.flash.initialize() # Create a dictionary of expected solution for flash outlet temperature # sweep temp_range = list(np.linspace(313, 396)) expected_vapor_frac = [ 0.14388, 0.14445, 0.14508, 0.14576, 0.1465, 0.14731, 0.14818, 0.14913, 0.15017, 0.15129, 0.15251, 0.15384, 0.15528, 0.15685, 0.15856, 0.16042, 0.16245, 0.16467, 0.16709, 0.16974, 0.17265, 0.17584, 0.17935, 0.18323, 0.18751, 0.19226, 0.19755, 0.20346, 0.21008, 0.21755, 0.22601, 0.23565, 0.24673, 0.25956, 0.27456, 0.29229, 0.31354, 0.33942, 0.37157, 0.4125, 0.46628, 0.53993, 0.64678, 0.81547, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ] expected_heat_duty = [ -396276.55508, -394859.42896, -393421.28226, -391960.40602, -390474.94512, -388962.88119, -387422.01297, -385849.93371, -384244.00483, -382601.32549, -380918.69691, -379192.58068, -377419.04976, -375593.73054, -373711.73419, -371767.57480, -369755.07135, -367667.22968, -365496.09940, -363232.59958, -360866.30485, -358385.18097, -355775.25563, -353020.20490, -350100.82935, -346994.38367, -343673.70980, -340106.10300, -336251.80960, -332062.00898, -327476.06061, -322417.68382, -316789.55435, -310465.49473, -303278.90949, -295005.17406, -285333.93764, -273823.89005, -259825.51107, -242341.82570, -219760.16114, -189290.02362, -145647.55666, -77469.59283, -3219.88910, -2631.66067, -2043.09220, -1454.17760, -864.91585, -275.30623 ] outvals = zip(expected_vapor_frac, expected_heat_duty) expected_sol = dict(zip(temp_range, outvals)) # Solve the model for a range of flash outlet temperatures # Perform flash outlet temperature sweep and test the solution for t in temp_range: m.fs.flash.vap_outlet.temperature.fix(t) res = solver.solve(m) assert res.solver.termination_condition == "optimal" frac = value(m.fs.flash.vap_outlet.flow_mol[0]) \ / value(m.fs.flash.inlet.flow_mol[0]) assert frac == pytest.approx(expected_sol[t][0], abs=1e-4) hduty = value(m.fs.flash.heat_duty[0]) assert hduty == pytest.approx(expected_sol[t][1], rel=1e-4)
# This software is distributed under the 3-clause BSD License. # ___________________________________________________________________________ # # Author: Gabe Hackebeil # Purpose: For regression testing to ensure that the Pyomo # NL writer properly reclassifies nonlinear expressions # as linear or trivial when fixing variables or params # cause such a situation. # # This test model relies on the gjh_asl_json executable. It # will not solve if sent to a real optimizer. # from pyomo.environ import ConcreteModel, Var, Param, Objective, Constraint, simple_constraint_rule model = ConcreteModel() model.x = Var() model.y = Var(initialize=0.0) model.z = Var() model.p = Param(initialize=0.0, mutable=True) model.q = Param(initialize=0.0, mutable=False) model.y.fixed = True model.obj = Objective(expr=model.x) model.con1 = Constraint(expr=model.x * model.y * model.z + model.x == 1.0) model.con2 = Constraint(expr=model.x * model.p * model.z + model.x == 1.0) model.con3 = Constraint(expr=model.x * model.q * model.z + model.x == 1.0) # Pyomo differs from AMPL in these cases that involve immutable params (q).
def model(self): model = ConcreteModel() model.prop = self.pparam_construct() model.te = self.pparam.HelmholtzThermoExpressions( model, parameters=model.prop) return model
def test_bad_option(): m = ConcreteModel() m.fs = FlowsheetBlock(default={"dynamic": False}) with pytest.raises(KeyError): m.fs.unit = HeatExchanger(default={"I'm a bad option": "hot"})
def main(): m = ConcreteModel() m.fs = FlowsheetBlock(default={"dynamic": False}) # Set up thermo props and reaction props m.fs.gas_properties = GasPhaseParameterBlock() m.fs.solid_properties = SolidPhaseParameterBlock() m.fs.hetero_reactions = HeteroReactionParameterBlock( default={"solid_property_package": m.fs.solid_properties, "gas_property_package": m.fs.gas_properties}) m.fs.MB = MBR(default={ "transformation_method": "dae.collocation", "gas_phase_config": {"property_package": m.fs.gas_properties}, "solid_phase_config": {"property_package": m.fs.solid_properties, "reaction_package": m.fs.hetero_reactions }}) # Fix bed geometry variables m.fs.MB.bed_diameter.fix(6.5) # m m.fs.MB.bed_height.fix(5) # m # Fix inlet port variables for gas and solid m.fs.MB.gas_inlet.flow_mol[0].fix(128.20513) # mol/s m.fs.MB.gas_inlet.temperature[0].fix(298.15) # K m.fs.MB.gas_inlet.pressure[0].fix(2.00E5) # Pa = 1E5 bar m.fs.MB.gas_inlet.mole_frac_comp[0, "CO2"].fix(0.02499) m.fs.MB.gas_inlet.mole_frac_comp[0, "H2O"].fix(0.00001) m.fs.MB.gas_inlet.mole_frac_comp[0, "CH4"].fix(0.975) m.fs.MB.solid_inlet.flow_mass[0].fix(591.4) # kg/s # Particle porosity: # The porosity of the OC particle at the inlet is calculated from the # known bulk density of the fresh OC particle (3251.75 kg/m3), and the # skeletal density of the fresh OC particle (calculated from the known # composition of the fresh particle, and the skeletal density of its # components [see the solids property package]) m.fs.MB.solid_inlet.particle_porosity[0].fix(0.27) m.fs.MB.solid_inlet.temperature[0].fix(1183.15) # K m.fs.MB.solid_inlet.mass_frac_comp[0, "Fe2O3"].fix(0.45) m.fs.MB.solid_inlet.mass_frac_comp[0, "Fe3O4"].fix(1e-9) m.fs.MB.solid_inlet.mass_frac_comp[0, "Al2O3"].fix(0.55) # Initialize fuel reactor t_start = time.time() # Run start time # State arguments for initializing property state blocks # Gas phase temperature is initialized at solid # temperature because thermal mass of solid >> thermal mass of gas # Particularly useful for initialization if reaction takes place blk = m.fs.MB gas_phase_state_args = { 'flow_mol': blk.gas_inlet.flow_mol[0].value, 'temperature': blk.solid_inlet.temperature[0].value, 'pressure': blk.gas_inlet.pressure[0].value, 'mole_frac': { 'CH4': blk.gas_inlet.mole_frac_comp[0, 'CH4'].value, 'CO2': blk.gas_inlet.mole_frac_comp[0, 'CO2'].value, 'H2O': blk.gas_inlet.mole_frac_comp[0, 'H2O'].value}} solid_phase_state_args = { 'flow_mass': blk.solid_inlet.flow_mass[0].value, 'particle_porosity': blk.solid_inlet.particle_porosity[0].value, 'temperature': blk.solid_inlet.temperature[0].value, 'mass_frac': { 'Fe2O3': blk.solid_inlet.mass_frac_comp[0, 'Fe2O3'].value, 'Fe3O4': blk.solid_inlet.mass_frac_comp[0, 'Fe3O4'].value, 'Al2O3': blk.solid_inlet.mass_frac_comp[0, 'Al2O3'].value}} m.fs.MB.initialize(outlvl=idaeslog.INFO, gas_phase_state_args=gas_phase_state_args, solid_phase_state_args=solid_phase_state_args) t_initialize = time.time() # Initialization time # Create a solver solver = get_solver() solver.solve(m.fs.MB, tee=True) t_simulation = time.time() # Simulation time print("\n") print("----------------------------------------------------------") print('Total initialization time: ', value(t_initialize - t_start), " s") print("----------------------------------------------------------") print("\n") print("----------------------------------------------------------") print('Total simulation time: ', value(t_simulation - t_start), " s") print("----------------------------------------------------------") return m
def test_get_check_units_on_all_expressions(self): # this method is going to test all the expression types that should work # to be defensive, we will also test that we actually have the expected expression type # therefore, if the expression system changes and we get a different expression type, # we will know we need to change these tests uc = units kg = uc.kg m = uc.m model = ConcreteModel() model.x = Var() model.y = Var() model.z = Var() model.p = Param(initialize=42.0, mutable=True) # test equality self._get_check_units_ok(3.0 * kg == 1.0 * kg, uc, 'kg', expr.EqualityExpression) self._get_check_units_fail(3.0 * kg == 2.0 * m, uc, expr.EqualityExpression) # test inequality self._get_check_units_ok(3.0 * kg <= 1.0 * kg, uc, 'kg', expr.InequalityExpression) self._get_check_units_fail(3.0 * kg <= 2.0 * m, uc, expr.InequalityExpression) self._get_check_units_ok(3.0 * kg >= 1.0 * kg, uc, 'kg', expr.InequalityExpression) self._get_check_units_fail(3.0 * kg >= 2.0 * m, uc, expr.InequalityExpression) # test RangedExpression self._get_check_units_ok(inequality(3.0 * kg, 4.0 * kg, 5.0 * kg), uc, 'kg', expr.RangedExpression) self._get_check_units_fail(inequality(3.0 * m, 4.0 * kg, 5.0 * kg), uc, expr.RangedExpression) self._get_check_units_fail(inequality(3.0 * kg, 4.0 * m, 5.0 * kg), uc, expr.RangedExpression) self._get_check_units_fail(inequality(3.0 * kg, 4.0 * kg, 5.0 * m), uc, expr.RangedExpression) # test SumExpression, NPV_SumExpression self._get_check_units_ok( 3.0 * model.x * kg + 1.0 * model.y * kg + 3.65 * model.z * kg, uc, 'kg', expr.SumExpression) self._get_check_units_fail( 3.0 * model.x * kg + 1.0 * model.y * m + 3.65 * model.z * kg, uc, expr.SumExpression) self._get_check_units_ok(3.0 * kg + 1.0 * kg + 2.0 * kg, uc, 'kg', expr.NPV_SumExpression) self._get_check_units_fail(3.0 * kg + 1.0 * kg + 2.0 * m, uc, expr.NPV_SumExpression) # test ProductExpression, NPV_ProductExpression self._get_check_units_ok(model.x * kg * model.y * m, uc, 'kg * m', expr.ProductExpression) self._get_check_units_ok(3.0 * kg * 1.0 * m, uc, 'kg * m', expr.NPV_ProductExpression) self._get_check_units_ok(3.0 * kg * m, uc, 'kg * m', expr.NPV_ProductExpression) # I don't think that there are combinations that can "fail" for products # test MonomialTermExpression self._get_check_units_ok(model.x * kg, uc, 'kg', expr.MonomialTermExpression) # test ReciprocalExpression, NPV_ReciprocalExpression self._get_check_units_ok(1.0 / (model.x * kg), uc, '1 / kg', expr.ReciprocalExpression) self._get_check_units_ok(1.0 / kg, uc, '1 / kg', expr.NPV_ReciprocalExpression) # I don't think that there are combinations that can "fail" for products # test PowExpression, NPV_PowExpression # ToDo: fix the str representation to combine the powers or the expression system self._get_check_units_ok( (model.x * kg**2)**3, uc, 'kg ** 6', expr.PowExpression) # would want this to be kg**6 self._get_check_units_fail(kg**model.x, uc, expr.PowExpression, UnitsError) self._get_check_units_fail(model.x**kg, uc, expr.PowExpression, UnitsError) self._get_check_units_ok(kg**2, uc, 'kg ** 2', expr.NPV_PowExpression) self._get_check_units_fail(3.0**kg, uc, expr.NPV_PowExpression, UnitsError) # test NegationExpression, NPV_NegationExpression self._get_check_units_ok(-(kg * model.x * model.y), uc, 'kg', expr.NegationExpression) self._get_check_units_ok(-kg, uc, 'kg', expr.NPV_NegationExpression) # don't think there are combinations that fan "fail" for negation # test AbsExpression, NPV_AbsExpression self._get_check_units_ok(abs(kg * model.x), uc, 'kg', expr.AbsExpression) self._get_check_units_ok(abs(kg), uc, 'kg', expr.NPV_AbsExpression) # don't think there are combinations that fan "fail" for abs # test the different UnaryFunctionExpression / NPV_UnaryFunctionExpression types # log self._get_check_units_ok(log(3.0 * model.x), uc, None, expr.UnaryFunctionExpression) self._get_check_units_fail(log(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(log(3.0 * model.p), uc, None, expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(log(3.0 * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # log10 self._get_check_units_ok(log10(3.0 * model.x), uc, None, expr.UnaryFunctionExpression) self._get_check_units_fail(log10(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(log10(3.0 * model.p), uc, None, expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(log10(3.0 * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # sin self._get_check_units_ok(sin(3.0 * model.x * uc.radians), uc, None, expr.UnaryFunctionExpression) self._get_check_units_fail(sin(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_fail(sin(3.0 * kg * model.x * uc.kg), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(sin(3.0 * model.p * uc.radians), uc, None, expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(sin(3.0 * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # cos self._get_check_units_ok(cos(3.0 * model.x * uc.radians), uc, None, expr.UnaryFunctionExpression) self._get_check_units_fail(cos(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_fail(cos(3.0 * kg * model.x * uc.kg), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(cos(3.0 * model.p * uc.radians), uc, None, expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(cos(3.0 * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # tan self._get_check_units_ok(tan(3.0 * model.x * uc.radians), uc, None, expr.UnaryFunctionExpression) self._get_check_units_fail(tan(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_fail(tan(3.0 * kg * model.x * uc.kg), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(tan(3.0 * model.p * uc.radians), uc, None, expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(tan(3.0 * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # sin self._get_check_units_ok(sinh(3.0 * model.x * uc.radians), uc, None, expr.UnaryFunctionExpression) self._get_check_units_fail(sinh(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_fail(sinh(3.0 * kg * model.x * uc.kg), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(sinh(3.0 * model.p * uc.radians), uc, None, expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(sinh(3.0 * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # cos self._get_check_units_ok(cosh(3.0 * model.x * uc.radians), uc, None, expr.UnaryFunctionExpression) self._get_check_units_fail(cosh(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_fail(cosh(3.0 * kg * model.x * uc.kg), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(cosh(3.0 * model.p * uc.radians), uc, None, expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(cosh(3.0 * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # tan self._get_check_units_ok(tanh(3.0 * model.x * uc.radians), uc, None, expr.UnaryFunctionExpression) self._get_check_units_fail(tanh(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_fail(tanh(3.0 * kg * model.x * uc.kg), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(tanh(3.0 * model.p * uc.radians), uc, None, expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(tanh(3.0 * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # asin self._get_check_units_ok(asin(3.0 * model.x), uc, 'rad', expr.UnaryFunctionExpression) self._get_check_units_fail(asin(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(asin(3.0 * model.p), uc, 'rad', expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(asin(3.0 * model.p * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # acos self._get_check_units_ok(acos(3.0 * model.x), uc, 'rad', expr.UnaryFunctionExpression) self._get_check_units_fail(acos(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(acos(3.0 * model.p), uc, 'rad', expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(acos(3.0 * model.p * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # atan self._get_check_units_ok(atan(3.0 * model.x), uc, 'rad', expr.UnaryFunctionExpression) self._get_check_units_fail(atan(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(atan(3.0 * model.p), uc, 'rad', expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(atan(3.0 * model.p * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # exp self._get_check_units_ok(exp(3.0 * model.x), uc, None, expr.UnaryFunctionExpression) self._get_check_units_fail(exp(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(exp(3.0 * model.p), uc, None, expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(exp(3.0 * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # sqrt self._get_check_units_ok(sqrt(3.0 * model.x), uc, None, expr.UnaryFunctionExpression) self._get_check_units_ok(sqrt(3.0 * model.x * kg**2), uc, 'kg', expr.UnaryFunctionExpression) self._get_check_units_ok(sqrt(3.0 * model.x * kg), uc, 'kg ** 0.5', expr.UnaryFunctionExpression) self._get_check_units_ok(sqrt(3.0 * model.p), uc, None, expr.NPV_UnaryFunctionExpression) self._get_check_units_ok(sqrt(3.0 * model.p * kg**2), uc, 'kg', expr.NPV_UnaryFunctionExpression) self._get_check_units_ok(sqrt(3.0 * model.p * kg), uc, 'kg ** 0.5', expr.NPV_UnaryFunctionExpression) # asinh self._get_check_units_ok(asinh(3.0 * model.x), uc, 'rad', expr.UnaryFunctionExpression) self._get_check_units_fail(asinh(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(asinh(3.0 * model.p), uc, 'rad', expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(asinh(3.0 * model.p * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # acosh self._get_check_units_ok(acosh(3.0 * model.x), uc, 'rad', expr.UnaryFunctionExpression) self._get_check_units_fail(acosh(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(acosh(3.0 * model.p), uc, 'rad', expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(acosh(3.0 * model.p * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # atanh self._get_check_units_ok(atanh(3.0 * model.x), uc, 'rad', expr.UnaryFunctionExpression) self._get_check_units_fail(atanh(3.0 * kg * model.x), uc, expr.UnaryFunctionExpression, UnitsError) self._get_check_units_ok(atanh(3.0 * model.p), uc, 'rad', expr.NPV_UnaryFunctionExpression) self._get_check_units_fail(atanh(3.0 * model.p * kg), uc, expr.NPV_UnaryFunctionExpression, UnitsError) # ceil self._get_check_units_ok(ceil(kg * model.x), uc, 'kg', expr.UnaryFunctionExpression) self._get_check_units_ok(ceil(kg), uc, 'kg', expr.NPV_UnaryFunctionExpression) # don't think there are combinations that fan "fail" for ceil # floor self._get_check_units_ok(floor(kg * model.x), uc, 'kg', expr.UnaryFunctionExpression) self._get_check_units_ok(floor(kg), uc, 'kg', expr.NPV_UnaryFunctionExpression) # don't think there are combinations that fan "fail" for floor # test Expr_ifExpression # consistent if, consistent then/else self._get_check_units_ok( expr.Expr_if(IF=model.x * kg + kg >= 2.0 * kg, THEN=model.x * kg, ELSE=model.y * kg), uc, 'kg', expr.Expr_ifExpression) # unitless if, consistent then/else self._get_check_units_ok( expr.Expr_if(IF=model.x >= 2.0, THEN=model.x * kg, ELSE=model.y * kg), uc, 'kg', expr.Expr_ifExpression) # consistent if, unitless then/else self._get_check_units_ok( expr.Expr_if(IF=model.x * kg + kg >= 2.0 * kg, THEN=model.x, ELSE=model.x), uc, None, expr.Expr_ifExpression) # inconsistent then/else self._get_check_units_fail( expr.Expr_if(IF=model.x >= 2.0, THEN=model.x * m, ELSE=model.y * kg), uc, expr.Expr_ifExpression) # inconsistent then/else NPV self._get_check_units_fail( expr.Expr_if(IF=model.x >= 2.0, THEN=model.p * m, ELSE=model.p * kg), uc, expr.Expr_ifExpression) # inconsistent then/else NPV units only self._get_check_units_fail( expr.Expr_if(IF=model.x >= 2.0, THEN=m, ELSE=kg), uc, expr.Expr_ifExpression) # test IndexTemplate and GetItemExpression model.S = Set() i = IndexTemplate(model.S) j = IndexTemplate(model.S) self._get_check_units_ok(i, uc, None, IndexTemplate) model.mat = Var(model.S, model.S) self._get_check_units_ok(model.mat[i, j + 1], uc, None, expr.GetItemExpression) # test ExternalFunctionExpression, NPV_ExternalFunctionExpression model.ef = ExternalFunction(python_callback_function) self._get_check_units_ok(model.ef(model.x, model.y), uc, None, expr.ExternalFunctionExpression) self._get_check_units_ok(model.ef(1.0, 2.0), uc, None, expr.NPV_ExternalFunctionExpression) self._get_check_units_fail(model.ef(model.x * kg, model.y), uc, expr.ExternalFunctionExpression, UnitsError) self._get_check_units_fail(model.ef(2.0 * kg, 1.0), uc, expr.NPV_ExternalFunctionExpression, UnitsError)