def __init__(self, *args, **kwargs): """Create the problem.""" kwargs.setdefault('name', 'DuranEx1') super(SimpleMINLP, self).__init__(*args, **kwargs) m = self """Set declarations""" I = m.I = RangeSet(1, 2, doc="continuous variables") J = m.J = RangeSet(1, 1, doc="discrete variables") # initial point information for discrete variables initY = {1: 1} # initial point information for continuous variables initX = {1: 0, 2: 0} """Variable declarations""" # DISCRETE VARIABLES Y = m.Y = Var(J, domain=Binary, initialize=initY) # CONTINUOUS VARIABLES X = m.X = Var(I, domain=Reals, initialize=initX) """Constraint definitions""" # CONSTRAINTS m.const1 = Constraint(expr=-X[2] + 5*log(X[1] + 1) + 3*Y[1] >= 0) m.const2 = Constraint(expr=-X[2] + X[1]**2 - Y[1] <= 1) m.const3 = Constraint(expr=X[1] + X[2] +20*Y[1] <= 24) m.const4 = Constraint(expr=2*X[2] + 3*X[1] <= 10) """Cost (objective) function definition""" m.cost = Objective(expr=10*X[1]**2 - X[2] + 5*(Y[1] - 1), sense=minimize)
def test_log(self): m = pe.ConcreteModel() m.x = pe.Var(initialize=2.0) e = pe.log(m.x) derivs = reverse_ad(e) symbolic = reverse_sd(e) self.assertAlmostEqual(derivs[m.x], pe.value(symbolic[m.x]), tol+3) self.assertAlmostEqual(derivs[m.x], approx_deriv(e, m.x), tol)
def test_expr_xfrm(self): from pyomo.repn.plugins.gams_writer import ( expression_to_string, StorageTreeChecker) from pyomo.core.expr.symbol_map import SymbolMap M = ConcreteModel() M.abc = Var() smap = SymbolMap() tc = StorageTreeChecker(M) expr = M.abc**2.0 self.assertEqual(str(expr), "abc**2.0") self.assertEqual(expression_to_string( expr, tc, smap=smap), "power(abc, 2.0)") expr = log(M.abc**2.0) self.assertEqual(str(expr), "log(abc**2.0)") self.assertEqual(expression_to_string( expr, tc, smap=smap), "log(power(abc, 2.0))") expr = log(M.abc**2.0) + 5 self.assertEqual(str(expr), "log(abc**2.0) + 5") self.assertEqual(expression_to_string( expr, tc, smap=smap), "log(power(abc, 2.0)) + 5") expr = exp(M.abc**2.0) + 5 self.assertEqual(str(expr), "exp(abc**2.0) + 5") self.assertEqual(expression_to_string( expr, tc, smap=smap), "exp(power(abc, 2.0)) + 5") expr = log(M.abc**2.0)**4 self.assertEqual(str(expr), "log(abc**2.0)**4") self.assertEqual(expression_to_string( expr, tc, smap=smap), "power(log(power(abc, 2.0)), 4)") expr = log(M.abc**2.0)**4.5 self.assertEqual(str(expr), "log(abc**2.0)**4.5") self.assertEqual(expression_to_string( expr, tc, smap=smap), "log(power(abc, 2.0)) ** 4.5")
def test_substitute_casadi_intrinsic3(self): m = self.m m.y = Var() t = IndexTemplate(m.t) e = sin(m.dv[t] + m.v[t]) + log(m.v[t] * m.y + m.dv[t]**2) templatemap = {} e3 = substitute_pyomo2casadi(e, templatemap) self.assertIs(e3.arg(0)._fcn, casadi.sin) self.assertIs(e3.arg(1)._fcn, casadi.log) m.del_component('y')
def test_log(self): c_bounds = [(-2.5, 2.8), (-2.5, -0.5), (0.5, 2.8), (-2.5, 0), (0, 2.8), (-2.5, -1), (1, 2.8), (-1, -0.5), (0.5, 1)] for cl, cu in c_bounds: m = pe.Block(concrete=True) m.x = pe.Var() m.c = pe.Constraint(expr=pe.inequality(body=pe.log(m.x), lower=cl, upper=cu)) fbbt(m) z = np.linspace(pe.value(m.c.lower), pe.value(m.c.upper), 100) if m.x.lb is None: xl = -np.inf else: xl = pe.value(m.x.lb) if m.x.ub is None: xu = np.inf else: xu = pe.value(m.x.ub) x = np.exp(z) self.assertTrue(np.all(xl <= x)) self.assertTrue(np.all(xu >= x))
def __init__(self, *args, **kwargs): """Create the problem.""" kwargs.setdefault('name', 'DuranEx1') super(SimpleMINLP, self).__init__(*args, **kwargs) m = self """Set declarations""" I = m.I = RangeSet(1, 4, doc="continuous variables") J = m.J = RangeSet(1, 3, doc="discrete variables") # initial point information for discrete variables initY = {1: 1, 2: 0, 3: 1} # initial point information for continuous variables initX = {1: 0, 2: 0, 3: 0, 4: 0} """Variable declarations""" # DISCRETE VARIABLES Y = m.Y = Var(J, domain=Binary, initialize=initY) # CONTINUOUS VARIABLES X = m.X = Var(I, domain=NonNegativeReals, initialize=initX) """Constraint definitions""" # CONSTRAINTS m.const1 = Constraint(expr=0.8*log(X[2] + 1) + 0.96*log(X[1] - X[2] + 1) - 0.8*X[3] >= 0) m.const2 = Constraint(expr=log(X[2] + 1) + 1.2*log(X[1] - X[2] + 1) - X[3] - 2*Y[3] >= -2) m.const3 = Constraint(expr=10*X[1] - 7*X[3] - 18*log(X[2] + 1) - 19.2*log(X[1] - X[2] + 1) + 10 - X[4] <= 0) m.const4 = Constraint(expr=X[2] - X[1] <= 0) m.const5 = Constraint(expr=X[2] - 2*Y[1] <= 0) m.const6 = Constraint(expr=X[1] - X[2] - 2*Y[2] <= 0) m.const7 = Constraint(expr=Y[1] + Y[2] <= 1) """Cost (objective) function definition""" m.cost = Objective(expr=-5*Y[1] - 6*Y[2] - 8*Y[3] - X[4], sense=maximize) """Bound definitions""" # x (continuous) upper bounds x_ubs = {1: 2, 2: 2, 3: 1, 4: 100} for i, x_ub in iteritems(x_ubs): X[i].setub(x_ub)
def P_sat_dY_inf_rule(block): return e.nonhenry.dY_inf.A + e.nonhenry.dY_inf.B/block.parent_block().T + e.nonhenry.dY_inf.C*pe.log(block.parent_block().T) + \ e.nonhenry.dY_inf.D*(block.parent_block().T)**2 + e.nonhenry.dY_inf.E/(block.parent_block().T)**2 == block.P_sat_dY_inf
def Hen0_ref_rule(block): return block.Hen0_ref == e.henry.A['C6H14'] + e.henry.B['C6H14']/block.parent_block().T + e.henry.C['C6H14']*pe.log(block.parent_block().T) + \ e.henry.D['C6H14']*(block.parent_block().T**2) + e.henry.E['C6H14']/(block.parent_block().T**2)
def delta_temperature(b, t): return (dT1[t] - dT2[t])/log(dT1[t]/dT2[t])
import pyomo.environ as pyo model = pyo.ConcreteModel() model.x = pyo.Var(bounds=(1.0, 10.0), initialize=5.0) model.y = pyo.Var(within=pyo.Binary) model.c1 = pyo.Constraint(expr=(model.x - 4.0)**2 - model.x <= 50.0 * (1 - model.y)) model.c2 = pyo.Constraint(expr=model.x * pyo.log(model.x) + 5.0 <= 50.0 * (model.y)) model.objective = pyo.Objective(expr=model.x, sense=pyo.minimize) pyo.SolverFactory('mindtpy').solve(model, mip_solver='glpk', nlp_solver='ipopt') model.objective.display() model.display() model.pprint()
def rule_omega(b, c): return (1.5794145 + 0.00635771 * b.theta[c] - 0.7314 * log(b.theta[c]) + 0.2417357 * log(b.theta[c])**2 - 0.0347045 * log(b.theta[c])**3)
def avrami5(*data): pd = data[0] return 5.0 * (1.0 - pd) * (-1 * pyo.log(1 - pd))**(5.0 - (1.0 / 5.0))
def avrami3(*data): pd = data[0] return 3.0 * (1.0 - pd) * (-1 * pyo.log(1 - pd))**(3.0 - (1.0 / 3.0))
def _bubble_dew_log_fug_coeff_method(blk, p, j, pp, pt_var): pobj = blk.params.get_phase(p) ctype = pobj._cubic_type cname = pobj.config.equation_of_state_options["type"].name # Ditch the m.fs.unit.control_volume... short_name = pt_var.name.split(".")[-1] #import pdb; pdb.set_trace() if short_name.startswith("temperature"): abbrv = "t" T = pt_var[pp] P = blk.pressure elif short_name.startswith("pressure"): abbrv = "p" P = pt_var[pp] T = blk.temperature else: raise BurntToast("Users shouldn't be calling this function. " "If you're a dev, you know what you did.") if short_name.endswith("bubble"): abbrv += "bub" if pobj.is_liquid_phase(): x = blk.mole_frac_comp log_mole_frac = blk.log_mole_frac_comp xidx = () elif pobj.is_vapor_phase(): x = getattr(blk, "_mole_frac_" + abbrv) log_mole_frac = getattr(blk, "log_mole_frac_" + abbrv) xidx = pp else: raise BurntToast("Users shouldn't be calling this function. " "If you're a dev, you know what you did.") elif short_name.endswith("dew"): abbrv += "dew" if pobj.is_vapor_phase(): x = blk.mole_frac_comp log_mole_frac = blk.log_mole_frac_comp xidx = () elif pobj.is_liquid_phase(): x = getattr(blk, "_mole_frac_" + abbrv) log_mole_frac = getattr(blk, "log_mole_frac_" + abbrv) xidx = pp else: raise BurntToast("Users shouldn't be calling this function. " "If you're a dev, you know what you did.") else: raise BurntToast("Users shouldn't be calling this function. " "If you're a dev, you know what you did.") def a(k): cobj = blk.params.get_component(k) fw = getattr(blk, cname + "_fw")[k] ac = getattr(blk, cname + '_a_crit')[k] func_alpha = getattr(blk.params, cname + "_func_alpha") return ac * func_alpha(T, fw, cobj) kappa = getattr(blk.params, cname + "_kappa") am = sum( sum(x[xidx, i] * x[xidx, j] * sqrt(a(i) * a(j)) * (1 - kappa[i, j]) for j in blk.component_list) for i in blk.component_list) b = getattr(blk, cname + "_b") bm = sum(x[xidx, i] * b[i] for i in blk.component_list) R = Cubic.gas_constant(blk) A = am * P / (R * T)**2 B = bm * P / (R * T) delta = (2 * sqrt(a(j)) / am * sum(x[xidx, i] * sqrt(a(i)) * (1 - kappa[j, i]) for i in blk.component_list)) expr_write = CubicThermoExpressions(blk) if pobj.is_vapor_phase(): Z = expr_write.z_vap(eos=pobj._cubic_type, A=A, B=B) elif pobj.is_liquid_phase(): Z = expr_write.z_liq(eos=pobj._cubic_type, A=A, B=B) return (_log_fug_coeff_method(A, b[j], bm, B, delta, Z, ctype) + log_mole_frac[xidx, j] + log(P / blk.params.pressure_ref))
def log_fug_phase_comp_eq(b, p, j, pp): return (b.log_mole_frac_phase_comp[p, j] + log(b.pressure / b.params.pressure_ref) + _log_fug_coeff_phase_comp_eq(b, p, j, pp))
def delta_enth_polytropic_con(b, t): Tout = properties_out[t].temperature Tin = properties_in[t].temperature return b.delta_enth_polytropic[t] == b.delta_enth_actual[t] \ - b.deltaS[t] * (Tout - Tin)/log(Tout / Tin)
def ObjectiveLog(model): ro = 0.1 return 0\ -model.FlowStrainWeight*sum(pyo.log(ro + model.FlowStrain[flow]) for flow in model.Flows ) \ + model.FlowRouteWeight*sum(model.FlowRoute[flow, arc] for flow in model.Flows for arc in model.Arcs)
def simplify_user_constraint(df, time_step_weights): """ Simplify a user-defined constraint in multiple iterations until the provided DataFrame holds only 3 columns (left hand side, le/eq/ge, right hand side). ==> The data from the simplified DataFrame is returned as python dicts for "lhs" and "rhs" and a string for the operation sign ('==', '>=', '<='). Exemplary string representation of the original user_expression: '-Q == (1 + F * 0.8) ** 3' Stepwise simplification process of the original DataFrame: 0 1 2 3 4 5 6 7 8 9 10 11 0 0 - comp.Q[0,0] == ( 1.0 + comp.F[0,0] * 0.8 ) ** 3.0 1 - comp.Q[0,1] == ( 1.0 + comp.F[0,1] * 0.8 ) ** 3.0 2 - comp.Q[0,2] == ( 1.0 + comp.F[0,2] * 0.8 ) ** 3.0 [...] 0 1 2 3 4 5 6 7 8 9 0 0 - comp.Q[0,0] == ( 1.0 + 0.8*comp.F[0,0] ) ** 3.0 1 - comp.Q[0,1] == ( 1.0 + 0.8*comp.F[0,1] ) ** 3.0 2 - comp.Q[0,2] == ( 1.0 + 0.8*comp.F[0,2] ) ** 3.0 [...] 0 1 2 3 4 5 6 7 0 0 - comp.Q[0,0] == ( 1.0 + 0.8*comp.F[0,0] ) ** 3.0 1 - comp.Q[0,1] == ( 1.0 + 0.8*comp.F[0,1] ) ** 3.0 2 - comp.Q[0,2] == ( 1.0 + 0.8*comp.F[0,2] ) ** 3.0 [...] 0 1 2 3 4 5 0 0 - comp.Q[0,0] == 1.0 + 0.8*comp.F[0,0] ** 3.0 1 - comp.Q[0,1] == 1.0 + 0.8*comp.F[0,1] ** 3.0 2 - comp.Q[0,2] == 1.0 + 0.8*comp.F[0,2] ** 3.0 [...] 0 1 2 3 0 0 - comp.Q[0,0] == (1.0 + 0.8*comp.F[0,0])**3.0 1 - comp.Q[0,1] == (1.0 + 0.8*comp.F[0,1])**3.0 2 - comp.Q[0,2] == (1.0 + 0.8*comp.F[0,2])**3.0 [...] 0 1 2 0 0 - comp.Q[0,0] == (1.0 + 0.8*comp.F[0,0])**3.0 1 - comp.Q[0,1] == (1.0 + 0.8*comp.F[0,1])**3.0 2 - comp.Q[0,2] == (1.0 + 0.8*comp.F[0,2])**3.0 [...] """ debug = False # prints simplification progress on the console if True # Simplify the DataFrame until it has only 3 columns (LHS <==> RHS) while_iter_count = 0 # init counter found_sum_operator = False # init dropped_index = False # init while len(df.columns) > 3 and while_iter_count < 100: # Increase counter by 1 for each iteration in the while-loop while_iter_count += 1 # Flag to check if mathematical operation has been performed # -> if True, jump to beginning of the while-loop (continue) operation_done = False # init found_minus_sign = False # init df.columns = range(len(df.columns)) # rename the columns first_row = df.iloc[0] # list of first row entries if debug: print(df.head(3).to_string()) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 1. Look for a part of the expression in brackets # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Loop first_row from left, look for first ')' and remember last '(' last_opening_idx = 0 # init first_closing_idx = len(first_row) # init for idx, obj in first_row.items(): if isinstance(obj, str) and obj == '(': last_opening_idx = idx if isinstance(obj, str) and obj == ')': first_closing_idx = idx break # Get slice of 'first_row' (in brackets) or whole row if no brackets first_row_slice = first_row[last_opening_idx:first_closing_idx + 1] # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 2. Look for exponents in the slice # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Look for power symbol ('**') in expression part for idx, obj in first_row_slice.items(): if isinstance(obj, str) and obj == '**': # Find names of surrounding elements of '**' operator lhs_idx = idx - 1 rhs_idx = idx + 1 rhs_obj = first_row_slice[rhs_idx] # If rhs is a minus sign, next element is considered if isinstance(rhs_obj, str) and rhs_obj == '-': rhs_idx = idx + 2 found_minus_sign = True # Do the power operation, depending on the flag # 'found_minus_sign' and delete surrounding columns if found_minus_sign: df[idx] = df[lhs_idx]**(-1 * df[rhs_idx]) df.drop([idx + 2, idx + 1, idx - 1], axis=1, inplace=True) else: df[idx] = df[lhs_idx]**df[rhs_idx] df.drop([idx + 1, idx - 1], axis=1, inplace=True) # Set flag 'operation_done' to True to continue while operation_done = True break # the for-loop # Jump to the beginning of while-loop if flag is True if operation_done: continue # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 3. Look for division and multiplication # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Look for division or multiplication symbols in expression part for idx, obj in first_row_slice.items(): if isinstance(obj, str) and (obj == '/' or obj == '*'): # Find names of surrounding elements of '/' or '*' operator lhs_idx = idx - 1 rhs_idx = idx + 1 rhs_obj = first_row_slice[rhs_idx] # If rhs is a minus sign, next element is considered if isinstance(rhs_obj, str) and rhs_obj == '-': rhs_idx = idx + 2 found_minus_sign = True # Do the operation, depending on the flag 'found_minus_sign' # and the found operator and delete surrounding columns if found_minus_sign: if obj == '/': df[idx] = df[lhs_idx] / (-1 * df[rhs_idx]) else: # obj == '*' df[idx] = df[lhs_idx] * (-1 * df[rhs_idx]) df.drop([idx + 2, idx + 1, idx - 1], axis=1, inplace=True) else: if obj == '/': df[idx] = df[lhs_idx] / df[rhs_idx] else: # obj == '*' df[idx] = df[lhs_idx] * df[rhs_idx] df.drop([idx + 1, idx - 1], axis=1, inplace=True) # Set flag 'operation_done' to True to continue while operation_done = True break # the for-loop # Jump to the beginning of while-loop if flag is True if operation_done: continue # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 4. Look for summation and subtraction # (--> Combinations: -+ or ++ are not allowed!) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Look for summation and subtraction symbols in expression part for idx, obj in first_row_slice.items(): if isinstance(obj, str) and (obj == '+' or obj == '-'): # ------------------------------------------------------ # Special case I: Plus or minus operator in first position if idx == 0: if obj == '-': df[1] = -1 * df[1] # else --> obj == '+' --> pass df.drop([0], axis=1, inplace=True) # delete first col operation_done = True break # the for-loop # ------------------------------------------------------ # Find names of surrounding elements of '+' or '-' operator lhs_idx = idx - 1 lhs_obj = first_row_slice[lhs_idx] rhs_idx = idx + 1 rhs_obj = first_row_slice[rhs_idx] # ------------------------------------------------------ # Special case II: Plus or minus operator is right beside an # opening bracket or an (non)-equality sign. if isinstance(lhs_obj, str) and (lhs_obj == '(' or lhs_obj == '==' or lhs_obj == '>=' or lhs_obj == '<='): if obj == '-': df[rhs_idx] = -1 * df[rhs_idx] # else --> obj == '+' --> pass df.drop([idx], axis=1, inplace=True) operation_done = True break # the for-loop # ------------------------------------------------------ # If rhs is a minus sign, next element is considered if isinstance(rhs_obj, str) and rhs_obj == '-': rhs_idx = idx + 2 found_minus_sign = True # Do the operation, depending on the flag 'found_minus_sign' # and the found operator and delete surrounding columns if found_minus_sign: if obj == '+': df[idx] = df[lhs_idx] + (-1 * df[rhs_idx]) else: # obj == '-' df[idx] = df[lhs_idx] - (-1 * df[rhs_idx]) df.drop([idx + 2, idx + 1, idx - 1], axis=1, inplace=True) else: if obj == '+': df[idx] = df[lhs_idx] + df[rhs_idx] else: # obj == '-' df[idx] = df[lhs_idx] - df[rhs_idx] df.drop([idx + 1, idx - 1], axis=1, inplace=True) # Set flag 'operation_done' to True to continue while operation_done = True break # the for-loop # Jump to the beginning of while-loop if flag is True if operation_done: continue # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # 5. Delete enclosing brackets # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # This point it reached, if an expression slice does not contain # any more possibilities to perform the mathematical operations # 'pow', 'div', 'mul', 'add', 'sub'. Check if the term is still # enclosed by brackets --> remove them. idx = first_row_slice.keys() if first_row[idx[0]] == '(' and first_row[idx[-1]] == ')': # Special case for operators: SUM, SIN, COS, EXP, LOG. # These operators are always on the left side of an opening bracket. # Check if there is one of these operators in front of the brackets: if idx[0] != 0 and isinstance(first_row[idx[0]-1], str) and \ first_row[idx[0]-1] in ['sum', 'sin', 'cos', 'exp', 'log']: # Get the name of the operator operator_left_of_bracket = first_row[idx[0] - 1] # Use simple python sum function if operator is 'sum': if operator_left_of_bracket == 'sum': # Only do 'sum' if it is not a scalar value (all the same). # Compare the expression string representations of the first # two expression rows (after some string modifications). exception = 'The data in the brackets of "sum"-operator ' \ 'is scalar (constant or not time-dependent). ' \ '"sum"-operator is useless in this case. ' \ 'Consider rewriting the user_expression.' all_rows = df[idx[1]].to_list() if len(all_rows) >= 2: row_0 = _expr_string_adjustment(all_rows[0].__str__()) row_1 = _expr_string_adjustment(all_rows[1].__str__()) if row_0 == row_1: raise ValueError(exception) # Don't allow sum for time-independent constraints. Actually # it would work, but it doesn't make sense [CAP == sum(42)]. elif len(all_rows) == 1: raise ValueError(exception) # Do sum operation if exception is not raised: # Also consider the weight of each time-step (only important # if the data is clustered). df[idx[1]] = sum(weight * row_data for weight, row_data in zip( time_step_weights, all_rows)) found_sum_operator = True # set flag for post-processing # Do the math with Pyomo's intrinsic functions for sin, log, ... elif operator_left_of_bracket == 'sin': df[idx[1]] = [pyo.sin(k) for k in df[idx[1]].to_list()] elif operator_left_of_bracket == 'cos': df[idx[1]] = [pyo.cos(k) for k in df[idx[1]].to_list()] elif operator_left_of_bracket == 'exp': df[idx[1]] = [pyo.exp(k) for k in df[idx[1]].to_list()] elif operator_left_of_bracket == 'log': df[idx[1]] = [pyo.log(k) for k in df[idx[1]].to_list()] # If there was an operator in front of the brackets --> drop it df.drop([idx[0] - 1], axis=1, inplace=True) # Now drop the surrounding brackets df.drop([idx[0], idx[-1]], axis=1, inplace=True) # Set flag 'operation_done' to True to continue while operation_done = True # Jump to the beginning of while-loop if flag is True if operation_done: continue # Outside of while-loop: # ~~~~~~~~~~~~~~~~~~~~~~ # Raise an error if too many iterations are performed on one constraint! if while_iter_count >= 100: raise ValueError( 'The function "simplify_user_constraint" needed too ' 'many iterations. The simplification process stopped ' 'before the constraint could be simplified to the ' 'desired form "LHS <==> RHS". Check your constraints!') # Final renaming of last three columns to [0, 1, 2] df.columns = range(len(df.columns)) if debug: print(df.head(3).to_string()) if debug: print('Number of while-loops:', str(while_iter_count)) # Special case: If there was at least one 'sum' operation, it is possible # that the constraint is not time-dependent anymore. Assume 'Q' is an time- # dependent variable. We will loose time-dependency in case A and not in # case B: A) 'CAP == sum(Q)'; B) 'CAP == Q + sum(Q)'. # Expression string representations are compared to check if the expressions # are the same (first two rows are enough). Note: The strings can have the # same content but different order and additional brackets sometimes # => adjust expression string representation to enable comparison. if found_sum_operator and len(df[0]) >= 2: lhs_row_0 = _expr_string_adjustment(df[0].iloc[0].__str__()) lhs_row_1 = _expr_string_adjustment(df[0].iloc[1].__str__()) rhs_row_0 = _expr_string_adjustment(df[2].iloc[0].__str__()) rhs_row_1 = _expr_string_adjustment(df[2].iloc[1].__str__()) if lhs_row_0 == lhs_row_1 and rhs_row_0 == rhs_row_1: df.drop(df.index[1:], axis=0, inplace=True) dropped_index = True if debug: print(df.head(3).to_string()) # Convert the first and the third column to python dictionaries and get the # global operation sign from the first row of the middle column. lhs = df[0].to_dict() op = df[1].iloc[0] # done only once --> it's the same operator in all rows rhs = df[2].to_dict() # Return the left and right hand side dicts and the operator sign return lhs, op, rhs, dropped_index
# ___________________________________________________________________________ # # Pyomo: Python Optimization Modeling Objects # Copyright (c) 2008-2022 # National Technology and Engineering Solutions of Sandia, LLC # Under the terms of Contract DE-NA0003525 with National Technology and # Engineering Solutions of Sandia, LLC, the U.S. Government retains certain # rights in this software. # This software is distributed under the 3-clause BSD License. # ___________________________________________________________________________ from pyomo.environ import ConcreteModel, Var, Objective, Constraint, log, log10, exp, sqrt model = ConcreteModel() # pick a value in the domain of all of these functions model.ONE = Var(initialize=1) model.ZERO = Var(initialize=0) model.obj = Objective(expr=model.ONE + model.ZERO) model.c_log = Constraint(expr=log(model.ONE) == 0) model.c_log10 = Constraint(expr=log10(model.ONE) == 0) model.c_exp = Constraint(expr=exp(model.ZERO) == 1) model.c_sqrt = Constraint(expr=sqrt(model.ONE) == 1) model.c_abs = Constraint(expr=abs(model.ONE) == 1)
def head_isen_eqn(b, t): f = pyo.log(fscale * b.parent_block().control_volume.properties_in[t].flow_vol) return b.head_isentropic[t] == -(-1373.6 * f**3 + 31759 * f**2 - 188528 * f + 500520)
def head_isen_eqn(b, t): f = pyo.log(fscale * b.parent_block().control_volume.properties_in[t].flow_vol) return b.head_isentropic[t] == -(-1676.3 * f**3 + 34916 * f**2 - 173801 * f + 456957)
def avrami2(*data): pd = data[0] return 2.0 * (1.0 - pd) * (-1 * pyo.log(1 - pd))**(2.0 - (1.0 / 2.0))
def regression_rule(model, i): return log(self.y[i]) == log(model.frontier[i] + 1) \ + sum(model.lamda[k] * self.z[i][k] for k in model.K) + model.epsilon[i]
def avrami4(*data): pd = data[0] return 4.0 * (1.0 - pd) * (-1 * pyo.log(1 - pd))**(4.0 - (1.0 / 4.0))
def rcond_wall_eqn(b): return b.rcond_wall * b.therm_cond_wall == 0.5 * b.do_tube * log(b.do_tube / b.di_tube)
def test_unhandled_expressions(self): m = ConcreteModel() m.x = Var() m.c1 = Constraint(expr=0 <= log(m.x)) self.assertTrue(satisfiable(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) model.xkg = Var(units=kg) model.ym = Var(units=m) # 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 DivisionExpression, NPV_DivisionExpression self._get_check_units_ok(1.0 / (model.x * kg), uc, '1/kg', EXPR.DivisionExpression) self._get_check_units_ok(2.0 / kg, uc, '1/kg', EXPR.NPV_DivisionExpression) self._get_check_units_ok((model.x * kg) / 1.0, uc, 'kg', EXPR.MonomialTermExpression) self._get_check_units_ok(kg / 2.0, uc, 'kg', EXPR.NPV_DivisionExpression) self._get_check_units_ok(model.y * m / (model.x * kg), uc, 'm/kg', EXPR.DivisionExpression) self._get_check_units_ok(m / kg, uc, 'm/kg', EXPR.NPV_DivisionExpression) # 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 EXPR.IndexTemplate and GetItemExpression model.S = Set() i = EXPR.IndexTemplate(model.S) j = EXPR.IndexTemplate(model.S) self._get_check_units_ok(i, uc, None, EXPR.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) # test ExternalFunctionExpression, NPV_ExternalFunctionExpression model.ef2 = ExternalFunction(python_callback_function, units=uc.kg) self._get_check_units_ok(model.ef2(model.x, model.y), uc, 'kg', EXPR.ExternalFunctionExpression) self._get_check_units_ok(model.ef2(1.0, 2.0), uc, 'kg', EXPR.NPV_ExternalFunctionExpression) self._get_check_units_fail(model.ef2(model.x * kg, model.y), uc, EXPR.ExternalFunctionExpression, UnitsError) self._get_check_units_fail(model.ef2(2.0 * kg, 1.0), uc, EXPR.NPV_ExternalFunctionExpression, UnitsError) # test ExternalFunctionExpression, NPV_ExternalFunctionExpression model.ef3 = ExternalFunction(python_callback_function, units=uc.kg, arg_units=[uc.kg, uc.m]) self._get_check_units_fail(model.ef3(model.x, model.y), uc, EXPR.ExternalFunctionExpression) self._get_check_units_fail(model.ef3(1.0, 2.0), uc, EXPR.NPV_ExternalFunctionExpression) self._get_check_units_fail(model.ef3(model.x * kg, model.y), uc, EXPR.ExternalFunctionExpression, UnitsError) self._get_check_units_fail(model.ef3(2.0 * kg, 1.0), uc, EXPR.NPV_ExternalFunctionExpression, UnitsError) self._get_check_units_ok(model.ef3(2.0 * kg, 1.0 * uc.m), uc, 'kg', EXPR.NPV_ExternalFunctionExpression) self._get_check_units_ok(model.ef3(model.x * kg, model.y * m), uc, 'kg', EXPR.ExternalFunctionExpression) self._get_check_units_ok(model.ef3(model.xkg, model.ym), uc, 'kg', EXPR.ExternalFunctionExpression) self._get_check_units_fail(model.ef3(model.ym, model.xkg), uc, EXPR.ExternalFunctionExpression, InconsistentUnitsError)
def calculate_scaling_factors(self): super().calculate_scaling_factors() # Get some scale factors that are frequently used to calculate others sf_flow = iscale.get_scaling_factor(self.flow_mol) sf_mol_fraction = {} comps = self.params.component_list for i in comps: sf_mol_fraction[i] = iscale.get_scaling_factor( self.mole_frac_comp[i]) # calculate flow_mol_comp scale factors for i, c in self.flow_mol_comp.items(): iscale.set_scaling_factor(c, sf_flow * sf_mol_fraction[i]) if self.is_property_constructed("energy_density_terms"): for i, c in self.energy_density_terms.items(): sf1 = iscale.get_scaling_factor(self.enth_mol_phase[i]) sf2 = iscale.get_scaling_factor(self.dens_mol_phase[i]) iscale.set_scaling_factor(c, sf1 * sf2) if self.is_property_constructed("enthalpy_flow_terms"): for i, c in self.enthalpy_flow_terms.items(): sf1 = iscale.get_scaling_factor(self.enth_mol_phase[i]) sf2 = iscale.get_scaling_factor(self.flow_mol) iscale.set_scaling_factor(c, sf1 * sf2) if self.is_property_constructed("heat_cap_correlation"): iscale.constraint_scaling_transform( self.heat_cap_correlation, iscale.get_scaling_factor(self.cp_mol) * iscale.get_scaling_factor(self.flow_mol), overwrite=False) if self.is_property_constructed("enthalpy_correlation"): for p, c in self.enthalpy_correlation.items(): iscale.constraint_scaling_transform( c, iscale.get_scaling_factor(self.enth_mol) * iscale.get_scaling_factor(self.flow_mol), overwrite=False) if self.is_property_constructed("entropy_correlation"): iscale.constraint_scaling_transform( self.entropy_correlation, iscale.get_scaling_factor(self.entr_mol) * iscale.get_scaling_factor(self.flow_mol), overwrite=False) if self.is_property_constructed("vapor_pressure_correlation"): iscale.constraint_scaling_transform( self.vapor_pressure_correlation, log(iscale.get_scaling_factor(self.pressure_sat)) * iscale.get_scaling_factor(self.flow_mol), overwrite=False) if self.is_property_constructed("therm_cond_con"): for i, c in self.therm_cond_con.items(): iscale.constraint_scaling_transform( c, iscale.get_scaling_factor(self.therm_cond_comp[i]), overwrite=False) if self.is_property_constructed("therm_mix_con"): iscale.constraint_scaling_transform(self.therm_mix_con, iscale.get_scaling_factor( self.therm_cond), overwrite=False) if self.is_property_constructed("visc_d_con"): for i, c in self.visc_d_con.items(): iscale.constraint_scaling_transform(c, iscale.get_scaling_factor( self.visc_d_comp[i]), overwrite=False) if self.is_property_constructed("visc_d_mix_con"): iscale.constraint_scaling_transform(self.visc_d_mix_con, iscale.get_scaling_factor( self.visc_d), overwrite=False)
def regression_rule(model, i): return log( self.y[i]) == log(model.frontier[i] + 1) + model.epsilon[i]
def test_common(self, model): # Reference state composition assert isinstance(model.state[1].Liq_x_ref, Expression) assert len(model.state[1].Liq_x_ref) == 6 for k in model.state[1].Liq_x_ref: assert k in ["H2O", "C6H12", "Na+", "H+", "Cl-", "OH-"] if k in ["H2O", "C6H12"]: assert str(model.state[1].Liq_x_ref[k].expr) == str(0.0) else: assert str(model.state[1].Liq_x_ref[k].expr) == str( model.state[1].mole_frac_phase_comp_true["Liq", k] / (model.state[1].mole_frac_phase_comp_true["Liq", "Cl-"] + model.state[1].mole_frac_phase_comp_true["Liq", "OH-"] + model.state[1].mole_frac_phase_comp_true["Liq", "Na+"] + model.state[1].mole_frac_phase_comp_true["Liq", "H+"])) assert isinstance(model.state[1].Liq_X, Expression) assert len(model.state[1].Liq_X) == 6 for j in model.state[1].Liq_X: if j in ["H2O", "C6H12"]: # _X should be mole_frac_phase_comp_true assert (str(model.state[1].Liq_X[j]._expr) == str( model.state[1].mole_frac_phase_comp_true["Liq", j])) else: # _X should be mutiplied by |charge| assert (str(model.state[1].Liq_X[j]._expr) == str( model.state[1].mole_frac_phase_comp_true["Liq", j] * abs(model.params.get_component(j).config.charge))) assert isinstance(model.state[1].Liq_X_ref, Expression) assert len(model.state[1].Liq_X_ref) == 6 for j in model.state[1].Liq_X_ref: if j in ["H2O", "C6H12"]: # _X should be mole_frac_phase_comp_true assert str(model.state[1].Liq_X_ref[j].expr) == str( model.state[1].Liq_x_ref[j]) else: # _X should be mutiplied by |charge| assert (str(model.state[1].Liq_X_ref[j]._expr) == str( model.state[1].Liq_x_ref[j] * abs(model.params.get_component(j).config.charge))) assert isinstance(model.state[1].Liq_Y, Expression) assert len(model.state[1].Liq_Y) == 4 for j in model.state[1].Liq_Y: if j in ["H+", "Na+"]: assert (str(model.state[1].Liq_Y[j]._expr) == str( model.state[1].Liq_X[j] / (model.state[1].Liq_X["Na+"] + model.state[1].Liq_X["H+"]))) else: assert (str(model.state[1].Liq_Y[j]._expr) == str( model.state[1].Liq_X[j] / (model.state[1].Liq_X["Cl-"] + model.state[1].Liq_X["OH-"]))) assert isinstance(model.state[1].Liq_ionic_strength, Expression) assert len(model.state[1].Liq_ionic_strength) == 1 assert str(model.state[1].Liq_ionic_strength.expr) == str( 0.5 * (model.params.get_component("Cl-").config.charge**2 * model.state[1].mole_frac_phase_comp_true["Liq", "Cl-"] + model.params.get_component("OH-").config.charge**2 * model.state[1].mole_frac_phase_comp_true["Liq", "OH-"] + model.params.get_component("Na+").config.charge**2 * model.state[1].mole_frac_phase_comp_true["Liq", "Na+"] + model.params.get_component("H+").config.charge**2 * model.state[1].mole_frac_phase_comp_true["Liq", "H+"])) assert isinstance(model.state[1].Liq_ionic_strength_ref, Expression) assert len(model.state[1].Liq_ionic_strength_ref) == 1 assert str(model.state[1].Liq_ionic_strength_ref.expr) == str( 0.5 * (model.params.get_component("Cl-").config.charge**2 * model.state[1].Liq_x_ref["Cl-"] + model.params.get_component("OH-").config.charge**2 * model.state[1].Liq_x_ref["OH-"] + model.params.get_component("Na+").config.charge**2 * model.state[1].Liq_x_ref["Na+"] + model.params.get_component("H+").config.charge**2 * model.state[1].Liq_x_ref["H+"])) assert isinstance(model.state[1].Liq_vol_mol_solvent, Expression) assert len(model.state[1].Liq_vol_mol_solvent) == 1 assert str(model.state[1].Liq_vol_mol_solvent.expr) == \ '1/(42*mol/m**3)' assert isinstance(model.state[1].Liq_relative_permittivity_solvent, Expression) assert len(model.state[1].Liq_relative_permittivity_solvent) == 1 assert str( model.state[1].Liq_relative_permittivity_solvent.expr) == (str( model.params.get_component( "H2O").relative_permittivity_liq_comp)) assert isinstance(model.state[1].Liq_A_DH, Expression) assert len(model.state[1].Liq_A_DH) == 1 assert_units_equivalent(model.state[1].Liq_A_DH, pyunits.dimensionless) assert str(model.state[1].Liq_A_DH.expr) == str( (1 / 3) * (2 * Constants.pi * Constants.avogadro_number / model.state[1].Liq_vol_mol_solvent)**0.5 * (Constants.elemental_charge**2 / (4 * Constants.pi * model.state[1].Liq_relative_permittivity_solvent * Constants.vacuum_electric_permittivity * Constants.boltzmann_constant * model.state[1].temperature)) **(3 / 2)) assert isinstance(model.state[1].Liq_log_gamma_pdh, Expression) assert len(model.state[1].Liq_log_gamma_pdh) == 6 for j in model.state[1].Liq_log_gamma_pdh: assert j in ["H2O", "C6H12", "Na+", "H+", "Cl-", "OH-"] if j in ["H2O", "C6H12"]: assert str(model.state[1].Liq_log_gamma_pdh[j].expr) == str( (2 * model.state[1].Liq_A_DH * model.state[1].Liq_ionic_strength**(3 / 2) / (1 + 14.9 * model.state[1].Liq_ionic_strength**(1 / 2)))) else: def ndxdn(j, k): if j == k: return ( (1 - model.state[1].Liq_x_ref[k]) / (model.state[1].mole_frac_phase_comp_true["Liq", "Cl-"] + model.state[1].mole_frac_phase_comp_true["Liq", "OH-"] + model.state[1].mole_frac_phase_comp_true["Liq", "Na+"] + model.state[1].mole_frac_phase_comp_true["Liq", "H+"])) else: return ( -model.state[1].Liq_x_ref[k] / (model.state[1].mole_frac_phase_comp_true["Liq", "Cl-"] + model.state[1].mole_frac_phase_comp_true["Liq", "OH-"] + model.state[1].mole_frac_phase_comp_true["Liq", "Na+"] + model.state[1].mole_frac_phase_comp_true["Liq", "H+"])) assert str(model.state[1].Liq_log_gamma_pdh[j].expr) == str( -model.state[1].Liq_A_DH * ((2 * model.params.get_component(j).config.charge**2 / 14.9) * log( (1 + 14.9 * model.state[1].Liq_ionic_strength**0.5) / (1 + 14.9 * model.state[1].Liq_ionic_strength_ref**0.5)) + (model.params.get_component(j).config.charge**2 * model.state[1].Liq_ionic_strength**0.5 - 2 * model.state[1].Liq_ionic_strength**1.5) / (1 + 14.9 * model.state[1].Liq_ionic_strength**0.5) - (2 * model.state[1].Liq_ionic_strength * model.state[1].Liq_ionic_strength_ref**-0.5) / (1 + 14.9 * model.state[1].Liq_ionic_strength_ref**0.5) * (0.5 * (model.params.get_component("Cl-").config.charge**2 * ndxdn(j, "Cl-") + model.params.get_component( "OH-").config.charge**2 * ndxdn(j, "OH-") + model.params.get_component("Na+").config.charge**2 * ndxdn(j, "Na+") + model.params.get_component( "H+").config.charge**2 * ndxdn(j, "H+"))))) assert isinstance(model.state[1].Liq_log_gamma_lc_I, Expression) assert len(model.state[1].Liq_log_gamma_lc_I) == 6 for k in model.state[1].Liq_log_gamma_lc_I: assert k in ["H2O", "C6H12", "Na+", "H+", "Cl-", "OH-"] assert isinstance(model.state[1].Liq_log_gamma_lc_I0, Expression) assert len(model.state[1].Liq_log_gamma_lc_I0) == 4 for k in model.state[1].Liq_log_gamma_lc_I0: assert k in ["Na+", "H+", "Cl-", "OH-"] assert str(model.state[1].Liq_log_gamma_lc_I0[k].expr) != \ str(model.state[1].Liq_log_gamma_lc_I[k].expr) assert isinstance(model.state[1].Liq_log_gamma_lc, Expression) assert len(model.state[1].Liq_log_gamma_lc) == 6 for k in model.state[1].Liq_log_gamma_lc: assert k in ["H2O", "C6H12", "Na+", "H+", "Cl-", "OH-"] if k in ["H2O", "C6H12"]: assert str(model.state[1].Liq_log_gamma_lc[k].expr) == \ str(model.state[1].Liq_log_gamma_lc_I[k]) else: assert str(model.state[1].Liq_log_gamma_lc[k].expr) == str( model.state[1].Liq_log_gamma_lc_I[k] - model.state[1].Liq_log_gamma_lc_I0[k]) assert isinstance(model.state[1].Liq_log_gamma, Expression) assert len(model.state[1].Liq_log_gamma) == 6 for k, v in model.state[1].Liq_log_gamma.items(): assert str(model.state[1].Liq_log_gamma[k].expr) == str( model.state[1].Liq_log_gamma_pdh[k] + model.state[1].Liq_log_gamma_lc[k])
def test_unhandled_expressions(self): m = ConcreteModel() m.x = Var() m.c1 = Constraint(expr=0 <= log(m.x)) self.assertTrue(satisfiable(m))
def Hen0_rule(block, i): return block.Hen0[i] == e.henry.A[i] + e.henry.B[i]/block.parent_block().T + e.henry.C[i]*pe.log(block.parent_block().T) + \ e.henry.D[i]*(block.parent_block().T**2) + e.henry.E[i]/(block.parent_block().T**2)
def obj_rule(model): return pe.log(model.Vi_upper - model.Vi_lower) + pe.log( model.Vj_upper - model.Vi_lower) + pe.log(model.delta_upper - model.delta_lower)
def gamma_rule(block, i): return pe.log(block.gamma[i])*(block.n_ave - cal_cnumber('C6H14')) == \ pe.log(block.gamma_ref)*(block.n_ave - cal_cnumber(i))
def valensi(*data): pd = data[0] return 1.0 / (-1.0 * pyo.log(1.0 - pd))
def delta_temperature(b, t): return (dT2[t] - dT1[t]) / (log(dT2[t]) - log(dT1[t]))
def head_isen_eqn(b, t): f = pyo.log(fscale * b.parent_block().control_volume.properties_in[t].flow_vol) return b.head_isentropic[t] == -(-2085.1 * f**3 + 38433 * f**2 - 150764 * f + 422313)