From a93ef141f57e0961d6948b8ab906af3b83a59e73 Mon Sep 17 00:00:00 2001 From: Caleb Bell Date: Fri, 26 Jul 2024 13:47:16 -0600 Subject: [PATCH 1/9] new config file --- .ruff.toml | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/.ruff.toml b/.ruff.toml index ef196c31..028b9e26 100644 --- a/.ruff.toml +++ b/.ruff.toml @@ -10,13 +10,28 @@ exclude = [ # "UP031", # "UP032", # ] + + + +[lint] select = ["ALL"] + extend-ignore = [ + "FIX002", # TODO are OK + "FIX004", # HACK is OK + "D415", # First docstring line should end with a period, question mark, or exclamation point "DTZ004", # utcfromtimestamp makes sense for atmosphere model "PGH003", # type ignoring makes sense for numba-related things "S102", # Yes, exec is dangerous but it can be quite useful as well + "PYI056", # changing __all__ + + "RUF012", # not using typing today + "PERF403", # obvious, use an autofix if one becomes available + "PERF203", # `try`-`except` within a loop incurs performance overhead + "PERF401", # PERF401 Use a list comprehension to create a transformed list + # chemicals specific "E701", # lots of this here @@ -139,13 +154,15 @@ extend-ignore = [ "TRY002", "TRY003", "TRY004", - "TRY200", + "B904", "TRY201", "TRY300", "TRY301", "TRY400", "Q000", "Q002", + + "PYI024", # PYI024 Use `typing.NamedTuple` instead of `collections.namedtuple ] -[mccabe] +[lint.mccabe] max-complexity = 10 From aca996e1e35850b90a0470cec8dfde6d71b14517 Mon Sep 17 00:00:00 2001 From: Caleb Bell Date: Fri, 26 Jul 2024 13:50:48 -0600 Subject: [PATCH 2/9] UP032,W293,UP031 --- thermo/activity.py | 4 +- thermo/chemical_package.py | 8 +- thermo/eos_mix.py | 8 +- thermo/equilibrium.py | 14 +-- thermo/flash/flash_base.py | 4 +- thermo/flash/flash_pure_vls.py | 8 +- thermo/group_contribution/joback.py | 7 +- thermo/phases/ceos.py | 2 +- thermo/phases/phase.py | 20 ++--- thermo/phases/virial_phase.py | 4 +- thermo/property_package.py | 30 +++---- thermo/regular_solution.py | 3 +- thermo/stream.py | 4 +- thermo/unifac.py | 5 +- thermo/utils/t_dependent_property.py | 118 +++++++++----------------- thermo/utils/tp_dependent_property.py | 2 +- 16 files changed, 95 insertions(+), 146 deletions(-) diff --git a/thermo/activity.py b/thermo/activity.py index bbfaecce..e8540df0 100644 --- a/thermo/activity.py +++ b/thermo/activity.py @@ -391,7 +391,7 @@ def exact_hash(self): d = object_data(self) ans = hash_any_primitive((self.__class__.__name__, d)) return ans - + def as_json(self, cache=None, option=0): r'''Method to create a JSON-friendly representation of the Gibbs Excess model which can be stored, and reloaded later. @@ -1028,7 +1028,7 @@ def _regress_binary_parameters(cls, gammas, xs, fitting_func, fit_parameters, **fit_kwargs) return res - + derivatives_added = [('dGE_dT', 'GE', 1), ('d2GE_dT2', 'GE', 2), ('d3GE_dT3', 'GE', 3), diff --git a/thermo/chemical_package.py b/thermo/chemical_package.py index dc6f8411..50ab193a 100644 --- a/thermo/chemical_package.py +++ b/thermo/chemical_package.py @@ -186,7 +186,7 @@ def _custom_as_json(self, d, cache): for k in ('PSRK_groups', 'UNIFAC_Dortmund_groups', 'UNIFAC_groups'): # keys are stored as strings and not ints d[k] = [{str(k): v for k, v in r.items()} if r is not None else r for r in d[k]] - + # This is not so much a performance optimization as an improvement on file size # and readability. Do not remove it! Comparing against an empty list is the @@ -1374,9 +1374,9 @@ def __init__(self, CASs=None, names=None, MWs=None, Tms=None, Tbs=None, """ for name, (var_type, desc, units, return_desc) in constants_docstrings.items(): type_name = var_type if type(var_type) is str else var_type.__name__ - new = """{} : {} - {}, {}. -""".format(name, type_name, desc, units) + new = f"""{name} : {type_name} + {desc}, {units}. +""" constants_doc += new try: diff --git a/thermo/eos_mix.py b/thermo/eos_mix.py index 61a0765a..2c1168b7 100644 --- a/thermo/eos_mix.py +++ b/thermo/eos_mix.py @@ -2797,7 +2797,7 @@ def d3b_dzizjzks(self): ''' N = self.N return zeros((N, N, N)) if self.vectorized else [[[0.0]*N for _ in range(N)] for _ in range(N)] - + @property def d3b_dninjnks(self): r'''Helper method for calculating the third partial mole number @@ -2860,7 +2860,7 @@ def d3epsilon_dzizjzks(self): ''' N = self.N return zeros((N, N, N)) if self.vectorized else [[[0.0]*N for _ in range(N)] for _ in range(N)] - + @property def d3delta_dzizjzks(self): r'''Helper method for calculating the third composition derivatives @@ -2882,7 +2882,7 @@ def d3delta_dzizjzks(self): ''' N = self.N return zeros((N, N, N)) if self.vectorized else [[[0.0]*N for _ in range(N)] for _ in range(N)] - + @property def da_alpha_dzs(self): r'''Helper method for calculating the composition derivatives of @@ -3132,7 +3132,7 @@ def da_alpha_dT_dzs(self): except: da_alpha_dT_j_rows = self._da_alpha_dT_j_rows return 2.0*da_alpha_dT_j_rows if self.vectorized else [i + i for i in da_alpha_dT_j_rows] - + @property def da_alpha_dT_dns(self): r'''Helper method for calculating the mole number derivatives of diff --git a/thermo/equilibrium.py b/thermo/equilibrium.py index 425d560e..1129359b 100644 --- a/thermo/equilibrium.py +++ b/thermo/equilibrium.py @@ -3330,12 +3330,12 @@ def get_bulk_property(self): type_name = var_type if type(var_type) is str else var_type.__name__ if return_desc is None: return_desc = desc - full_desc = """{}, {}. + full_desc = f"""{desc}, {units}. Returns ------- -{} : {} - {}, {}.""".format(desc, units, name, type_name, return_desc, units) +{name} : {type_name} + {return_desc}, {units}.""" # print(full_desc) getter.__doc__ = full_desc except: @@ -3642,12 +3642,12 @@ def get(self): getter = _make_getter_component_molar_weight(_CAS) name = '%s_molar_weight' %(_name) - _add_attrs_doc = r"""Method to calculate and return the effective quantiy - of {} in the phase as a molar weight, [g/mol]. + _add_attrs_doc = rf"""Method to calculate and return the effective quantiy + of {_name} in the phase as a molar weight, [g/mol]. This is the molecular weight of the phase times the mass fraction of the - {} component. - """.format(_name, _name) + {_name} component. + """ getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) diff --git a/thermo/flash/flash_base.py b/thermo/flash/flash_base.py index 8625d75c..90688cc2 100644 --- a/thermo/flash/flash_base.py +++ b/thermo/flash/flash_base.py @@ -325,8 +325,8 @@ def flash(self, zs=None, T=None, P=None, VF=None, SF=None, V=None, H=None, T = float(T) flash_specs['T'] = T if T < self.T_MIN_FLASH_ANY: - raise ValueError("Specified temperature ({} K) is below the minimum temeprature ({} K) " - "supported by any of the provided phases".format(T, self.T_MIN_FLASH_ANY)) + raise ValueError(f"Specified temperature ({T} K) is below the minimum temeprature ({self.T_MIN_FLASH_ANY} K) " + "supported by any of the provided phases") # if T <= 0.0: # raise ValueError("Specified temperature (%s K) is unphysical" %(T,)) if P_spec: diff --git a/thermo/flash/flash_pure_vls.py b/thermo/flash/flash_pure_vls.py index ee140808..92a91b41 100644 --- a/thermo/flash/flash_pure_vls.py +++ b/thermo/flash/flash_pure_vls.py @@ -941,16 +941,12 @@ def selection_fun_1P(new, prev): uncertain_solution = True if VL_liq is not None: - s += '({}, {}) VL 2 Phase solution: ({:g}, {:g}); '.format( - VL_liq.__class__.__name__, VL_gas.__class__.__name__, - spec_val_l, spec_val_g) + s += f'({VL_liq.__class__.__name__}, {VL_gas.__class__.__name__}) VL 2 Phase solution: ({spec_val_l:g}, {spec_val_g:g}); ' VL_min_spec, VL_max_spec = min(spec_val_l, spec_val_g), max(spec_val_l, spec_val_g), if VL_min_spec <= spec_val <= VL_max_spec: had_solution = True if SF is not None: - s += '({}, {}) VL 2 Phase solution: ({:g}, {:g}); '.format( - VS_flash.phases[0].__class__.__name__, VS_flash.solid0.__class__.__name__, - spec_val_s, spec_other) + s += f'({VS_flash.phases[0].__class__.__name__}, {VS_flash.solid0.__class__.__name__}) VL 2 Phase solution: ({spec_val_s:g}, {spec_other:g}); ' S_min_spec, S_max_spec = min(spec_val_s, spec_other), max(spec_val_s, spec_other), if S_min_spec <= spec_val <= S_max_spec: had_solution = True diff --git a/thermo/group_contribution/joback.py b/thermo/group_contribution/joback.py index 9779b7f2..1f2a9928 100644 --- a/thermo/group_contribution/joback.py +++ b/thermo/group_contribution/joback.py @@ -203,11 +203,8 @@ def __init__(self, i, name, Tc, Pc, Vc, Tb, Tm, Hform, Gform, Cpa, Cpb, self.mub = mub def __repr__(self): - return """JOBACK(i={!r}, name={!r}, Tc={!r}, Pc={!r}, Vc={!r}, Tb={!r}, Tm={!r}, Hform={!r}, Gform={!r}, -Cpa={!r}, Cpb={!r}, Cpc={!r}, Cpd={!r}, Hfus={!r}, Hvap={!r}, mua={!r}, mub={!r})""".format( - self.i, self.name, self.Tc, self.Pc, self.Vc, self.Tb, self.Tm, - self.Hform, self.Gform, self.Cpa, self.Cpb, self.Cpc, self.Cpd, - self.Hfus, self.Hvap, self.mua, self.mub) + return f"""JOBACK(i={self.i!r}, name={self.name!r}, Tc={self.Tc!r}, Pc={self.Pc!r}, Vc={self.Vc!r}, Tb={self.Tb!r}, Tm={self.Tm!r}, Hform={self.Hform!r}, Gform={self.Gform!r}, +Cpa={self.Cpa!r}, Cpb={self.Cpb!r}, Cpc={self.Cpc!r}, Cpd={self.Cpd!r}, Hfus={self.Hfus!r}, Hvap={self.Hvap!r}, mua={self.mua!r}, mub={self.mub!r})""" joback_groups_str_dict = {'-CH3': JOBACK(i=1, name='-CH3', Tc=0.0141, Pc=-0.0012, Vc=65.0, Tb=23.58, Tm=-5.1, Hform=-76.45, Gform=-43.96, Cpa=19.5, Cpb=-0.00808, Cpc=0.000153, Cpd=-9.67e-08, Hfus=0.908, Hvap=2.373, mua=548.29, mub=-1.719), diff --git a/thermo/phases/ceos.py b/thermo/phases/ceos.py index 661a8ef4..5304e062 100644 --- a/thermo/phases/ceos.py +++ b/thermo/phases/ceos.py @@ -101,7 +101,7 @@ class CEOSPhase(IdealGasDeparturePhase): def _custom_as_json(self, d, cache): d['eos_class'] = d['eos_class'].__full_path__ - + def _custom_from_json(self, *args): self.eos_class = eos_mix_full_path_dict[self.eos_class] diff --git a/thermo/phases/phase.py b/thermo/phases/phase.py index c8bc8629..19cbb60d 100644 --- a/thermo/phases/phase.py +++ b/thermo/phases/phase.py @@ -6284,16 +6284,16 @@ def gammas(self): def _der(self, property=a, differentiate_by=b, at_constant=c): return self._derivs_jacobian(a=property, b=differentiate_by, c=at_constant) t = f'd{a}_d{b}_{c}' - doc = r"""Method to calculate and return the {} derivative of {} of the phase at constant {}. + doc = rf"""Method to calculate and return the {b_name} derivative of {a_name} of the phase at constant {c_name}. .. math:: - \left(\frac{{\partial {}}}{{\partial {}}}\right)_{{{}}} + \left(\frac{{\partial {a_str}}}{{\partial {b_str}}}\right)_{{{c}}} Returns ------- -{} : float - The {} derivative of {} of the phase at constant {}, [{}/{}] -""".format(b_name, a_name, c_name, a_str, b_str, c, t, b_name, a_name, c_name, a_units, b_units) +{t} : float + The {b_name} derivative of {a_name} of the phase at constant {c_name}, [{a_units}/{b_units}] +""" setattr(Phase, t, _der) try: _der.__doc__ = doc @@ -6345,16 +6345,16 @@ def _der(self, prop=attr): if not '2' in attr: # TODO docs for second mass derivatives - doc = r"""Method to calculate and return the {} derivative of mass {} of the phase at constant {}. + doc = rf"""Method to calculate and return the {prop_names[diff_by]} derivative of mass {prop_names[prop]} of the phase at constant {prop_names[at_constant]}. .. math:: - \left(\frac{{\partial {}_{{\text{{mass}}}}}}{{\partial {}}}\right)_{{{}}} + \left(\frac{{\partial {prop}_{{\text{{mass}}}}}}{{\partial {diff_by}}}\right)_{{{at_constant}}} Returns ------- - {} : float - The {} derivative of mass {} of the phase at constant {}, [{}/{}] - """.format(prop_names[diff_by], prop_names[prop], prop_names[at_constant], prop, diff_by, at_constant, s, prop_names[diff_by], prop_names[prop], prop_names[at_constant], prop_units[prop], prop_units[diff_by]) + {s} : float + The {prop_names[diff_by]} derivative of mass {prop_names[prop]} of the phase at constant {prop_names[at_constant]}, [{prop_units[prop]}/{prop_units[diff_by]}] + """ try: _der.__doc__ = doc#'Automatically generated derivative. %s %s' %(base, end) except: diff --git a/thermo/phases/virial_phase.py b/thermo/phases/virial_phase.py index 7eeec2a0..92230114 100644 --- a/thermo/phases/virial_phase.py +++ b/thermo/phases/virial_phase.py @@ -347,8 +347,8 @@ def exact_hash(self): d = self.__dict__ ans = hash_any_primitive((self.__class__.__name__, self.state_hash(), self.model_hash(), d)) return ans - - + + def __eq__(self, other): return self.__hash__() == hash(other) diff --git a/thermo/property_package.py b/thermo/property_package.py index 9ec37f48..5d0d65cd 100644 --- a/thermo/property_package.py +++ b/thermo/property_package.py @@ -744,9 +744,8 @@ def PH_VF_error(VF, P, zs, H_goal): if Hm < Hm_low: raise ValueError('The requested molar enthalpy cannot be found' ' with this bounded solver because the lower ' - 'temperature bound {:g} K has an enthalpy ({:g} ' - 'J/mol) higher than that requested ({:g} J/mol)'.format( - T_low, Hm_low, Hm)) + f'temperature bound {T_low:g} K has an enthalpy ({Hm_low:g} ' + f'J/mol) higher than that requested ({Hm:g} J/mol)') if Hm_high is None: pkg_high = self.to(T=T_high, P=P, zs=zs) pkg_high._post_flash() @@ -754,9 +753,8 @@ def PH_VF_error(VF, P, zs, H_goal): if Hm > Hm_high: raise ValueError('The requested molar enthalpy cannot be found' ' with this bounded solver because the upper ' - 'temperature bound {:g} K has an enthalpy ({:g} ' - 'J/mol) lower than that requested ({:g} J/mol)'.format( - T_high, Hm_high, Hm)) + f'temperature bound {T_high:g} K has an enthalpy ({Hm_high:g} ' + f'J/mol) lower than that requested ({Hm:g} J/mol)') def flash_PS_zs_bounded(self, P, Sm, zs, T_low=None, T_high=None, @@ -815,9 +813,8 @@ def PS_VF_error(VF, P, zs, S_goal): if Sm < Sm_low: raise ValueError('The requested molar entropy cannot be found' ' with this bounded solver because the lower ' - 'temperature bound {:g} K has an entropy ({:g} ' - 'J/mol/K) higher than that requested ({:g} J/mol/K)'.format( - T_low, Sm_low, Sm)) + f'temperature bound {T_low:g} K has an entropy ({Sm_low:g} ' + f'J/mol/K) higher than that requested ({Sm:g} J/mol/K)') if Sm_high is None: pkg_high = self.to(T=T_high, P=P, zs=zs) pkg_high._post_flash() @@ -825,9 +822,8 @@ def PS_VF_error(VF, P, zs, S_goal): if Sm > Sm_high: raise ValueError('The requested molar entropy cannot be found' ' with this bounded solver because the upper ' - 'temperature bound {:g} K has an entropy ({:g} ' - 'J/mol/K) lower than that requested ({:g} J/mol/K)'.format( - T_high, Sm_high, Sm)) + f'temperature bound {T_high:g} K has an entropy ({Sm_high:g} ' + f'J/mol/K) lower than that requested ({Sm:g} J/mol/K)') def flash_TS_zs_bounded(self, T, Sm, zs, P_low=None, P_high=None, Sm_low=None, Sm_high=None): @@ -876,9 +872,8 @@ def TS_VF_error(VF, T, zs, S_goal): if Sm > Sm_low: raise ValueError('The requested molar entropy cannot be found' ' with this bounded solver because the lower ' - 'pressure bound {:g} Pa has an entropy ({:g} ' - 'J/mol/K) lower than that requested ({:g} J/mol/K)'.format( - P_low, Sm_low, Sm)) + f'pressure bound {P_low:g} Pa has an entropy ({Sm_low:g} ' + f'J/mol/K) lower than that requested ({Sm:g} J/mol/K)') if Sm_high is None: pkg_high = self.to(T=T, P=P_high, zs=zs) pkg_high._post_flash() @@ -886,9 +881,8 @@ def TS_VF_error(VF, T, zs, S_goal): if Sm < Sm_high: raise ValueError('The requested molar entropy cannot be found' ' with this bounded solver because the upper ' - 'pressure bound {:g} Pa has an entropy ({:g} ' - 'J/mol/K) upper than that requested ({:g} J/mol/K)'.format( - P_high, Sm_high, Sm)) + f'pressure bound {P_high:g} Pa has an entropy ({Sm_high:g} ' + f'J/mol/K) upper than that requested ({Sm:g} J/mol/K)') @property def Hm_reactive(self): Hm = self.Hm diff --git a/thermo/regular_solution.py b/thermo/regular_solution.py index 2e1dd049..d4d7e5f7 100644 --- a/thermo/regular_solution.py +++ b/thermo/regular_solution.py @@ -377,8 +377,7 @@ def __init__(self, T, xs, Vs, SPs, lambda_coeffs=None): def __repr__(self): - s = '{}(T={}, xs={}, Vs={}, SPs={}'.format(self.__class__.__name__, repr(self.T), repr(self.xs), - self.Vs, self.SPs) + s = f'{self.__class__.__name__}(T={repr(self.T)}, xs={repr(self.xs)}, Vs={self.Vs}, SPs={self.SPs}' if not self._lambda_coeffs_zero: s += f' , lambda_coeffs={self.lambda_coeffs})' else: diff --git a/thermo/stream.py b/thermo/stream.py index fd8aee84..92c30df4 100644 --- a/thermo/stream.py +++ b/thermo/stream.py @@ -895,7 +895,7 @@ def Vfgs(self, arg): def ns(self): r'''Mole flows of the stream if specified [mol/s]''' return self.specifications['ns'] - + @ns.setter def ns(self, arg): r'''Set the mole flows of the stream [mol/s]''' @@ -1769,7 +1769,7 @@ def update(self, **kwargs): """ for key, value in kwargs.items(): setattr(self, key, value) - + def stream(self, existing_flash=None, hot_start=None): r'''Create and return an EquilibriumStream object using the set specifications. If `existing_flash` is provided, that :obj:`EquilibriumState` object will be used diff --git a/thermo/unifac.py b/thermo/unifac.py index 5be99cb3..9be43e80 100644 --- a/thermo/unifac.py +++ b/thermo/unifac.py @@ -4416,7 +4416,7 @@ class UNIFAC(GibbsExcess): __slots__ = GibbsExcess.__slots__ + _cached_calculated_attributes + ('N_groups', 'Qs', 'cmp_group_idx', 'cmp_v_count', 'cmp_v_count_inv', 'group_cmp_idx', 'psi_a', 'psi_b', 'psi_c', 'qs', 'r34x_sum_inv', 'rs', 'rs_34', 'skip_comb', 'version', 'vs', '_Xs_pure', '_Thetas_pure') - + recalculable_attributes = GibbsExcess.recalculable_attributes + _cached_calculated_attributes @@ -4608,8 +4608,7 @@ def __repr__(self): # pragma: no cover psi_abc = (self.psi_a, self.psi_b, self.psi_c) s = 'UNIFAC(' s += f'T={self.T}, xs={self.xs}, rs={self.rs}, qs={self.qs}' - s += ', Qs={}, vs={}, psi_abc={}, version={}'.format(self.Qs, self.vs, - psi_abc, self.version) + s += f', Qs={self.Qs}, vs={self.vs}, psi_abc={psi_abc}, version={self.version}' s += ')' return s diff --git a/thermo/utils/t_dependent_property.py b/thermo/utils/t_dependent_property.py index 0f935c38..ead3a42c 100644 --- a/thermo/utils/t_dependent_property.py +++ b/thermo/utils/t_dependent_property.py @@ -1623,7 +1623,7 @@ def _custom_from_json(self, *args): self.T_cached = None # No need to set self.prop_cached - + for correlation_name in TDependentProperty.correlation_models.keys(): # Should be lazy created? correlation_key = TDependentProperty.correlation_parameters[correlation_name] @@ -2318,8 +2318,8 @@ def method(self): @method.setter def method(self, method): if method not in self.all_methods and method is not None: - raise ValueError("Method '{}' is not available for this chemical; " - "available methods are {}".format(method, self.all_methods)) + raise ValueError(f"Method '{method}' is not available for this chemical; " + f"available methods are {self.all_methods}") self.T_cached = None self._method = method @@ -2691,65 +2691,29 @@ def as_poly_fit(self): raise ValueError("No polynomial fit defined") if method == POLY_FIT: - return '{}(load_data=False, poly_fit=({}, {}, {}))'.format(self.__class__.__name__, - repr(self.poly_fit_Tmin), repr(self.poly_fit_Tmax), - repr(self.poly_fit_coeffs)) + return f'{self.__class__.__name__}(load_data=False, poly_fit=({repr(self.poly_fit_Tmin)}, {repr(self.poly_fit_Tmax)}, {repr(self.poly_fit_coeffs)}))' elif method == EXP_POLY_FIT: - return '{}(load_data=False, exp_poly_fit=({}, {}, {}))'.format(self.__class__.__name__, - repr(self.exp_poly_fit_Tmin), repr(self.exp_poly_fit_Tmax), - repr(self.exp_poly_fit_coeffs)) + return f'{self.__class__.__name__}(load_data=False, exp_poly_fit=({repr(self.exp_poly_fit_Tmin)}, {repr(self.exp_poly_fit_Tmax)}, {repr(self.exp_poly_fit_coeffs)}))' elif method == POLY_FIT_LN_TAU: - return '{}(load_data=False, Tc={}, poly_fit_ln_tau=({}, {}, {}, {}))'.format(self.__class__.__name__, - repr(self.poly_fit_ln_tau_Tc), - repr(self.poly_fit_ln_tau_Tmin), repr(self.poly_fit_ln_tau_Tmax), - repr(self.poly_fit_ln_tau_Tc), - repr(self.poly_fit_ln_tau_coeffs)) + return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.poly_fit_ln_tau_Tc)}, poly_fit_ln_tau=({repr(self.poly_fit_ln_tau_Tmin)}, {repr(self.poly_fit_ln_tau_Tmax)}, {repr(self.poly_fit_ln_tau_Tc)}, {repr(self.poly_fit_ln_tau_coeffs)}))' elif method == EXP_POLY_FIT_LN_TAU: - return '{}(load_data=False, Tc={}, exp_poly_fit_ln_tau=({}, {}, {}, {}))'.format(self.__class__.__name__, - repr(self.exp_poly_fit_ln_tau_Tc), - repr(self.exp_poly_fit_ln_tau_Tmin), repr(self.exp_poly_fit_ln_tau_Tmax), - repr(self.exp_poly_fit_ln_tau_Tc), - repr(self.exp_poly_fit_ln_tau_coeffs)) + return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.exp_poly_fit_ln_tau_Tc)}, exp_poly_fit_ln_tau=({repr(self.exp_poly_fit_ln_tau_Tmin)}, {repr(self.exp_poly_fit_ln_tau_Tmax)}, {repr(self.exp_poly_fit_ln_tau_Tc)}, {repr(self.exp_poly_fit_ln_tau_coeffs)}))' elif method == STABLEPOLY_FIT: - return '{}(load_data=False, stablepoly_fit=({}, {}, {}))'.format(self.__class__.__name__, - repr(self.stablepoly_fit_Tmin), repr(self.stablepoly_fit_Tmax), - repr(self.stablepoly_fit_coeffs)) + return f'{self.__class__.__name__}(load_data=False, stablepoly_fit=({repr(self.stablepoly_fit_Tmin)}, {repr(self.stablepoly_fit_Tmax)}, {repr(self.stablepoly_fit_coeffs)}))' elif method == EXP_STABLEPOLY_FIT: - return '{}(load_data=False, exp_stablepoly_fit=({}, {}, {}))'.format(self.__class__.__name__, - repr(self.exp_stablepoly_fit_Tmin), repr(self.exp_stablepoly_fit_Tmax), - repr(self.exp_stablepoly_fit_coeffs)) + return f'{self.__class__.__name__}(load_data=False, exp_stablepoly_fit=({repr(self.exp_stablepoly_fit_Tmin)}, {repr(self.exp_stablepoly_fit_Tmax)}, {repr(self.exp_stablepoly_fit_coeffs)}))' elif method == STABLEPOLY_FIT_LN_TAU: - return '{}(load_data=False, Tc={}, stablepoly_fit_ln_tau=({}, {}, {}, {}))'.format(self.__class__.__name__, - repr(self.stablepoly_fit_ln_tau_Tc), - repr(self.stablepoly_fit_ln_tau_Tmin), repr(self.stablepoly_fit_ln_tau_Tmax), - repr(self.stablepoly_fit_ln_tau_Tc), - repr(self.stablepoly_fit_ln_tau_coeffs)) + return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.stablepoly_fit_ln_tau_Tc)}, stablepoly_fit_ln_tau=({repr(self.stablepoly_fit_ln_tau_Tmin)}, {repr(self.stablepoly_fit_ln_tau_Tmax)}, {repr(self.stablepoly_fit_ln_tau_Tc)}, {repr(self.stablepoly_fit_ln_tau_coeffs)}))' elif method == EXP_STABLEPOLY_FIT_LN_TAU: - return '{}(load_data=False, Tc={}, exp_stablepoly_fit_ln_tau=({}, {}, {}, {}))'.format(self.__class__.__name__, - repr(self.exp_stablepoly_fit_ln_tau_Tc), - repr(self.exp_stablepoly_fit_ln_tau_Tmin), repr(self.exp_stablepoly_fit_ln_tau_Tmax), - repr(self.exp_stablepoly_fit_ln_tau_Tc), - repr(self.exp_stablepoly_fit_ln_tau_coeffs)) + return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.exp_stablepoly_fit_ln_tau_Tc)}, exp_stablepoly_fit_ln_tau=({repr(self.exp_stablepoly_fit_ln_tau_Tmin)}, {repr(self.exp_stablepoly_fit_ln_tau_Tmax)}, {repr(self.exp_stablepoly_fit_ln_tau_Tc)}, {repr(self.exp_stablepoly_fit_ln_tau_coeffs)}))' elif method == CHEB_FIT: - return '{}(load_data=False, cheb_fit=({}, {}, {}))'.format(self.__class__.__name__, - repr(self.cheb_fit_Tmin), repr(self.cheb_fit_Tmax), - repr(self.cheb_fit_coeffs)) + return f'{self.__class__.__name__}(load_data=False, cheb_fit=({repr(self.cheb_fit_Tmin)}, {repr(self.cheb_fit_Tmax)}, {repr(self.cheb_fit_coeffs)}))' elif method == EXP_CHEB_FIT: - return '{}(load_data=False, exp_cheb_fit=({}, {}, {}))'.format(self.__class__.__name__, - repr(self.exp_cheb_fit_Tmin), repr(self.exp_cheb_fit_Tmax), - repr(self.exp_cheb_fit_coeffs)) + return f'{self.__class__.__name__}(load_data=False, exp_cheb_fit=({repr(self.exp_cheb_fit_Tmin)}, {repr(self.exp_cheb_fit_Tmax)}, {repr(self.exp_cheb_fit_coeffs)}))' elif method == CHEB_FIT_LN_TAU: - return '{}(load_data=False, Tc={}, cheb_fit_ln_tau=({}, {}, {}, {}))'.format(self.__class__.__name__, - repr(self.cheb_fit_ln_tau_Tc), - repr(self.cheb_fit_ln_tau_Tmin), repr(self.cheb_fit_ln_tau_Tmax), - repr(self.cheb_fit_ln_tau_Tc), - repr(self.cheb_fit_ln_tau_coeffs)) + return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.cheb_fit_ln_tau_Tc)}, cheb_fit_ln_tau=({repr(self.cheb_fit_ln_tau_Tmin)}, {repr(self.cheb_fit_ln_tau_Tmax)}, {repr(self.cheb_fit_ln_tau_Tc)}, {repr(self.cheb_fit_ln_tau_coeffs)}))' elif method == EXP_CHEB_FIT_LN_TAU: - return '{}(load_data=False, Tc={}, exp_cheb_fit_ln_tau=({}, {}, {}, {}))'.format(self.__class__.__name__, - repr(self.exp_cheb_fit_ln_tau_Tc), - repr(self.exp_cheb_fit_ln_tau_Tmin), repr(self.exp_cheb_fit_ln_tau_Tmax), - repr(self.exp_cheb_fit_ln_tau_Tc), - repr(self.exp_cheb_fit_ln_tau_coeffs)) + return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.exp_cheb_fit_ln_tau_Tc)}, exp_cheb_fit_ln_tau=({repr(self.exp_cheb_fit_ln_tau_Tmin)}, {repr(self.exp_cheb_fit_ln_tau_Tmax)}, {repr(self.exp_cheb_fit_ln_tau_Tc)}, {repr(self.exp_cheb_fit_ln_tau_coeffs)}))' def _base_calculate(self, T, method): if method in self.correlations: @@ -3918,14 +3882,14 @@ def T_dependent_property_derivative(self, T, order=1): except: if self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "Failed to extrapolate {}th derivative of {} method '{}' " - "at T={} K for component with CASRN '{}'".format(order, self.name.lower(), method, T, self.CASRN) + f"Failed to extrapolate {order}th derivative of {self.name.lower()} method '{method}' " + f"at T={T} K for component with CASRN '{self.CASRN}'" ) return None elif self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "{} method '{}' is not valid at T={} K " - "for component with CASRN '{}'".format(self.name, method, T, self.CASRN) + f"{self.name} method '{method}' is not valid at T={T} K " + f"for component with CASRN '{self.CASRN}'" ) else: return None @@ -3934,8 +3898,8 @@ def T_dependent_property_derivative(self, T, order=1): except: if self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "Failed to evaluate {}th derivative of {} method '{}' " - "at T={} K for component with CASRN '{}'".format(order, self.name.lower(), method, T, self.CASRN) + f"Failed to evaluate {order}th derivative of {self.name.lower()} method '{method}' " + f"at T={T} K for component with CASRN '{self.CASRN}'" ) def calculate_integral(self, T1, T2, method): @@ -4036,15 +4000,15 @@ def T_dependent_property_integral(self, T1, T2): except: # pragma: no cover if self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "Failed to extrapolate integral of {} method '{}' " - "between T={} to {} K for component with CASRN '{}'".format(self.name.lower(), method, T1, Tmin, self.CASRN) + f"Failed to extrapolate integral of {self.name.lower()} method '{method}' " + f"between T={T1} to {Tmin} K for component with CASRN '{self.CASRN}'" ) else: return None elif self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "{} method '{}' is not valid between T={} to T={} K " - "for component with CASRN '{}'".format(self.name, method, T1, Tmin, self.CASRN) + f"{self.name} method '{method}' is not valid between T={T1} to T={Tmin} K " + f"for component with CASRN '{self.CASRN}'" ) else: return None @@ -4060,15 +4024,15 @@ def T_dependent_property_integral(self, T1, T2): except: if self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "Failed to extrapolate integral of {} method '{}' " - "between T={} to {} K for component with CASRN '{}'".format(self.name.lower(), method, Tmax, T2, self.CASRN) + f"Failed to extrapolate integral of {self.name.lower()} method '{method}' " + f"between T={Tmax} to {T2} K for component with CASRN '{self.CASRN}'" ) else: return None elif self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "{} method '{}' is not valid between T={} to T={} K " - "for component with CASRN '{}'".format(self.name, method, T2, Tmax, self.CASRN) + f"{self.name} method '{method}' is not valid between T={T2} to T={Tmax} K " + f"for component with CASRN '{self.CASRN}'" ) else: return None @@ -4078,8 +4042,8 @@ def T_dependent_property_integral(self, T1, T2): except: # pragma: no cover if self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "Failed to evaluate integral of {} method '{}' " - "between T={} to {} K for component with CASRN '{}'".format(self.name.lower(), method, Tmax, T2, self.CASRN) + f"Failed to evaluate integral of {self.name.lower()} method '{method}' " + f"between T={Tmax} to {T2} K for component with CASRN '{self.CASRN}'" ) else: return None @@ -4185,15 +4149,15 @@ def T_dependent_property_integral_over_T(self, T1, T2): except: if self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "Failed to extrapolate integral-over-T of {} method '{}' " - "between T={} to {} K for component with CASRN '{}'".format(self.name.lower(), method, T1, Tmin, self.CASRN) + f"Failed to extrapolate integral-over-T of {self.name.lower()} method '{method}' " + f"between T={T1} to {Tmin} K for component with CASRN '{self.CASRN}'" ) else: return None elif self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "{} method '{}' is not valid between T={} to T={} K " - "for component with CASRN '{}'".format(self.name, method, T1, Tmin, self.CASRN) + f"{self.name} method '{method}' is not valid between T={T1} to T={Tmin} K " + f"for component with CASRN '{self.CASRN}'" ) else: return None @@ -4209,15 +4173,15 @@ def T_dependent_property_integral_over_T(self, T1, T2): except: # pragma: no cover if self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "Failed to extrapolate integral-over-T of {} method '{}' " - "between T={} to {} K for component with CASRN '{}'".format(self.name.lower(), method, Tmax, T2, self.CASRN) + f"Failed to extrapolate integral-over-T of {self.name.lower()} method '{method}' " + f"between T={Tmax} to {T2} K for component with CASRN '{self.CASRN}'" ) else: return None elif self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "{} method '{}' is not valid between T={} to T={} K " - "for component with CASRN '{}'".format(self.name, method, T2, Tmax, self.CASRN) + f"{self.name} method '{method}' is not valid between T={T2} to T={Tmax} K " + f"for component with CASRN '{self.CASRN}'" ) else: return None @@ -4227,8 +4191,8 @@ def T_dependent_property_integral_over_T(self, T1, T2): except: if self.RAISE_PROPERTY_CALCULATION_ERROR: raise RuntimeError( - "Failed to evaluate integral-over-T of {} method '{}' " - "between T={} to {} K for component with CASRN '{}'".format(self.name.lower(), method, Tmax, T2, self.CASRN) + f"Failed to evaluate integral-over-T of {self.name.lower()} method '{method}' " + f"between T={Tmax} to {T2} K for component with CASRN '{self.CASRN}'" ) else: return None diff --git a/thermo/utils/tp_dependent_property.py b/thermo/utils/tp_dependent_property.py index 31379d74..373da7d5 100644 --- a/thermo/utils/tp_dependent_property.py +++ b/thermo/utils/tp_dependent_property.py @@ -468,7 +468,7 @@ def interpolate_P(self, T, P, name): properties2 = [[self.interpolation_property(p) for p in r] for r in properties] else: properties2 = properties - + # The data table must be sorted now, after transform the data may not be in ascending order Ts2_sorted_indices = np.argsort(Ts2) From feeec4c421607dbca3c5a7c244174f63fe89babb Mon Sep 17 00:00:00 2001 From: Caleb Bell Date: Fri, 26 Jul 2024 13:54:51 -0600 Subject: [PATCH 3/9] RUF010,SIM910,UP031,PLR2044,W291,PLR1714 --- thermo/activity.py | 2 +- thermo/chemical.py | 2 +- thermo/electrochem.py | 1 - thermo/eos.py | 10 +++--- thermo/eos_mix.py | 28 +++++++-------- thermo/eos_volume.py | 3 +- thermo/equilibrium.py | 2 +- thermo/flash/flash_base.py | 4 +-- thermo/flash/flash_pure_vls.py | 4 +-- thermo/flash/flash_utils.py | 3 +- thermo/flash/flash_vl.py | 1 - thermo/nrtl.py | 4 +-- thermo/phases/ceos.py | 2 +- thermo/phases/gibbs_excess.py | 4 +-- thermo/phases/helmholtz_eos.py | 1 - thermo/phases/phase.py | 2 +- thermo/property_package.py | 2 +- thermo/regular_solution.py | 2 +- thermo/serialize.py | 2 +- thermo/stream.py | 2 +- thermo/unifac.py | 18 +++++----- thermo/utils/mixture_property.py | 2 +- thermo/utils/t_dependent_property.py | 51 ++++++++++++++-------------- thermo/volume.py | 2 +- thermo/wilson.py | 2 +- 25 files changed, 73 insertions(+), 83 deletions(-) diff --git a/thermo/activity.py b/thermo/activity.py index e8540df0..396c3b1f 100644 --- a/thermo/activity.py +++ b/thermo/activity.py @@ -328,7 +328,7 @@ def __repr__(self): IdealSolution(T=300.0, xs=[.1, .2, .3, .4]) ''' # Other classes with different parameters should expose them here too - s = f'{self.__class__.__name__}(T={repr(self.T)}, xs={repr(self.xs)})' + s = f'{self.__class__.__name__}(T={self.T!r}, xs={self.xs!r})' return s def __eq__(self, other): diff --git a/thermo/chemical.py b/thermo/chemical.py index c35e64c7..e8a479c7 100644 --- a/thermo/chemical.py +++ b/thermo/chemical.py @@ -99,7 +99,7 @@ CHEMSEP = (298., 101325, 'g', 0, 0, True) # It has an option to add Hf to the reference PRO_II = (298.15, 101325, 'gas', 0, 0, True) HYSYS = (298.15, 101325, 'calc', 'Hf', 0, True) -UNISIM = HYSYS # +UNISIM = HYSYS SUPERPRO = (298.15, 101325, 'calc', 0, 0, True) # No support for entropy found, 0 assumed # note soecifying a phase works for chemicals but not mixtures. diff --git a/thermo/electrochem.py b/thermo/electrochem.py index f5ca1cc3..15184825 100644 --- a/thermo/electrochem.py +++ b/thermo/electrochem.py @@ -597,7 +597,6 @@ def Laliberte_density(T, ws, CASRNs): c4s.append(float(dat[7])) return Laliberte_density_mix(T, ws, c0s, c1s, c2s, c3s, c4s) -# ### Laliberty Heat Capacity Functions diff --git a/thermo/eos.py b/thermo/eos.py index c06662f7..f4cbdb69 100644 --- a/thermo/eos.py +++ b/thermo/eos.py @@ -998,16 +998,16 @@ def __repr__(self): >>> eos PR(Tc=507.6, Pc=3025000.0, omega=0.2975, T=400.0, P=1000000.0) ''' - s = f'{self.__class__.__name__}(Tc={repr(self.Tc)}, Pc={repr(self.Pc)}, omega={repr(self.omega)}, ' + s = f'{self.__class__.__name__}(Tc={self.Tc!r}, Pc={self.Pc!r}, omega={self.omega!r}, ' for k, v in self.kwargs.items(): s += f'{k}={v}, ' if hasattr(self, 'no_T_spec') and self.no_T_spec: - s += f'P={self.P!r}, V={repr(self.V)}' + s += f'P={self.P!r}, V={self.V!r}' elif self.V is not None: - s += f'T={self.T!r}, V={repr(self.V)}' + s += f'T={self.T!r}, V={self.V!r}' else: - s += f'T={self.T!r}, P={repr(self.P)}' + s += f'T={self.T!r}, P={self.P!r}' s += ')' return s @@ -1266,7 +1266,7 @@ def set_from_PT(self, Vs, only_l=False, only_g=False): extra = ', zs is %s' %(self.zs) else: extra = '' - raise ValueError(f'No acceptable roots were found; the roots are {Vs!s}, T is {str(self.T)} K, P is {str(self.P)} Pa, a_alpha is {str([self.a_alpha])}, b is {str([self.b])}{extra}') + raise ValueError(f'No acceptable roots were found; the roots are {Vs!s}, T is {self.T!s} K, P is {self.P!s} Pa, a_alpha is {[self.a_alpha]!s}, b is {[self.b]!s}{extra}') def set_properties_from_solution(self, T, P, V, b, delta, epsilon, a_alpha, diff --git a/thermo/eos_mix.py b/thermo/eos_mix.py index 2c1168b7..6d733c52 100644 --- a/thermo/eos_mix.py +++ b/thermo/eos_mix.py @@ -411,17 +411,17 @@ def atindexes(values): def __repr__(self): - s = f'{self.__class__.__name__}(Tcs={repr(self.Tcs)}, Pcs={repr(self.Pcs)}, omegas={repr(self.omegas)}, ' + s = f'{self.__class__.__name__}(Tcs={self.Tcs!r}, Pcs={self.Pcs!r}, omegas={self.omegas!r}, ' for k, v in self.kwargs.items(): - s += f'{k}={repr(v)}, ' + s += f'{k}={v!r}, ' s += 'zs=%s, ' %(repr(self.zs)) if hasattr(self, 'no_T_spec') and self.no_T_spec: - s += f'P={self.P!r}, V={repr(self.V)}' + s += f'P={self.P!r}, V={self.V!r}' elif self.V is not None: - s += f'T={self.T!r}, V={repr(self.V)}' + s += f'T={self.T!r}, V={self.V!r}' else: - s += f'T={self.T!r}, P={repr(self.P)}' + s += f'T={self.T!r}, P={self.P!r}' s += ')' return s @@ -1726,8 +1726,8 @@ def _err_VL_jacobian(self, lnKsVF, T, P, zs, near_critical=False, xs = [zi/(1.0 + VF*(Ki - 1.0)) for zi, Ki in zip(zs, Ks)] ys = [Ki*xi for Ki, xi in zip(Ks, xs)] - eos_g = self.to_TP_zs_fast(T=T, P=P, zs=ys, only_g=True) # - eos_l = self.to_TP_zs_fast(T=T, P=P, zs=xs, only_l=True) # + eos_g = self.to_TP_zs_fast(T=T, P=P, zs=ys, only_g=True) + eos_l = self.to_TP_zs_fast(T=T, P=P, zs=xs, only_l=True) # eos_g = self.to_TP_zs(T=T, P=P, zs=ys) # eos_l = self.to_TP_zs(T=T, P=P, zs=xs) @@ -1872,9 +1872,9 @@ def _err_VL(self, lnKsVF, T, P, zs, near_critical=False, info=None): err_RR = Rachford_Rice_flash_error(VF, zs, Ks) - eos_g = self.to_TP_zs_fast(T=T, P=P, zs=ys, only_g=True) # + eos_g = self.to_TP_zs_fast(T=T, P=P, zs=ys, only_g=True) eos_g.fugacities() - eos_l = self.to_TP_zs_fast(T=T, P=P, zs=xs, only_l=True) # + eos_l = self.to_TP_zs_fast(T=T, P=P, zs=xs, only_l=True) eos_l.fugacities() if not near_critical: @@ -3060,7 +3060,7 @@ def d3a_alpha_dzizjzks(self): This derivative is checked numerically. ''' N = self.N - return zeros((N, N, N)) if self.vectorized else [[[0.0]*N for _ in range(N)] for _ in range(N)] + return zeros((N, N, N)) if self.vectorized else [[[0.0]*N for _ in range(N)] for _ in range(N)] @property def d3a_alpha_dninjnks(self): @@ -3092,7 +3092,7 @@ def d3a_alpha_dninjnks(self): N = self.N zs = self.zs a_alpha6 = -6.0*a_alpha - matrix = zeros((N, N, N)) if self.vectorized else [[[0.0]*N for _ in range(N)] for _ in range(N)] + matrix = zeros((N, N, N)) if self.vectorized else [[[0.0]*N for _ in range(N)] for _ in range(N)] for i in range(N): l = [] for j in range(N): @@ -7619,7 +7619,7 @@ def d2delta_dzizjs(self): This derivative is checked numerically. ''' N = self.N - return zeros((N, N)) if self.vectorized else [[0.0]*N for i in range(N)] + return zeros((N, N)) if self.vectorized else [[0.0]*N for i in range(N)] @property def d2delta_dninjs(self): @@ -10405,7 +10405,7 @@ def d2delta_dzizjs(self): This derivative is checked numerically. ''' N = self.N - return zeros((N, N)) if self.vectorized else [[0.0]*N for i in range(N)] + return zeros((N, N)) if self.vectorized else [[0.0]*N for i in range(N)] @property def d2delta_dninjs(self): @@ -10426,7 +10426,7 @@ def d2delta_dninjs(self): This derivative is checked numerically. ''' N = self.N - return zeros((N, N)) if self.vectorized else [[0.0]*N for i in range(N)] + return zeros((N, N)) if self.vectorized else [[0.0]*N for i in range(N)] @property def d3delta_dninjnks(self): diff --git a/thermo/eos_volume.py b/thermo/eos_volume.py index f2c235ea..f9b85a6d 100644 --- a/thermo/eos_volume.py +++ b/thermo/eos_volume.py @@ -1086,7 +1086,7 @@ def volume_solutions_fast(T, P, b, delta, epsilon, a_alpha): + 0.5*csqrt((x9*(-4.*x0*t1*t1*t1 + t2*t2))+0.0j) )+0.0j)**third - x20 = -t1/x19# + x20 = -t1/x19 x22 = x5 + x5 x25 = 4.*x0*x20 return ((x0*x20 - x19 + x5)*third, @@ -1247,7 +1247,6 @@ def volume_solutions_a2(T, P, b, delta, epsilon, a_alpha): :scale: 70 % :alt: SRK EOS decane volume error high pressure ''' - # RT_inv = R_inv/T P_RT_inv = P*RT_inv B = etas = b*P_RT_inv diff --git a/thermo/equilibrium.py b/thermo/equilibrium.py index 1129359b..c9979fc7 100644 --- a/thermo/equilibrium.py +++ b/thermo/equilibrium.py @@ -223,7 +223,7 @@ class EquilibriumState: 'liquid0', 'liquid1', 'liquid2', 'bulk', 'flash_specs', 'flash_convergence', 'flasher', 'settings', 'constants', 'correlations', '__dict__') - obj_references = ('liquid_bulk', 'solid_bulk', 'bulk', 'gas', 'liquids', 'phases', + obj_references = ('liquid_bulk', 'solid_bulk', 'bulk', 'gas', 'liquids', 'phases', 'solids', 'settings', 'constants', 'correlations', 'flasher', 'liquid0', 'liquid1', 'liquid2') diff --git a/thermo/flash/flash_base.py b/thermo/flash/flash_base.py index 90688cc2..cbda9595 100644 --- a/thermo/flash/flash_base.py +++ b/thermo/flash/flash_base.py @@ -422,7 +422,6 @@ def flash(self, zs=None, T=None, P=None, VF=None, SF=None, V=None, H=None, else: g, liquids = None, [other_phase] flash_convergence = {'iterations': iterations, 'err': err} -# return dest(T, Psub, zs, gas=g, liquids=liquids, solids=[s], betas=[1-SF, SF], flash_specs=flash_specs, flash_convergence=flash_convergence, @@ -435,7 +434,6 @@ def flash(self, zs=None, T=None, P=None, VF=None, SF=None, V=None, H=None, else: g, liquids = None, [other_phase] flash_convergence = {'iterations': iterations, 'err': err} -# return dest(Tsub, P, zs, gas=g, liquids=liquids, solids=[s], betas=[1-SF, SF], flash_specs=flash_specs, flash_convergence=flash_convergence, @@ -1183,7 +1181,7 @@ def grid_props(self, spec0='T', spec1='P', prop='H', norm = None else: norm = LogNorm() - im = ax.pcolormesh(X, Y, z, cmap=color_map, norm=norm) # + im = ax.pcolormesh(X, Y, z, cmap=color_map, norm=norm) cbar = fig.colorbar(im, ax=ax) cbar.set_label(prop) diff --git a/thermo/flash/flash_pure_vls.py b/thermo/flash/flash_pure_vls.py index 92a91b41..c4964926 100644 --- a/thermo/flash/flash_pure_vls.py +++ b/thermo/flash/flash_pure_vls.py @@ -471,7 +471,6 @@ def Psat_guess(self, T): if self.VL_only_CEOSs_same: # Two phase pure eoss are two phase up to the critical point only! Then one phase Psat = self.eos_pure_STP.Psat(T) - # else: try: Psat = self.correlations.VaporPressures[0](T) @@ -1150,7 +1149,7 @@ def flash_VF_HSGUA(self, fixed_var_val, spec_val, fixed_var='VF', spec_var='H', dPsat_dT = (dfg_T - dfl_T)/(dfl_P - dfg_P) except ZeroDivisionError: at_critical = True - dPsat_dT = self.constants.Pcs[0] # + dPsat_dT = self.constants.Pcs[0] dv_g = dPsat_dT*gas_props[dspec_dP_idx][i] + gas_props[dspec_dT_idx][i] dv_l = dPsat_dT*liq_props[dspec_dP_idx][i] + liq_props[dspec_dT_idx][i] @@ -1317,7 +1316,6 @@ def to_solve(T): return err, dv - # try: T_calc = newton(to_solve, guess, fprime=True, low=low, high=high, xtol=1e-12, require_eval=True) except: diff --git a/thermo/flash/flash_utils.py b/thermo/flash/flash_utils.py index 811c21b3..f3366c08 100644 --- a/thermo/flash/flash_utils.py +++ b/thermo/flash/flash_utils.py @@ -1686,7 +1686,7 @@ def jac(lnKsP): # ys = [exp(lnKsP[i])*xs[i] for i in cmps] return lnKsP[-1], xs, zs, iterations -def dew_bubble_bounded_naive(guess, fixed_val, zs, flasher, iter_var='T', fixed_var='P', V_over_F=1, # +def dew_bubble_bounded_naive(guess, fixed_val, zs, flasher, iter_var='T', fixed_var='P', V_over_F=1, maxiter=200, xtol=1E-10, ytol=None, hot_start=None ): # Bound the problem @@ -4133,7 +4133,6 @@ def to_solve(states): # print(kwargs, errs) return errs, jac -# states, iterations = newton_system(to_solve, x0=guesses, jac=True, xtol=xtol, ytol=ytol, maxiter=maxiter, damping_func=damping_maintain_sign) phase = cache[0] diff --git a/thermo/flash/flash_vl.py b/thermo/flash/flash_vl.py index a719ce1c..0df14aa8 100644 --- a/thermo/flash/flash_vl.py +++ b/thermo/flash/flash_vl.py @@ -349,7 +349,6 @@ def _finish_initialization(self): if liquid is None: raise ValueError("Liquid model is required") - # self.phases = [gas, liquid] self._finish_initialization_base() diff --git a/thermo/nrtl.py b/thermo/nrtl.py index 35fde68b..35e288ff 100644 --- a/thermo/nrtl.py +++ b/thermo/nrtl.py @@ -569,7 +569,7 @@ class NRTL(GibbsExcess): stored_attributes = _model_attributes + ('alpha_temperature_independent', 'tau_coeffs_nonzero','zero_coeffs') _cached_calculated_attributes = ('_alphas', '_dGs_dT', '_xj_dGs_dT_jis', '_xj_Gs_dtaus_dT_jis', '_d2Gs_dT2', '_xj_taus_dGs_dT_jis', '_dtaus_dT', '_Gs', '_d2taus_dT2', - '_taus', '_xj_Gs_jis_inv', '_xj_Gs_taus_jis', '_xj_Gs_jis', + '_taus', '_xj_Gs_jis_inv', '_xj_Gs_taus_jis', '_xj_Gs_jis', '_d3taus_dT3', '_d3Gs_dT3', '_Gs_transposed', '_Gs_taus_transposed', '_Gs_taus') __slots__ = GibbsExcess.__slots__ + stored_attributes + _cached_calculated_attributes recalculable_attributes = _cached_calculated_attributes + GibbsExcess.recalculable_attributes @@ -734,7 +734,7 @@ def __init__(self, T, xs, tau_coeffs=None, alpha_coeffs=None, def __repr__(self): - s = f'{self.__class__.__name__}(T={repr(self.T)}, xs={repr(self.xs)}' + s = f'{self.__class__.__name__}(T={self.T!r}, xs={self.xs!r}' for i, attr in enumerate(self._model_attributes[:6]): if self.tau_coeffs_nonzero[i]: s += f', {attr}={getattr(self, attr)}' diff --git a/thermo/phases/ceos.py b/thermo/phases/ceos.py index 5304e062..32e972a4 100644 --- a/thermo/phases/ceos.py +++ b/thermo/phases/ceos.py @@ -155,7 +155,7 @@ def __init__(self, eos_class, eos_kwargs, HeatCapacityGases=None, Hfs=None, self.composition_independent = eos_class is IGMIX if T is None: T = 298.15 if P is None: P = 101325.0 - if zs is None: + if zs is None: if vectorized: v = 1.0 / N zs = full(N, v) diff --git a/thermo/phases/gibbs_excess.py b/thermo/phases/gibbs_excess.py index d72bfce2..1504c54e 100644 --- a/thermo/phases/gibbs_excess.py +++ b/thermo/phases/gibbs_excess.py @@ -2242,7 +2242,7 @@ def to_int(P): H = 0.0 for i in range(self.N): - H += zs[i]*(Cpl_integrals_pure[i] - Hvaps_T_ref[i]) # + H += zs[i]*(Cpl_integrals_pure[i] - Hvaps_T_ref[i]) # If we can use the liquid heat capacity and prove its consistency # This bit is the differential with respect to pressure @@ -2521,7 +2521,7 @@ def to_int2(P): for i in cmps: Sg298_to_T = Cpig_integrals_over_T_pure[i] Svap = -Hvaps[i]*T_inv # Do the transition at the temperature of the liquid - S += zs[i]*(Sg298_to_T + Svap - R*log(P*P_REF_IG_INV)) # + S += zs[i]*(Sg298_to_T + Svap - R*log(P*P_REF_IG_INV)) # self._S = S = S + self.GibbsExcessModel.SE() return S diff --git a/thermo/phases/helmholtz_eos.py b/thermo/phases/helmholtz_eos.py index 4c4af515..0921c3eb 100644 --- a/thermo/phases/helmholtz_eos.py +++ b/thermo/phases/helmholtz_eos.py @@ -172,7 +172,6 @@ def dlnphis_dV_T(self): x2 = rho*(d2A_ddelta2*x0 + rho_red*rho_inv*rho_inv) x3 = dA_ddelta + x1 dlnphi_dV_T = x0*(2.0*dA_ddelta + x1 + x2 - (x2 + x3)/(rho*x0*x3 + 1.0) - 1.0/delta) -# dlnphi_dV_T *= -1.0/(self._V*self._V) return [dlnphi_dV_T] diff --git a/thermo/phases/phase.py b/thermo/phases/phase.py index 19cbb60d..6b949fa3 100644 --- a/thermo/phases/phase.py +++ b/thermo/phases/phase.py @@ -1316,7 +1316,7 @@ def dfugacities_dns(self): phis = self.phis() dlnphis_dns = self.dlnphis_dns() P, zs, N = self.P, self.zs, self.N - matrix = zeros((N, N)) if self.vectorized else [[0.0]*N for _ in range(N)] + matrix = zeros((N, N)) if self.vectorized else [[0.0]*N for _ in range(N)] for i in range(N): phi_P = P*phis[i] ziPphi = phi_P*zs[i] diff --git a/thermo/property_package.py b/thermo/property_package.py index 5d0d65cd..8a80508e 100644 --- a/thermo/property_package.py +++ b/thermo/property_package.py @@ -341,7 +341,7 @@ def pure_guesses(self, zero_fraction=1E-6): for k in cmps] return pure_guesses - def Wilson_guesses(self, T, P, zs, powers=(1, -1, 1/3., -1/3.)): # + def Wilson_guesses(self, T, P, zs, powers=(1, -1, 1/3., -1/3.)): # First K is vapor-like phase; second, liquid like cmps = range(self.N) Ks_Wilson = [Wilson_K_value(T=T, P=P, Tc=self.Tcs[i], Pc=self.Pcs[i], omega=self.omegas[i]) for i in cmps] diff --git a/thermo/regular_solution.py b/thermo/regular_solution.py index d4d7e5f7..1bfc45a2 100644 --- a/thermo/regular_solution.py +++ b/thermo/regular_solution.py @@ -377,7 +377,7 @@ def __init__(self, T, xs, Vs, SPs, lambda_coeffs=None): def __repr__(self): - s = f'{self.__class__.__name__}(T={repr(self.T)}, xs={repr(self.xs)}, Vs={self.Vs}, SPs={self.SPs}' + s = f'{self.__class__.__name__}(T={self.T!r}, xs={self.xs!r}, Vs={self.Vs}, SPs={self.SPs}' if not self._lambda_coeffs_zero: s += f' , lambda_coeffs={self.lambda_coeffs})' else: diff --git a/thermo/serialize.py b/thermo/serialize.py index b9c6928a..42f09ab7 100644 --- a/thermo/serialize.py +++ b/thermo/serialize.py @@ -307,7 +307,7 @@ def as_json(self, cache=None, option=0): else: num = len(id_to_num_str) # May change as we do as_json so we must re-check the length num_str = f'pyid_{num}' - id_to_num_str[id(o)] = num_str + id_to_num_str[id(o)] = num_str num_to_object[num_str] = o.as_json(cache) d[obj_name] = num_str diff --git a/thermo/stream.py b/thermo/stream.py index 92c30df4..099eaf91 100644 --- a/thermo/stream.py +++ b/thermo/stream.py @@ -1281,7 +1281,7 @@ def __repr__(self): s = f'{self.__class__.__name__}(flasher={self.flasher is not None}, ' for k, v in self.specifications.items(): if v is not None: - s += f'{k}={repr(v)}, ' + s += f'{k}={v!r}, ' s = s[:-2] s += ')' return s diff --git a/thermo/unifac.py b/thermo/unifac.py index 9be43e80..58729516 100644 --- a/thermo/unifac.py +++ b/thermo/unifac.py @@ -4402,15 +4402,15 @@ class UNIFAC(GibbsExcess): gammas_from_args = staticmethod(unifac_gammas_from_args) - _cached_calculated_attributes = ('_Fis', '_Fs', '_Fs_pure', '_Gs', '_Gs_pure', '_Hs', '_Hs_pure', '_Theta_Psi_sum_invs', '_Theta_Psi_sums', - '_Theta_pure_Psi_sum_invs', '_Theta_pure_Psi_sums', '_Thetas', '_Thetas_sum_inv', '_VSXS', '_Vis', '_Vis_modified', '_Ws', - '_Xs', '_Xs_sum_inv', '_d2Fis_dxixjs', '_d2Thetas_dxixjs', '_d2Vis_dxixjs', '_d2Vis_modified_dxixjs', - '_d2lnGammas_subgroups_dT2', '_d2lnGammas_subgroups_dTdxs', '_d2lnGammas_subgroups_dxixjs', '_d2lnGammas_subgroups_pure_dT2', - '_d2lngammas_c_dxixjs', '_d2lngammas_r_dT2', '_d2lngammas_r_dTdxs', '_d2lngammas_r_dxixjs', '_d2psis_dT2', '_d3Fis_dxixjxks', - '_d3GE_dT3', '_d3Vis_dxixjxks', '_d3Vis_modified_dxixjxks', '_d3lnGammas_subgroups_dT3', '_d3lnGammas_subgroups_pure_dT3', - '_d3lngammas_c_dxixjxks', '_d3lngammas_r_dT3', '_d3psis_dT3', '_dFis_dxs', '_dThetas_dxs', '_dVis_dxs', '_dVis_modified_dxs', - '_dgammas_dxs', '_dlnGammas_subgroups_dT', '_dlnGammas_subgroups_dxs', '_dlnGammas_subgroups_pure_dT', '_dlngammas_c_dxs', - '_dlngammas_r_dT', '_dlngammas_r_dxs', '_dpsis_dT', '_lnGammas_subgroups', '_lnGammas_subgroups_pure', '_lngammas_c', + _cached_calculated_attributes = ('_Fis', '_Fs', '_Fs_pure', '_Gs', '_Gs_pure', '_Hs', '_Hs_pure', '_Theta_Psi_sum_invs', '_Theta_Psi_sums', + '_Theta_pure_Psi_sum_invs', '_Theta_pure_Psi_sums', '_Thetas', '_Thetas_sum_inv', '_VSXS', '_Vis', '_Vis_modified', '_Ws', + '_Xs', '_Xs_sum_inv', '_d2Fis_dxixjs', '_d2Thetas_dxixjs', '_d2Vis_dxixjs', '_d2Vis_modified_dxixjs', + '_d2lnGammas_subgroups_dT2', '_d2lnGammas_subgroups_dTdxs', '_d2lnGammas_subgroups_dxixjs', '_d2lnGammas_subgroups_pure_dT2', + '_d2lngammas_c_dxixjs', '_d2lngammas_r_dT2', '_d2lngammas_r_dTdxs', '_d2lngammas_r_dxixjs', '_d2psis_dT2', '_d3Fis_dxixjxks', + '_d3GE_dT3', '_d3Vis_dxixjxks', '_d3Vis_modified_dxixjxks', '_d3lnGammas_subgroups_dT3', '_d3lnGammas_subgroups_pure_dT3', + '_d3lngammas_c_dxixjxks', '_d3lngammas_r_dT3', '_d3psis_dT3', '_dFis_dxs', '_dThetas_dxs', '_dVis_dxs', '_dVis_modified_dxs', + '_dgammas_dxs', '_dlnGammas_subgroups_dT', '_dlnGammas_subgroups_dxs', '_dlnGammas_subgroups_pure_dT', '_dlngammas_c_dxs', + '_dlngammas_r_dT', '_dlngammas_r_dxs', '_dpsis_dT', '_lnGammas_subgroups', '_lnGammas_subgroups_pure', '_lngammas_c', '_lngammas_r', '_psis', '_qx_sum_inv', '_rx_sum_inv') __slots__ = GibbsExcess.__slots__ + _cached_calculated_attributes + ('N_groups', 'Qs', 'cmp_group_idx', 'cmp_v_count', 'cmp_v_count_inv', 'group_cmp_idx', diff --git a/thermo/utils/mixture_property.py b/thermo/utils/mixture_property.py index f839bf14..c27369d1 100644 --- a/thermo/utils/mixture_property.py +++ b/thermo/utils/mixture_property.py @@ -53,7 +53,7 @@ class MixtureProperty: pure_references = () pure_reference_types = () - obj_references = () + obj_references = () json_version = 1 non_json_attributes = ['TP_zs_ws_cached', 'prop_cached'] vectorized = False diff --git a/thermo/utils/t_dependent_property.py b/thermo/utils/t_dependent_property.py index ead3a42c..245b4eba 100644 --- a/thermo/utils/t_dependent_property.py +++ b/thermo/utils/t_dependent_property.py @@ -1157,10 +1157,10 @@ def __init_subclass__(cls): {'A': 2.1e-5, 'B': 1.29, 'C': 488.0, 'D': 0.0}, # near dippr kg 1-heptene {'A': 4.5e-5, 'B': 1.2, 'C': 420.0, 'D': 0.0}, # near dippr kg propene {'A': 1.7e-6, 'B': 1.67, 'C': 660.0, 'D': -95400.0}, # near dippr kg acetic acid - {'A': 0.0, 'B': 4000.0, 'C': 0.75, 'D': 0.0}, # - {'A': 1e9, 'B': -5.0, 'C': -1500, 'D': 1e6}, # - {'A': 0.0, 'B': 3600.0, 'C': 0.73, 'D': 0.0}, # - {'A': 0.0076, 'B': 0.51, 'C': 2175, 'D': 185000.0}, # + {'A': 0.0, 'B': 4000.0, 'C': 0.75, 'D': 0.0}, + {'A': 1e9, 'B': -5.0, 'C': -1500, 'D': 1e6}, + {'A': 0.0, 'B': 3600.0, 'C': 0.73, 'D': 0.0}, + {'A': 0.0076, 'B': 0.51, 'C': 2175, 'D': 185000.0}, ]}), 'DIPPR104': (['A', 'B'], ['C', 'D', 'E'], @@ -1225,13 +1225,13 @@ def __init_subclass__(cls): {'A': 0.67524, 'B': 0.24431, 'C': 645.61,'D': 0.26239}, # near some chemsep liquid densities {'A': 0.5251, 'B': 0.20924, 'C': 736.61,'D': 0.18363}, # near some chemsep liquid densities - {'A': 0.13, 'B': 0.23, 'C': 910.,'D': 0.29}, # - {'A': 9.0, 'B': 0.5, 'C': 2400.,'D': 0.58}, # - {'A': 1.0, 'B': 0.14, 'C': 1000.0,'D': 0.1}, # - {'A': 0.24, 'B': 0.05, 'C': 6000.0,'D': 0.2}, # - {'A': 6.5, 'B': 0.5, 'C': 3.5, 'D': 0.2}, # - {'A': 15.0, 'B': 0.3, 'C': 7000.0, 'D': 0.3}, # - {'A': 0.1, 'B': 0.05, 'C': 3300.0, 'D': 0.1}, # + {'A': 0.13, 'B': 0.23, 'C': 910.,'D': 0.29}, + {'A': 9.0, 'B': 0.5, 'C': 2400.,'D': 0.58}, + {'A': 1.0, 'B': 0.14, 'C': 1000.0,'D': 0.1}, + {'A': 0.24, 'B': 0.05, 'C': 6000.0,'D': 0.2}, + {'A': 6.5, 'B': 0.5, 'C': 3.5, 'D': 0.2}, + {'A': 15.0, 'B': 0.3, 'C': 7000.0, 'D': 0.3}, + {'A': 0.1, 'B': 0.05, 'C': 3300.0, 'D': 0.1}, ]}), 'DIPPR105_inv': (['A', 'B', 'C', 'D'], [], @@ -1263,7 +1263,7 @@ def __init_subclass__(cls): 'DIPPR106_inv': (['Tc', 'A', 'B'], ['C', 'D', 'E'], {'f': lambda T, **kwargs: 1.0/EQ106(T, order=0, **kwargs),}, - {'fit_params': ['A', 'B', 'C', 'D', 'E'], + {'fit_params': ['A', 'B', 'C', 'D', 'E'], }), 'YawsSigma': (['Tc', 'A', 'B'], ['C', 'D', 'E'], @@ -1299,7 +1299,6 @@ def __init_subclass__(cls): {'A': 820000.0, 'B': 375000, 'C': 1750.0, 'D': -1e6, 'E': 275.}, {'A': 150000.0, 'B': 145000, 'C': 1225.0, 'D': -5.75e7, 'E': 7.75}, ]}), - # 'DIPPR114': (['Tc', 'A', 'B', 'C', 'D'], [], {'f': EQ114, @@ -2103,7 +2102,7 @@ def fit_data_to_model(cls, Ts, data, model, model_kwargs=None, do_K_fold = False - model_skipped_parameter_combinations = skipped_parameter_combinations.get(model, None) + model_skipped_parameter_combinations = skipped_parameter_combinations.get(model) for i in range(start_idx, len(optional_args)+1): our_fit_parameters = optional_args[0:i] @@ -2691,29 +2690,29 @@ def as_poly_fit(self): raise ValueError("No polynomial fit defined") if method == POLY_FIT: - return f'{self.__class__.__name__}(load_data=False, poly_fit=({repr(self.poly_fit_Tmin)}, {repr(self.poly_fit_Tmax)}, {repr(self.poly_fit_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, poly_fit=({self.poly_fit_Tmin!r}, {self.poly_fit_Tmax!r}, {self.poly_fit_coeffs!r}))' elif method == EXP_POLY_FIT: - return f'{self.__class__.__name__}(load_data=False, exp_poly_fit=({repr(self.exp_poly_fit_Tmin)}, {repr(self.exp_poly_fit_Tmax)}, {repr(self.exp_poly_fit_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, exp_poly_fit=({self.exp_poly_fit_Tmin!r}, {self.exp_poly_fit_Tmax!r}, {self.exp_poly_fit_coeffs!r}))' elif method == POLY_FIT_LN_TAU: - return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.poly_fit_ln_tau_Tc)}, poly_fit_ln_tau=({repr(self.poly_fit_ln_tau_Tmin)}, {repr(self.poly_fit_ln_tau_Tmax)}, {repr(self.poly_fit_ln_tau_Tc)}, {repr(self.poly_fit_ln_tau_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, Tc={self.poly_fit_ln_tau_Tc!r}, poly_fit_ln_tau=({self.poly_fit_ln_tau_Tmin!r}, {self.poly_fit_ln_tau_Tmax!r}, {self.poly_fit_ln_tau_Tc!r}, {self.poly_fit_ln_tau_coeffs!r}))' elif method == EXP_POLY_FIT_LN_TAU: - return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.exp_poly_fit_ln_tau_Tc)}, exp_poly_fit_ln_tau=({repr(self.exp_poly_fit_ln_tau_Tmin)}, {repr(self.exp_poly_fit_ln_tau_Tmax)}, {repr(self.exp_poly_fit_ln_tau_Tc)}, {repr(self.exp_poly_fit_ln_tau_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, Tc={self.exp_poly_fit_ln_tau_Tc!r}, exp_poly_fit_ln_tau=({self.exp_poly_fit_ln_tau_Tmin!r}, {self.exp_poly_fit_ln_tau_Tmax!r}, {self.exp_poly_fit_ln_tau_Tc!r}, {self.exp_poly_fit_ln_tau_coeffs!r}))' elif method == STABLEPOLY_FIT: - return f'{self.__class__.__name__}(load_data=False, stablepoly_fit=({repr(self.stablepoly_fit_Tmin)}, {repr(self.stablepoly_fit_Tmax)}, {repr(self.stablepoly_fit_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, stablepoly_fit=({self.stablepoly_fit_Tmin!r}, {self.stablepoly_fit_Tmax!r}, {self.stablepoly_fit_coeffs!r}))' elif method == EXP_STABLEPOLY_FIT: - return f'{self.__class__.__name__}(load_data=False, exp_stablepoly_fit=({repr(self.exp_stablepoly_fit_Tmin)}, {repr(self.exp_stablepoly_fit_Tmax)}, {repr(self.exp_stablepoly_fit_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, exp_stablepoly_fit=({self.exp_stablepoly_fit_Tmin!r}, {self.exp_stablepoly_fit_Tmax!r}, {self.exp_stablepoly_fit_coeffs!r}))' elif method == STABLEPOLY_FIT_LN_TAU: - return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.stablepoly_fit_ln_tau_Tc)}, stablepoly_fit_ln_tau=({repr(self.stablepoly_fit_ln_tau_Tmin)}, {repr(self.stablepoly_fit_ln_tau_Tmax)}, {repr(self.stablepoly_fit_ln_tau_Tc)}, {repr(self.stablepoly_fit_ln_tau_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, Tc={self.stablepoly_fit_ln_tau_Tc!r}, stablepoly_fit_ln_tau=({self.stablepoly_fit_ln_tau_Tmin!r}, {self.stablepoly_fit_ln_tau_Tmax!r}, {self.stablepoly_fit_ln_tau_Tc!r}, {self.stablepoly_fit_ln_tau_coeffs!r}))' elif method == EXP_STABLEPOLY_FIT_LN_TAU: - return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.exp_stablepoly_fit_ln_tau_Tc)}, exp_stablepoly_fit_ln_tau=({repr(self.exp_stablepoly_fit_ln_tau_Tmin)}, {repr(self.exp_stablepoly_fit_ln_tau_Tmax)}, {repr(self.exp_stablepoly_fit_ln_tau_Tc)}, {repr(self.exp_stablepoly_fit_ln_tau_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, Tc={self.exp_stablepoly_fit_ln_tau_Tc!r}, exp_stablepoly_fit_ln_tau=({self.exp_stablepoly_fit_ln_tau_Tmin!r}, {self.exp_stablepoly_fit_ln_tau_Tmax!r}, {self.exp_stablepoly_fit_ln_tau_Tc!r}, {self.exp_stablepoly_fit_ln_tau_coeffs!r}))' elif method == CHEB_FIT: - return f'{self.__class__.__name__}(load_data=False, cheb_fit=({repr(self.cheb_fit_Tmin)}, {repr(self.cheb_fit_Tmax)}, {repr(self.cheb_fit_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, cheb_fit=({self.cheb_fit_Tmin!r}, {self.cheb_fit_Tmax!r}, {self.cheb_fit_coeffs!r}))' elif method == EXP_CHEB_FIT: - return f'{self.__class__.__name__}(load_data=False, exp_cheb_fit=({repr(self.exp_cheb_fit_Tmin)}, {repr(self.exp_cheb_fit_Tmax)}, {repr(self.exp_cheb_fit_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, exp_cheb_fit=({self.exp_cheb_fit_Tmin!r}, {self.exp_cheb_fit_Tmax!r}, {self.exp_cheb_fit_coeffs!r}))' elif method == CHEB_FIT_LN_TAU: - return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.cheb_fit_ln_tau_Tc)}, cheb_fit_ln_tau=({repr(self.cheb_fit_ln_tau_Tmin)}, {repr(self.cheb_fit_ln_tau_Tmax)}, {repr(self.cheb_fit_ln_tau_Tc)}, {repr(self.cheb_fit_ln_tau_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, Tc={self.cheb_fit_ln_tau_Tc!r}, cheb_fit_ln_tau=({self.cheb_fit_ln_tau_Tmin!r}, {self.cheb_fit_ln_tau_Tmax!r}, {self.cheb_fit_ln_tau_Tc!r}, {self.cheb_fit_ln_tau_coeffs!r}))' elif method == EXP_CHEB_FIT_LN_TAU: - return f'{self.__class__.__name__}(load_data=False, Tc={repr(self.exp_cheb_fit_ln_tau_Tc)}, exp_cheb_fit_ln_tau=({repr(self.exp_cheb_fit_ln_tau_Tmin)}, {repr(self.exp_cheb_fit_ln_tau_Tmax)}, {repr(self.exp_cheb_fit_ln_tau_Tc)}, {repr(self.exp_cheb_fit_ln_tau_coeffs)}))' + return f'{self.__class__.__name__}(load_data=False, Tc={self.exp_cheb_fit_ln_tau_Tc!r}, exp_cheb_fit_ln_tau=({self.exp_cheb_fit_ln_tau_Tmin!r}, {self.exp_cheb_fit_ln_tau_Tmax!r}, {self.exp_cheb_fit_ln_tau_Tc!r}, {self.exp_cheb_fit_ln_tau_coeffs!r}))' def _base_calculate(self, T, method): if method in self.correlations: diff --git a/thermo/volume.py b/thermo/volume.py index c34fdf2d..a49a05d3 100644 --- a/thermo/volume.py +++ b/thermo/volume.py @@ -1783,7 +1783,7 @@ class VolumeSolid(TDependentProperty): """Maximum value of Heat capacity; arbitrarily set to 0.002, as the largest in the data is 0.00136.""" - ranked_methods = [CRC_INORG_S, GOODMAN] # + ranked_methods = [CRC_INORG_S, GOODMAN] """Default rankings of the available methods.""" custom_args = ('MW', 'Tt', 'Vml_Tt') diff --git a/thermo/wilson.py b/thermo/wilson.py index 915ac004..762cb99b 100644 --- a/thermo/wilson.py +++ b/thermo/wilson.py @@ -845,7 +845,7 @@ def __init__(self, T, xs, lambda_coeffs=None, ABCDEF=None, lambda_as=None, lambd def __repr__(self): - s = f'{self.__class__.__name__}(T={repr(self.T)}, xs={repr(self.xs)}' + s = f'{self.__class__.__name__}(T={self.T!r}, xs={self.xs!r}' for i, attr in enumerate(self._model_attributes): if self.lambda_coeffs_nonzero[i]: s += f', {attr}={getattr(self, attr)}' From 34d28c3ac36abd845bebff9245c4260dd0ea3e9d Mon Sep 17 00:00:00 2001 From: Caleb Bell Date: Fri, 26 Jul 2024 14:06:34 -0600 Subject: [PATCH 4/9] Ruff UP031,PLR1714,E713,SIM401,C405,PLW0604,PLR1714,D411,W291,D204 --- thermo/chemical.py | 18 ++++---- thermo/chemical_package.py | 2 +- thermo/chemical_utils.py | 4 +- thermo/coolprop.py | 6 +-- thermo/datasheet.py | 8 ++-- thermo/electrochem.py | 10 ++--- thermo/eos.py | 32 +++++++------- thermo/eos_mix.py | 2 +- thermo/equilibrium.py | 48 ++++++++++----------- thermo/flash/flash_base.py | 22 +++++----- thermo/flash/flash_pure_vls.py | 16 +++---- thermo/flash/flash_utils.py | 8 ++-- thermo/nrtl.py | 4 +- thermo/phases/helmholtz_eos.py | 2 +- thermo/phases/phase.py | 4 +- thermo/phases/phase_utils.py | 8 ++-- thermo/serialize.py | 2 +- thermo/stream.py | 61 ++++++++++++++------------- thermo/test_utils.py | 2 +- thermo/thermal_conductivity.py | 2 + thermo/unifac.py | 14 +++--- thermo/units.py | 6 +-- thermo/utils/mixture_property.py | 18 ++++---- thermo/utils/t_dependent_property.py | 46 ++++++++++---------- thermo/utils/tp_dependent_property.py | 2 +- 25 files changed, 176 insertions(+), 171 deletions(-) diff --git a/thermo/chemical.py b/thermo/chemical.py index e8a479c7..8acf9346 100644 --- a/thermo/chemical.py +++ b/thermo/chemical.py @@ -755,11 +755,11 @@ def __init__(self, ID, T=298.15, P=101325, autocalc=True): self.formula = ID['formula'] # DO NOT REMOVE molecular_weight until the database gets updated with consistent MWs self.MW = ID['MW'] if 'MW' in ID else molecular_weight(simple_formula_parser(self.formula)) - self.PubChem = ID['PubChem'] if 'PubChem' in ID else None - self.smiles = ID['smiles'] if 'smiles' in ID else None - self.InChI = ID['InChI'] if 'InChI' in ID else None - self.InChI_Key = ID['InChI_Key'] if 'InChI_Key' in ID else None - self.synonyms = ID['synonyms'] if 'synonyms' in ID else None + self.PubChem = ID.get('PubChem', None) + self.smiles = ID.get('smiles', None) + self.InChI = ID.get('InChI', None) + self.InChI_Key = ID.get('InChI_Key', None) + self.synonyms = ID.get('synonyms', None) else: self.ID = ID # Identification @@ -3249,15 +3249,15 @@ def Peclet_heat(self, V=None, D=None): # Add the functional groups def _make_getter_group(name): def get(self): - base_name = 'is_%s' %(name) + base_name = 'is_{}'.format(name) ref = getattr(functional_groups, base_name) return ref(self.rdkitmol) return get for _name in group_names: getter = property(_make_getter_group(_name)) - name = 'is_%s' %(_name) - _add_attrs_doc = r"""Method to return whether or not this chemical is in the category %s, [-] - """ %(_name) + name = 'is_{}'.format(_name) + _add_attrs_doc = r"""Method to return whether or not this chemical is in the category {}, [-] + """.format(_name) getter.__doc__ = _add_attrs_doc setattr(Chemical, name, getter) diff --git a/thermo/chemical_package.py b/thermo/chemical_package.py index 50ab193a..edcf52c2 100644 --- a/thermo/chemical_package.py +++ b/thermo/chemical_package.py @@ -1868,7 +1868,7 @@ def as_poly_fit(self, props=None): else: iter_props = self.pure_correlations - s = '%s(' %(self.__class__.__name__) + s = '{}('.format(self.__class__.__name__) s += 'constants=constants, skip_missing=True,\n' for prop in iter_props: prop_attr = getattr(self, prop) diff --git a/thermo/chemical_utils.py b/thermo/chemical_utils.py index 5231ccf3..857d8827 100644 --- a/thermo/chemical_utils.py +++ b/thermo/chemical_utils.py @@ -287,8 +287,8 @@ def _standard_state_ideal_gas_formation_direct(T, Hf_ref, Sf_ref, atoms, gas_Cp, S_calc = reactant_coeff*Sf_ref + reactant_coeff*dS_compound # if the compound is an element it will need special handling to go from solid liquid to gas if needed - solid_ele = set(['C']) - liquid_ele = set(['']) + solid_ele = {'C'} + liquid_ele = {''} for coeff, ele_data in zip(elemental_counts, elemental_composition): ele = list(ele_data.keys())[0] diff --git a/thermo/coolprop.py b/thermo/coolprop.py index 4802dde8..ef48bac1 100644 --- a/thermo/coolprop.py +++ b/thermo/coolprop.py @@ -230,7 +230,7 @@ def store_coolprop_fluids(): data = {CASRN: coolprop_fluids[CASRN].as_json() for CASRN in coolprop_dict} ver = CoolProp.__version__ - file = open(os.path.join(data_dir, 'CoolPropFluids%s.json' %ver), 'w') + file = open(os.path.join(data_dir, 'CoolPropFluids{}.json'.format(ver)), 'w') json.dump(data, file) file.close() @@ -240,7 +240,7 @@ def load_coolprop_fluids(depth=0): import CoolProp ver = CoolProp.__version__ - pth = os.path.join(data_dir, 'CoolPropFluids%s.json' %ver) + pth = os.path.join(data_dir, 'CoolPropFluids{}.json'.format(ver)) try: file = open(pth) except: @@ -418,7 +418,7 @@ def CoolProp_json_alpha0_to_kwargs(json_data, as_np=False): # Not relevant continue else: - raise ValueError("Unrecognized alpha0 type %s" %(d['type'])) + raise ValueError("Unrecognized alpha0 type {}".format(d['type'])) if as_np: for k, v in kwargs.items(): diff --git a/thermo/datasheet.py b/thermo/datasheet.py index 13e4c476..9ad73478 100644 --- a/thermo/datasheet.py +++ b/thermo/datasheet.py @@ -288,25 +288,25 @@ def tabulate_streams(names=None, *args, **kwargs): if kwargs.get('Mole flows', True): for i, CAS in enumerate(CASs): - s = 'Mole flow, mol/s %s' %IDs[CAS] + s = 'Mole flow, mol/s {}'.format(IDs[CAS]) vals = [j[i] for j in mole_flows] dat[s] = vals if kwargs.get('Mass flows', True): for i, CAS in enumerate(CASs): - s = 'Mass flow, kg/s %s' %IDs[CAS] + s = 'Mass flow, kg/s {}'.format(IDs[CAS]) vals = [j[i] for j in mass_flows] dat[s] = vals if kwargs.get('Mass fractions', True): for i, CAS in enumerate(CASs): - s = 'Mass fraction %s' %IDs[CAS] + s = 'Mass fraction {}'.format(IDs[CAS]) vals = [j[i] for j in mass_fractions] dat[s] = vals if kwargs.get('Mole fractions', True): for i, CAS in enumerate(CASs): - s = 'Mole fraction %s' %IDs[CAS] + s = 'Mole fraction {}'.format(IDs[CAS]) vals = [j[i] for j in mole_fractions] dat[s] = vals diff --git a/thermo/electrochem.py b/thermo/electrochem.py index 15184825..72f1df14 100644 --- a/thermo/electrochem.py +++ b/thermo/electrochem.py @@ -1487,9 +1487,9 @@ def ion_balance_adjust_wrapper(charges, zs, n_anions, n_cations, anion_zs, cation_zs, z_water = ion_balance_adjust_one(charges, zs, n_anions, n_cations, adjust=adjust) new_zi = cation_zs[cation_index] if positive else anion_zs[anion_index] if increase is True and new_zi < old_zi: - raise ValueError('Adjusting specified ion %s resulted in a decrease of its quantity but an increase was specified' % selected_ion.formula) + raise ValueError('Adjusting specified ion {} resulted in a decrease of its quantity but an increase was specified'.format(selected_ion.formula)) elif increase is False and new_zi > old_zi: - raise ValueError('Adjusting specified ion %s resulted in a increase of its quantity but an decrease was specified' % selected_ion.formula) + raise ValueError('Adjusting specified ion {} resulted in a increase of its quantity but an decrease was specified'.format(selected_ion.formula)) return anion_zs, cation_zs, z_water @@ -1497,7 +1497,7 @@ def ion_balance_adjust_one(charges, zs, n_anions, n_cations, adjust): main_tot = sum([zs[i]*charges[i] for i in range(len(charges)) if i != adjust]) zs[adjust] = -main_tot/charges[adjust] if zs[adjust] < 0: - raise ValueError('A negative value of %f ion mole fraction was required to balance the charge' %zs[adjust]) + raise ValueError('A negative value of {:f} ion mole fraction was required to balance the charge'.format(zs[adjust])) z_water = 1. - sum(zs[0:-1]) anion_zs = zs[0:n_anions] @@ -1528,7 +1528,7 @@ def ion_balance_dominant(impacts, balance_error, charges, zs, n_anions, else: adjust = impacts.index(min(impacts)) else: - raise ValueError('Allowable methods are %s' %charge_balance_methods) + raise ValueError('Allowable methods are {}'.format(charge_balance_methods)) return ion_balance_adjust_one(charges, zs, n_anions, n_cations, adjust) @@ -1563,7 +1563,7 @@ def ion_balance_proportional(anion_charges, cation_charges, zs, n_anions, multiplier = -cation_balance_error/anion_balance_error anion_zs = [i*multiplier for i in anion_zs] else: - raise Exception('Allowable methods are %s' %charge_balance_methods) + raise Exception('Allowable methods are {}'.format(charge_balance_methods)) z_water = 1. - sum(anion_zs) - sum(cation_zs) return anion_zs, cation_zs, z_water diff --git a/thermo/eos.py b/thermo/eos.py index f4cbdb69..1d65c342 100644 --- a/thermo/eos.py +++ b/thermo/eos.py @@ -1131,7 +1131,7 @@ def solve(self, pure_a_alphas=True, only_l=False, only_g=False, full_alphas=True T = mp.mpf(T) self.P = float(R*T/(V-self.b) - self.a_alpha/(V*V + self.delta*V + self.epsilon)) if self.P <= 0.0: - raise ValueError("TV inputs result in negative pressure of %f Pa" %(self.P)) + raise ValueError("TV inputs result in negative pressure of {:f} Pa".format(self.P)) # self.P = R*self.T/(V-self.b) - self.a_alpha/(V*(V + self.delta) + self.epsilon) else: raise ValueError("Two specs are required") @@ -1263,7 +1263,7 @@ def set_from_PT(self, Vs, only_l=False, only_g=False): # Even in the case of three real roots, it is still the min/max that make sense print([self.T, self.P, b, self.delta, self.epsilon, self.a_alpha, 'coordinates of failure']) if self.multicomponent: - extra = ', zs is %s' %(self.zs) + extra = ', zs is {}'.format(self.zs) else: extra = '' raise ValueError(f'No acceptable roots were found; the roots are {Vs!s}, T is {self.T!s} K, P is {self.P!s} Pa, a_alpha is {[self.a_alpha]!s}, b is {[self.b]!s}{extra}') @@ -2135,7 +2135,7 @@ def volume_errors(self, Tmin=1e-4, Tmax=1e4, Pmin=1e-2, Pmax=1e9, if timing: ax.set_title('Volume timings; max %.2e us' %(max_err*1e6)) else: - ax.set_title('Volume solution validation; max err %.4e' %(max_err)) + ax.set_title('Volume solution validation; max err {:.4e}'.format(max_err)) if show: plt.show() @@ -2323,7 +2323,7 @@ def PT_surface_special(self, Tmin=1e-4, Tmax=1e4, Pmin=1e-2, Pmax=1e9, norm = LogNorm() if base_positive else None im = ax.pcolormesh(X, Y, z, cmap=color_map, norm=norm) cbar = fig.colorbar(im, ax=ax) - cbar.set_label('%s' %base_property) + cbar.set_label('{}'.format(base_property)) if Psat: plt.plot(Ts_Psats, Psats, label='Psat') @@ -2349,7 +2349,7 @@ def PT_surface_special(self, Tmin=1e-4, Tmax=1e4, Pmin=1e-2, Pmax=1e9, plt.legend() - ax.set_title('%s vs minimum Gibbs validation' %(base_property)) + ax.set_title('{} vs minimum Gibbs validation'.format(base_property)) if show: plt.show() @@ -2453,10 +2453,10 @@ def saturation_prop_plot(self, prop, Tmin=None, Tmax=None, pts=100, plt.plot(Ts, props) ax.set_xlabel('Temperature [K]') - ax.set_ylabel(r'%s' %(prop)) + ax.set_ylabel(r'{}'.format(prop)) - ax.set_title(r'Saturation %s curve' %(prop)) + ax.set_title(r'Saturation {} curve'.format(prop)) if show: plt.show() @@ -2546,14 +2546,14 @@ def Psat_errors(self, Tmin=None, Tmax=None, pts=50, plot=False, show=False, # Trust the fit - do not continue if no good continue except Exception as e: - raise ValueError("Failed to converge at %.16f K with unexpected error" %(T), e, self) + raise ValueError("Failed to converge at {:.16f} K with unexpected error".format(T), e, self) try: Psat_polished = self.Psat(T, polish=True) Psats_num.append(Psat_polished) except Exception as e: failed = True - raise ValueError("Failed to converge at %.16f K with unexpected error" %(T), e, self) + raise ValueError("Failed to converge at {:.16f} K with unexpected error".format(T), e, self) Ts_worked.append(T) Ts = Ts_worked @@ -2590,7 +2590,7 @@ def Psat_errors(self, Tmin=None, Tmax=None, pts=50, plot=False, show=False, if trunc_err_high is not None and max_err > trunc_err_high: max_err = trunc_err_high - ax1.set_title('Vapor pressure validation; max rel err %.4e' %(max_err)) + ax1.set_title('Vapor pressure validation; max rel err {:.4e}'.format(max_err)) if show: plt.show() @@ -2834,7 +2834,7 @@ def to_solve(T): try: Tsat = newton(to_solve_newton, guess, fprime=True, maxiter=100, xtol=4e-13, require_eval=False, damping=1.0, low=low, high=high) - assert Tsat != low and Tsat != high + assert Tsat not in (low, high) except: Tsat = newton(to_solve_newton, guess, fprime=True, maxiter=250, # the wider range can take more iterations xtol=4e-13, require_eval=False, damping=1.0, low=low, high=high*2) @@ -2924,7 +2924,7 @@ def Psat(self, T, polish=False, guess=None): Psat_ranges_low = self.Psat_ranges_low if x > Psat_ranges_low[-1]: if not polish: - raise NoSolutionError("T %.8f K is too low for equations to converge" %(T)) + raise NoSolutionError("T {:.8f} K is too low for equations to converge".format(T)) else: # Needs to still be here for generating better data x = Psat_ranges_low[-1] @@ -2943,7 +2943,7 @@ def Psat(self, T, polish=False, guess=None): if polish: Psat = 1e-100 else: - raise NoSolutionError("T %.8f K is too low for equations to converge" %(T)) + raise NoSolutionError("T {:.8f} K is too low for equations to converge".format(T)) except OverflowError: # coefficients sometimes overflow before T is lowered to 0.32Tr # For @@ -3074,7 +3074,7 @@ def to_solve_bisect(P): converged = False if not converged: - raise ValueError("Could not converge at T=%.6f K" %(T)) + raise ValueError("Could not converge at T={:.6f} K".format(T)) return Psat @@ -3160,7 +3160,7 @@ def dPsat_dT(self, T, polish=False, also_Psat=False): Psat_ranges_low = self.Psat_ranges_low x = alpha/Tr - 1. if x > Psat_ranges_low[-1]: - raise NoSolutionError("T %.8f K is too low for equations to converge" %(T)) + raise NoSolutionError("T {:.8f} K is too low for equations to converge".format(T)) for i in range(len(Psat_ranges_low)): if x < Psat_ranges_low[i]: @@ -10035,7 +10035,7 @@ def solve_T(self, P, V, solution=None): x30 = b*x12 T_calc = -Tc*(2.*a*m*x9*(V*x21*x21*x21*(V + b)*(P*x2 + P*x7 + x17 + x18 + x22 + x23 - x24))**0.5*(m + 1.) - x20*x21*(-P*x16*x6 + x1*x22 + x10*x26 + x13*x28 - x13*x30 + x15*x23 + x15*x24 + x19*x26 + x22*x3 + x25*x5 + x25 + x27*x5 + x27 + x28*x29 + x28*x5 - x29*x30 - x30*x5))/(x20*x9) if abs(T_calc.imag) > 1e-12: - raise ValueError("Calculated imaginary temperature %s" %(T_calc)) + raise ValueError("Calculated imaginary temperature {}".format(T_calc)) return T_calc else: return Tc*(-2*a*m*sqrt(V*(V - b)**3*(V + b)*(P*R*Tc*V**2 + P*R*Tc*V*b - P*V*a*m**2 + P*a*b*m**2 + R*Tc*a*m**2 + 2*R*Tc*a*m + R*Tc*a))*(m + 1)*(R*Tc*V**2 + R*Tc*V*b - V*a*m**2 + a*b*m**2)**2 + (V - b)*(R**2*Tc**2*V**4 + 2*R**2*Tc**2*V**3*b + R**2*Tc**2*V**2*b**2 - 2*R*Tc*V**3*a*m**2 + 2*R*Tc*V*a*b**2*m**2 + V**2*a**2*m**4 - 2*V*a**2*b*m**4 + a**2*b**2*m**4)*(P*R*Tc*V**4 + 2*P*R*Tc*V**3*b + P*R*Tc*V**2*b**2 - P*V**3*a*m**2 + P*V*a*b**2*m**2 + R*Tc*V**2*a*m**2 + 2*R*Tc*V**2*a*m + R*Tc*V**2*a + R*Tc*V*a*b*m**2 + 2*R*Tc*V*a*b*m + R*Tc*V*a*b + V*a**2*m**4 + 2*V*a**2*m**3 + V*a**2*m**2 - a**2*b*m**4 - 2*a**2*b*m**3 - a**2*b*m**2))/((R*Tc*V**2 + R*Tc*V*b - V*a*m**2 + a*b*m**2)**2*(R**2*Tc**2*V**4 + 2*R**2*Tc**2*V**3*b + R**2*Tc**2*V**2*b**2 - 2*R*Tc*V**3*a*m**2 + 2*R*Tc*V*a*b**2*m**2 + V**2*a**2*m**4 - 2*V*a**2*b*m**4 + a**2*b**2*m**4)) diff --git a/thermo/eos_mix.py b/thermo/eos_mix.py index 6d733c52..a688d039 100644 --- a/thermo/eos_mix.py +++ b/thermo/eos_mix.py @@ -415,7 +415,7 @@ def __repr__(self): for k, v in self.kwargs.items(): s += f'{k}={v!r}, ' - s += 'zs=%s, ' %(repr(self.zs)) + s += 'zs={}, '.format(repr(self.zs)) if hasattr(self, 'no_T_spec') and self.no_T_spec: s += f'P={self.P!r}, V={self.V!r}' elif self.V is not None: diff --git a/thermo/equilibrium.py b/thermo/equilibrium.py index c9979fc7..8311a20e 100644 --- a/thermo/equilibrium.py +++ b/thermo/equilibrium.py @@ -250,9 +250,9 @@ def __str__(self): def __repr__(self): s = f'{self.__class__.__name__}(T={self.T}, P={self.P}, zs={self.zs}, betas={self.betas}' - s += ', gas=%s' %(self.gas.__repr__()) - s += ', liquids=%s' %(self.liquids.__repr__()) - s += ', solids=%s' %(self.solids.__repr__()) + s += ', gas={}'.format(self.gas.__repr__()) + s += ', liquids={}'.format(self.liquids.__repr__()) + s += ', solids={}'.format(self.solids.__repr__()) s += ')' return s @@ -3265,8 +3265,8 @@ def _make_getter_correlations(name): def get_correlation(self): return getattr(self.correlations, name) - text = """Wrapper to obtain the list of %s objects of the associated -:obj:`PropertyCorrelationsPackage `.""" %(name) + text = """Wrapper to obtain the list of {} objects of the associated +:obj:`PropertyCorrelationsPackage `.""".format(name) try: get_correlation.__doc__ = text except: @@ -3490,11 +3490,11 @@ def get_atom_fraction(self): for ele in periodic_table: getter = _make_getter_atom_fraction(ele.symbol) - name = '%s_atom_fraction' %(ele.name) + name = '{}_atom_fraction'.format(ele.name) _add_attrs_doc = r"""Method to calculate and return the mole fraction that - is %s element, [-] - """ %(ele.name) + is {} element, [-] + """.format(ele.name) getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3514,11 +3514,11 @@ def get_atom_mass_fraction(self): return get_atom_mass_fraction for ele in periodic_table: getter = _make_getter_atom_mass_fraction(ele.symbol) - name = '%s_atom_mass_fraction' %(ele.name) + name = '{}_atom_mass_fraction'.format(ele.name) _add_attrs_doc = r"""Method to calculate and return the mass fraction of the phase - that is %s element, [-] - """ %(ele.name) + that is {} element, [-] + """.format(ele.name) getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3538,11 +3538,11 @@ def get_atom_mass_flow(self): for ele in periodic_table: getter = _make_getter_atom_mass_flow(ele.symbol) - name = '%s_atom_mass_flow' %(ele.name) + name = '{}_atom_mass_flow'.format(ele.name) _add_attrs_doc = r"""Method to calculate and return the mass flow of atoms - that are %s element, [kg/s] - """ %(ele.name) + that are {} element, [kg/s] + """.format(ele.name) getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3562,11 +3562,11 @@ def get_atom_flow(self): for ele in periodic_table: getter = _make_getter_atom_flow(ele.symbol) - name = '%s_atom_flow' %(ele.name) + name = '{}_atom_flow'.format(ele.name) _add_attrs_doc = r"""Method to calculate and return the mole flow that is - %s, [mol/s] - """ %(ele.name) + {}, [mol/s] + """.format(ele.name) getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3586,11 +3586,11 @@ def get_atom_count_flow(self): for ele in periodic_table: getter = _make_getter_atom_count_flow(ele.symbol) - name = '%s_atom_count_flow' %(ele.name) + name = '{}_atom_count_flow'.format(ele.name) _add_attrs_doc = r"""Method to calculate and return the number of atoms in the - flow which are %s, [atoms/s] - """ %(ele.name) + flow which are {}, [atoms/s] + """.format(ele.name) getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3618,10 +3618,10 @@ def get(self): return get for _name, _CAS in _comonent_specific_properties.items(): getter = _make_getter_partial_pressure(_CAS) - name = '%s_partial_pressure' %(_name) + name = '{}_partial_pressure'.format(_name) - _add_attrs_doc = r"""Method to calculate and return the ideal partial pressure of %s, [Pa] - """ %(_name) + _add_attrs_doc = r"""Method to calculate and return the ideal partial pressure of {}, [Pa] + """.format(_name) getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3640,7 +3640,7 @@ def get(self): for _name, _CAS in _comonent_specific_properties.items(): getter = _make_getter_component_molar_weight(_CAS) - name = '%s_molar_weight' %(_name) + name = '{}_molar_weight'.format(_name) _add_attrs_doc = rf"""Method to calculate and return the effective quantiy of {_name} in the phase as a molar weight, [g/mol]. diff --git a/thermo/flash/flash_base.py b/thermo/flash/flash_base.py index cbda9595..0c6ae8e2 100644 --- a/thermo/flash/flash_base.py +++ b/thermo/flash/flash_base.py @@ -1355,7 +1355,7 @@ def debug_PT(self, zs, Pmin=None, Pmax=None, Tmin=None, Tmax=None, pts=50, if len(zs) > 4: zs = '...' - plt.title('PT system flashes, zs=%s' %zs) + plt.title('PT system flashes, zs={}'.format(zs)) if show: plt.show() else: @@ -1467,10 +1467,10 @@ def plot_TP(self, zs, Tmin=None, Tmax=None, pts=50, branches=None, plt.semilogy(Ts, P_bubbles, label='TP bubble point curve') plt.xlabel('System temperature, K') plt.ylabel('System pressure, Pa') - plt.title('PT system curve, zs=%s' %zs) + plt.title('PT system curve, zs={}'.format(zs)) if branch: for VF, Ps in zip(branches, branch_Ps): - plt.semilogy(Ts, Ps, label='TP curve for VF=%s'%VF) + plt.semilogy(Ts, Ps, label='TP curve for VF={}'.format(VF)) plt.legend(loc='best') if show: plt.show() @@ -1583,10 +1583,10 @@ def plot_PT(self, zs, Pmin=None, Pmax=None, pts=50, branches=[], plt.plot(Ps, T_bubbles, label='PT bubble point curve') plt.xlabel('System pressure, Pa') plt.ylabel('System temperature, K') - plt.title('PT system curve, zs=%s' %zs) + plt.title('PT system curve, zs={}'.format(zs)) if branch: for VF, Ts in zip(branches, branch_Ts): - plt.plot(Ps, Ts, label='PT curve for VF=%s'%VF) + plt.plot(Ps, Ts, label='PT curve for VF={}'.format(VF)) plt.legend(loc='best') if show: @@ -1682,9 +1682,9 @@ def bubble_at_zs(zs): cb.update_ticks() # plt.tight_layout() if is_T_spec: - text = "Bubble pressure vs composition (left) and dew pressure vs composition (right) at %s K" %T + text = "Bubble pressure vs composition (left) and dew pressure vs composition (right) at {} K".format(T) else: - text = "Bubble temperature vs composition (left) and dew temperature vs composition (right) at %s Pa" %P + text = "Bubble temperature vs composition (left) and dew temperature vs composition (right) at {} Pa".format(P) fig.suptitle(text, fontsize=14) fig.subplots_adjust(top=0.85) plt.show() @@ -1757,7 +1757,7 @@ def plot_Txy(self, P, pts=30, ignore_errors=True, values=False, show=True): # pr import matplotlib.pyplot as plt fig, ax = plt.subplots() names = self.constants.aliases - plt.title('Txy diagram at P=%s Pa' %P) + plt.title('Txy diagram at P={} Pa'.format(P)) plt.plot(z1, Ts_dew, label='Dew temperature, K') plt.plot(z1, Ts_bubble, label='Bubble temperature, K') plt.xlabel(f'Mole fraction {names[0]}') @@ -1836,7 +1836,7 @@ def plot_Pxy(self, T, pts=30, ignore_errors=True, values=False, show=True): # pr import matplotlib.pyplot as plt fig, ax = plt.subplots() - plt.title('Pxy diagram at T=%s K' %T) + plt.title('Pxy diagram at T={} K'.format(T)) plt.plot(z1, Ps_dew, label='Dew pressure') plt.plot(z1, Ps_bubble, label='Bubble pressure') plt.xlabel(f'Mole fraction {names[0]}') @@ -1912,9 +1912,9 @@ def plot_xy(self, P=None, T=None, pts=30, ignore_errors=True, values=False, import matplotlib.pyplot as plt fig, ax = plt.subplots() if T is not None: - plt.title('xy diagram at T=%s K (varying P)' %T) + plt.title('xy diagram at T={} K (varying P)'.format(T)) else: - plt.title('xy diagram at P=%s Pa (varying T)' %P) + plt.title('xy diagram at P={} Pa (varying T)'.format(P)) names = self.constants.aliases plt.xlabel(f'Liquid mole fraction {names[0]}') plt.ylabel(f'Vapor mole fraction {names[0]}') diff --git a/thermo/flash/flash_pure_vls.py b/thermo/flash/flash_pure_vls.py index c4964926..ba064516 100644 --- a/thermo/flash/flash_pure_vls.py +++ b/thermo/flash/flash_pure_vls.py @@ -349,7 +349,7 @@ def flash_TPV(self, T, P, V, zs=None, solution=None, hot_start=None): elif callable(solution): fun = solution else: - raise ValueError("Did not recognize solution %s" %(solution)) + raise ValueError("Did not recognize solution {}".format(solution)) if self.phase_count == 1: phase = self.phases[0].to(zs=zs, T=T, P=P, V=V) @@ -950,7 +950,7 @@ def selection_fun_1P(new, prev): if S_min_spec <= spec_val <= S_max_spec: had_solution = True if had_solution: - raise UnconvergedError("Could not converge but solution detected in bounds: %s" %s) + raise UnconvergedError("Could not converge but solution detected in bounds: {}".format(s)) elif uncertain_solution: raise UnconvergedError("Could not converge and unable to detect if solution detected in bounds") else: @@ -1126,8 +1126,8 @@ def flash_VF_HSGUA(self, fixed_var_val, spec_val, fixed_var='VF', spec_var='H', dfug_dT_idx = props.index('dfugacity_dT') dfug_dP_idx = props.index('dfugacity_dP') - dspec_dT_var = 'd%s_dT' %(spec_var) - dspec_dP_var = 'd%s_dP' %(spec_var) + dspec_dT_var = 'd{}_dT'.format(spec_var) + dspec_dP_var = 'd{}_dP'.format(spec_var) dspec_dT_idx = props.index(dspec_dT_var) dspec_dP_idx = props.index(dspec_dP_var) @@ -1256,8 +1256,8 @@ def flash_VF_HSGUA(self, fixed_var_val, spec_val, fixed_var='VF', spec_var='H', return self.flash_VF_HSGUA_bounded(T_guess, T_low, T_high, fixed_var_val, spec_val, fixed_var=fixed_var, spec_var=spec_var) def _VF_HSGUA_der_root(self, guess, low, high, fixed_var_val, spec_val, fixed_var='VF', spec_var='H'): - dspec_dT_var = 'd%s_dT' % (spec_var) - dspec_dP_var = 'd%s_dP' % (spec_var) + dspec_dT_var = 'd{}_dT'.format(spec_var) + dspec_dP_var = 'd{}_dP'.format(spec_var) VF = fixed_var_val val_cache = [None, 0] @@ -1291,8 +1291,8 @@ def to_solve(T): return T_zero, val_cache[0] def flash_VF_HSGUA_bounded(self, guess, low, high, fixed_var_val, spec_val, fixed_var='VF', spec_var='H'): - dspec_dT_var = 'd%s_dT' % (spec_var) - dspec_dP_var = 'd%s_dP' % (spec_var) + dspec_dT_var = 'd{}_dT'.format(spec_var) + dspec_dP_var = 'd{}_dP'.format(spec_var) VF = fixed_var_val cache = [0] diff --git a/thermo/flash/flash_utils.py b/thermo/flash/flash_utils.py index f3366c08..e9fa6d35 100644 --- a/thermo/flash/flash_utils.py +++ b/thermo/flash/flash_utils.py @@ -845,7 +845,7 @@ def nonlin_spec_NP(guess, fixed_val, spec_val, zs, compositions_guesses, betas_g dspec_diter_s = f'd{spec}_d{iter_var}' dspec_diter_callables = [getattr(phase.__class__, dspec_diter_s) for phase in phases] - dspec_dn_s = 'd%s_dns' %(spec) + dspec_dn_s = 'd{}_dns'.format(spec) dspec_dn_callables = [getattr(phase.__class__, dspec_dn_s) for phase in phases] jac = True @@ -1826,7 +1826,7 @@ def dew_bubble_newton_zs(guess, fixed_val, zs, liquid_phase, gas_phase, for i in cmps: JN[i] = -comp_factor - s = 'dlnphis_d%s' %(iter_var) + s = 'dlnphis_d{}'.format(iter_var) dlnphis_diter_var_iter = getattr(iter_phase.__class__, s) dlnphis_diter_var_const = getattr(const_phase.__class__, s) dlnphis_dzs = iter_phase.__class__.dlnphis_dzs @@ -1996,7 +1996,7 @@ def dew_bubble_Michelsen_Mollerup(guess, fixed_val, zs, liquid_phase, gas_phase, else: iter_msg, const_msg = g_undefined_P_msg, l_undefined_P_msg - s = 'dlnphis_d%s' %(iter_var) + s = 'dlnphis_d{}'.format(iter_var) dlnphis_diter_var_iter = getattr(iter_phase.__class__, s) dlnphis_diter_var_const = getattr(const_phase.__class__, s) @@ -2166,7 +2166,7 @@ def existence_3P_Michelsen_Mollerup(guess, fixed_val, zs, iter_phase, liquid0, l elif iter_var == 'P': iter_msg, const_msg = g_undefined_P_msg, l_undefined_P_msg - s = 'dlnphis_d%s' %(iter_var) + s = 'dlnphis_d{}'.format(iter_var) dlnphis_diter_var_iter = getattr(iter_phase.__class__, s) dlnphis_diter_var_liquid0 = getattr(liquid0.__class__, s) # dlnphis_diter_var_liquid1 = getattr(liquid1.__class__, s) diff --git a/thermo/nrtl.py b/thermo/nrtl.py index 35e288ff..549e73dd 100644 --- a/thermo/nrtl.py +++ b/thermo/nrtl.py @@ -738,9 +738,9 @@ def __repr__(self): for i, attr in enumerate(self._model_attributes[:6]): if self.tau_coeffs_nonzero[i]: s += f', {attr}={getattr(self, attr)}' - s += ', alpha_cs=%s' %(self.alpha_cs) + s += ', alpha_cs={}'.format(self.alpha_cs) if not self.alpha_temperature_independent: - s += ', alpha_ds=%s' %(self.alpha_ds) + s += ', alpha_ds={}'.format(self.alpha_ds) s += ')' return s diff --git a/thermo/phases/helmholtz_eos.py b/thermo/phases/helmholtz_eos.py index 0921c3eb..cca0a62f 100644 --- a/thermo/phases/helmholtz_eos.py +++ b/thermo/phases/helmholtz_eos.py @@ -50,7 +50,7 @@ def __repr__(self): >>> phase IAPWS95Gas(T=300, P=100000.0, zs=[1.0]) ''' - base = '%s(' %(self.__class__.__name__) + base = '{}('.format(self.__class__.__name__) iter_props = ('Hfs', 'Gfs', 'Sfs', 'T', 'P', 'zs') if self.__class__.__name__ not in ('IAPWS95Gas', 'IAPWS95Liquid') else ('T', 'P', 'zs') for s in iter_props: if hasattr(self, s) and getattr(self, s) is not None: diff --git a/thermo/phases/phase.py b/thermo/phases/phase.py index 6b949fa3..e762a942 100644 --- a/thermo/phases/phase.py +++ b/thermo/phases/phase.py @@ -184,7 +184,7 @@ def __init_subclass__(cls): __full_path__ = None def __str__(self): - s = '<%s, ' %(self.__class__.__name__) + s = '<{}, '.format(self.__class__.__name__) try: s += f'T={self.T:g} K, P={self.P:g} Pa' except: @@ -6342,7 +6342,7 @@ def _der(self, prop=attr): at_constant = 'T' if diff_by == 'P' else 'P' s = f'{base}_mass_{end}' - if not '2' in attr: + if '2' not in attr: # TODO docs for second mass derivatives doc = rf"""Method to calculate and return the {prop_names[diff_by]} derivative of mass {prop_names[prop]} of the phase at constant {prop_names[at_constant]}. diff --git a/thermo/phases/phase_utils.py b/thermo/phases/phase_utils.py index c8c9691d..010762ea 100644 --- a/thermo/phases/phase_utils.py +++ b/thermo/phases/phase_utils.py @@ -93,17 +93,17 @@ def lnphis_direct(zs, model, T, P, N, *args): for i in range(N): lnphis[i] = 0.0 return lnphis - elif model == 10200 or model == 10201 or model == 10204 or model == 10205 or model == 10206: + elif model in (10200, 10201, 10204, 10205, 10206): return PR_lnphis_fastest(zs, T, P, N, *args) - elif model == 10100 or model == 10104 or model == 10105: + elif model in (10100, 10104, 10105): return SRK_lnphis_fastest(zs, T, P, N, *args) elif model == 10002: return RK_lnphis_fastest(zs, T, P, N, *args) elif model == 10001: return VDW_lnphis_fastest(zs, T, P, N, *args) - elif model == 11202 or model == 11203 or model == 11207: + elif model in (11202, 11203, 11207): return PR_translated_lnphis_fastest(zs, T, P, N, *args) - elif model == 11101 or model == 11102 or model == 11103: + elif model in (11101, 11102, 11103): return SRK_translated_lnphis_fastest(zs, T, P, N, *args) # so far only used by the test test_UNIFAC_lnphis_direct elif 20000 <= model <= 29999: # numba: delete diff --git a/thermo/serialize.py b/thermo/serialize.py index 42f09ab7..5beda833 100644 --- a/thermo/serialize.py +++ b/thermo/serialize.py @@ -220,7 +220,7 @@ class JsonOptEncodable(): obj_references = None '''If this attribute is not None, instead of inspecting each object for whether it is a json-supported type, - only these attribute names are inspected for recursion. These are also the only references + only these attribute names are inspected for recursion. These are also the only references subject to deduplication. ''' diff --git a/thermo/stream.py b/thermo/stream.py index 099eaf91..f985ecd6 100644 --- a/thermo/stream.py +++ b/thermo/stream.py @@ -57,20 +57,20 @@ class StreamArgs: '''Creates an StreamArgs object, which is a holder and specification - tracking/counting utility object for the purposes of making - heat and material balances. Unlike :obj:`EquilibriumStream`, this + tracking/counting utility object for the purposes of making + heat and material balances. Unlike :obj:`EquilibriumStream`, this object is mutable and doesn't require any specifications. Specifications can be set as they become available, and then a :obj:`EquilibriumStream` can be generated from the method :obj:`StreamArgs.flash`. The specification tracking is the key purpose of this object. Once a - `T` and `P` have been set, `V` **can't** be set because there are no + `T` and `P` have been set, `V` **can't** be set because there are no degrees of freedom. Another state specification mst be removed by setting it to None before a new specification can be set. The specifications supported are the same as those of :obj:`EquilibriumStream`. Handling flow flow vs. composition is fuzzier because of the common use cases - where a flow rate may be known, but not composition; or the composition but not + where a flow rate may be known, but not composition; or the composition but not the flow, however later when the product flows are known it is desireable to set it. To allow this, the variables `ns`, `ms`, `Qls`, and `Qgs` are allowed to overwrite an existing @@ -201,6 +201,7 @@ class StreamArgs: and a partial list of mass fractions. This can be useful for some problems ''' + flashed = False '''`flashed` can be checked to quickly determine if an object is already flashed. It is always False for `StreamArgs`, and True for `EquilibriumState` and `EquilibriumStream`''' @@ -394,7 +395,7 @@ def energy(self): @energy.setter def energy(self, energy): - r'''Set the flowing energy of the stream [W]. This variable can set either the + r'''Set the flowing energy of the stream [W]. This variable can set either the flow rate, or act as an enthalpy spec if another flow rate specification is specified.''' if energy is None: self.specifications['energy'] = energy @@ -409,7 +410,7 @@ def energy_reactive(self): return self.specifications['energy_reactive'] @energy_reactive.setter def energy_reactive(self, energy_reactive): - r'''Set the flowing energy of the stream on a reactive basis [W]. This variable can set either the + r'''Set the flowing energy of the stream on a reactive basis [W]. This variable can set either the flow rate, or act as an enthalpy spec if another flow rate specification is specified.''' if energy_reactive is None: self.specifications['energy_reactive'] = energy_reactive @@ -1287,13 +1288,13 @@ def __repr__(self): return s def reconcile_flows(self, n_tol=2e-15, m_tol=2e-15): - """Evaluate the flow specifications provided to the StreamArgs instance + """Evaluate the flow specifications provided to the StreamArgs instance in the event the original inputs are overspecified, in the assumption that the inputs are internally consistent. If they are not consistent to the tolerances of this function, the :obj:`StreamArgs` instance will raise an error. - Examples this function can check are both `ms` and `m` provided, + Examples this function can check are both `ms` and `m` provided, or `ms` with one missing value and `m` provided (`ms` will be modified with the calculated value of the previously missing flow), if both `ms` and `ns` are set but with only some values in `ms` and some in `ns` @@ -1492,7 +1493,7 @@ def clear_state_specs(self): @property def state_specs(self): '''List of state specifications which have been set, as tuples - of ('specification_name', specification_value). Energy is + of ('specification_name', specification_value). Energy is included regardless of whether it is being used as a state specification. @@ -1542,7 +1543,7 @@ def state_specs(self): @property def non_pressure_state_specs(self): '''List of state specifications which have been set, as tuples - of ('specification_name', specification_value), excluding pressure. + of ('specification_name', specification_value), excluding pressure. Energy is included regardless of whether it is being used as a state specification. @@ -1627,7 +1628,7 @@ def state_specified(self): @property def non_pressure_spec_specified(self): '''Whether there is at least one state specification excluding a pressure - specification. + specification. Energy is included regardless of whether it is being used as a state specification. @@ -1779,7 +1780,7 @@ def stream(self, existing_flash=None, hot_start=None): Parameters ---------- existing_flash : EquilibriumState, optional - Existing flash which will be used instead of the composition and + Existing flash which will be used instead of the composition and state specs of this object [-] hot_start : EquilibriumState, optional Flash at nearby conditions that may be used to initialize the flash [-] @@ -2268,7 +2269,7 @@ def set_extensive_flow(self, n=None): except: pass - if self.phase == 'l/g' or self.phase == 'l': + if self.phase in ('l/g', 'l'): self.nl = nl = n*(1. - self.V_over_F) self.nls = [xi*nl for xi in self.xs] self.mls = [ni*MWi*1E-3 for ni, MWi in zip(self.nls, self.MWs)] @@ -2278,7 +2279,7 @@ def set_extensive_flow(self, n=None): else: self.Ql = None - if self.phase == 'l/g' or self.phase == 'g': + if self.phase in ('l/g', 'g'): self.ng = ng = n*self.V_over_F self.ngs = [yi*ng for yi in self.ys] self.mgs = [ni*MWi*1E-3 for ni, MWi in zip(self.ngs, self.MWs)] @@ -2409,7 +2410,7 @@ def __sub__(self, other): for i, in_self in enumerate(components_in_self): if not in_self and other.zs[i] > 0: raise Exception('Not all components to be removed are \ -present in the first stream; %s is not present.' %other.IDs[i]) +present in the first stream; {} is not present.'.format(other.IDs[i])) # Calculate the mole flows of each species ns_self = list(self.ns) @@ -2424,8 +2425,8 @@ def __sub__(self, other): relative_difference_product = abs(ns_self[i] - nj)/n_product relative_difference_self = abs(ns_self[i] - nj)/ns_self[i] if ns_self[i] - nj < 0 and (relative_difference_product > 1E-12 or relative_difference_self > 1E-9): - raise Exception('Attempting to remove more %s than is in the \ -first stream.' %self.IDs[i]) + raise Exception('Attempting to remove more {} than is in the \ +first stream.'.format(self.IDs[i])) if ns_self[i] - nj < 0.: ns_self[i] = 0. elif relative_difference_product < 1E-12: @@ -2576,14 +2577,15 @@ class EquilibriumStream(EquilibriumState): Previously calculated :obj:`EquilibriumState` at the exact conditions, will be used instead of performing a new flash calculation if provided [-] ''' + flashed = True __full_path__ = f"{__module__}.{__qualname__}" def __repr__(self): flow_spec, flow_spec_val = self.flow_spec - s = '%s(%s=%s, ' %(self.__class__.__name__, flow_spec, flow_spec_val) + s = '{}({}={}, '.format(self.__class__.__name__, flow_spec, flow_spec_val) s += 'flasher=flasher' - s += ', existing_flash=%s' %EquilibriumState.__repr__(self).replace('EquilibriumStream', 'EquilibriumState') + s += ', existing_flash={}'.format(EquilibriumState.__repr__(self).replace('EquilibriumStream', 'EquilibriumState')) s += ')' return s @@ -2988,6 +2990,7 @@ class EnergyStream: >>> EnergyStream(Q=None) EnergyStream(Q=None) ''' + __full_path__ = f"{__module__}.{__qualname__}" obj_references = [] @@ -3137,10 +3140,10 @@ def _mole_balance_process_ns(f, ns, compounds, use_mass=True, use_volume=True): return ns def mole_balance(inlets, outlets, compounds, use_mass=True, use_volume=True): - r'''Basic function for performing material balances between a set of - inputs and outputs. The API of the function is to accept + r'''Basic function for performing material balances between a set of + inputs and outputs. The API of the function is to accept two lists of {EquilibriumStream, StreamArgs} objects. - The objects are subjected to the condition + The objects are subjected to the condition :math:`\text{material in} = \text{material out}` If an overdetermined set of inputs is provided (flow known for all objects), @@ -3150,8 +3153,8 @@ def mole_balance(inlets, outlets, compounds, use_mass=True, use_volume=True): anything), objects are unchanged and the function returns False. More usefully, if there is exactly one unknown flow, that unknown will be calculated. - This means the :obj:`StreamArgs` object with the unknown flow will have the balanced - mole flow `n` set to it. + This means the :obj:`StreamArgs` object with the unknown flow will have the balanced + mole flow `n` set to it. In certain cases where StreamArgs is used with `multiple_composition_basis`, it can also calculate for a single component flow as part of the specs `ns`, `ms`, `Qls`, or `Qgs` if that is the unknown. @@ -3405,10 +3408,10 @@ def mole_balance(inlets, outlets, compounds, use_mass=True, use_volume=True): def energy_balance(inlets, outlets, reactive=False, use_mass=False): - r'''Basic function for performing energy balances between a set of - inputs and outputs. The API of the function is to accept + r'''Basic function for performing energy balances between a set of + inputs and outputs. The API of the function is to accept two lists of {EnergyStream, EquilibriumStream, StreamArgs} objects. - The objects are subjected to the condition + The objects are subjected to the condition :math:`\text{energy in} = \text{energy out}` If an overdetermined set of inputs is provided (energy known for all objects), @@ -3629,7 +3632,7 @@ def energy_balance(inlets, outlets, reactive=False, use_mass=False): H_mass_in_unknown_0 = unknown_state_0.H_mass() if not reactive else unknown_state_0.H_reactive_mass() H_mass_in_unknown_1 = unknown_state_1.H_mass() if not reactive else unknown_state_1.H_reactive_mass() energy_in_known = sum(v for v in all_energy_in if v is not None) - m_in_known = sum(v.m for i, v in enumerate(inlets) if (i != in_unknown_idx_0 and i != in_unknown_idx_1 and not isinstance(v, EnergyStream))) + m_in_known = sum(v.m for i, v in enumerate(inlets) if (i not in (in_unknown_idx_0, in_unknown_idx_1) and not isinstance(v, EnergyStream))) m_out_known = sum(v.m for i, v in enumerate(outlets) if not isinstance(v, EnergyStream)) inlets[in_unknown_idx_0].m = (H_mass_in_unknown_1*m_in_known - H_mass_in_unknown_1*m_out_known - energy_in_known + outlet_energy)/(H_mass_in_unknown_0 - H_mass_in_unknown_1) @@ -3648,7 +3651,7 @@ def energy_balance(inlets, outlets, reactive=False, use_mass=False): H_mass_out_unknown_0 = unknown_state_0.H_mass() if not reactive else unknown_state_0.H_reactive_mass() H_mass_out_unknown_1 = unknown_state_1.H_mass() if not reactive else unknown_state_1.H_reactive_mass() energy_out_known = sum(v for v in all_energy_out if v is not None) - m_out_known = sum(v.m for i, v in enumerate(outlets) if (i != out_unknown_idx_0 and i != out_unknown_idx_1 and not isinstance(v, EnergyStream))) + m_out_known = sum(v.m for i, v in enumerate(outlets) if (i not in (out_unknown_idx_0, out_unknown_idx_1) and not isinstance(v, EnergyStream))) m_in_known = sum(v.m for i, v in enumerate(inlets) if not isinstance(v, EnergyStream)) outlets[out_unknown_idx_0].m = (H_mass_out_unknown_1*m_out_known - H_mass_out_unknown_1*m_in_known - energy_out_known + inlet_energy)/(H_mass_out_unknown_0 - H_mass_out_unknown_1) diff --git a/thermo/test_utils.py b/thermo/test_utils.py index db9c9e42..e08a9aa3 100644 --- a/thermo/test_utils.py +++ b/thermo/test_utils.py @@ -107,5 +107,5 @@ def mark_plot_unsupported(plot_fig, reason, color='r'): def flash_rounding(x): if isinstance(x, float): - return float('%.10e' %(x)) + return float('{:.10e}'.format(x)) return x diff --git a/thermo/thermal_conductivity.py b/thermo/thermal_conductivity.py index 9e551f58..219c7ea5 100644 --- a/thermo/thermal_conductivity.py +++ b/thermo/thermal_conductivity.py @@ -1444,6 +1444,7 @@ class ThermalConductivitySolid(TDependentProperty): See Also -------- + Examples -------- >>> obj = ThermalConductivitySolid(CASRN='142-82-5') @@ -1451,6 +1452,7 @@ class ThermalConductivitySolid(TDependentProperty): References ---------- ''' + name = 'solid thermal conductivity' units = 'W/m/K' interpolation_T = None diff --git a/thermo/unifac.py b/thermo/unifac.py index 58729516..5b559989 100644 --- a/thermo/unifac.py +++ b/thermo/unifac.py @@ -168,7 +168,7 @@ class UNIFAC_subgroup: 'priority', 'atoms', 'bonds'] def __repr__(self): # pragma: no cover - return '<%s>' %self.group + return '<{}>'.format(self.group) def __init__(self, group_id, group, main_group_id, main_group, R, Q, smarts=None, priority=None, atoms=None, bonds=None, hydrogen_from_smarts=False): @@ -3154,7 +3154,7 @@ def chemgroups_to_matrix(chemgroups): all_keys = set() [all_keys.update(i.keys()) for i in chemgroups] for k in sorted(list(all_keys)): - matrix.append([l[k] if k in l else 0 for l in chemgroups]) + matrix.append([l.get(k, 0) for l in chemgroups]) # matrix.append([float(l[k]) if k in l else 0.0 for l in chemgroups]) # Cannot notice performance improvement return matrix @@ -3165,7 +3165,7 @@ def unifac_psis(T, N_groups, version, psi_a, psi_b, psi_c, psis=None): mT_inv = -1.0/T - if version == 4 or version == 5: + if version in (4, 5): T0 = 298.15 TmT0 = T - T0 B = T*log(T0/T) + T - T0 @@ -3191,7 +3191,7 @@ def unifac_dpsis_dT(T, N_groups, version, psi_a, psi_b, psi_c, psis, dpsis_dT=No T2_inv = 1.0/(T*T) - if version == 4 or version == 5: + if version in (4, 5): T0 = 298.15 mT_inv = -1.0/T T2_inv = mT_inv*mT_inv @@ -3220,7 +3220,7 @@ def unifac_d2psis_dT2(T, N_groups, version, psi_a, psi_b, psi_c, psis, d2psis_dT if d2psis_dT2 is None: d2psis_dT2 = [[0.0]*N_groups for _ in range(N_groups)] # numba: delete # d2psis_dT2 = zeros((N_groups, N_groups)) # numba: uncomment - if version == 4 or version == 5: + if version in (4, 5): T0 = 298.15 T_inv = 1.0/T T2_inv = T_inv*T_inv @@ -3255,7 +3255,7 @@ def unifac_d3psis_dT3(T, N_groups, version, psi_a, psi_b, psi_c, psis, d3psis_dT # d3psis_dT3 = zeros((N_groups, N_groups)) # numba: uncomment - if version == 4 or version == 5: + if version in (4, 5): T0 = 298.15 T_inv = 1.0/T nT3_inv = -T_inv*T_inv*T_inv @@ -4073,7 +4073,7 @@ def unifac_gammas_from_args(xs, N, N_groups, vs, rs, qs, Qs, Vis, rx_sum_inv = unifac_Vis(rs=rs, xs=xs, N=N) Fis, qx_sum_inv = unifac_Vis(rs=qs, xs=xs, N=N) - if version == 1 or version == 3 or version == 4: + if version in (1, 3, 4): Vis_modified, r34x_sum_inv = unifac_Vis(rs=rs_34, xs=xs, N=N) else: Vis_modified = Vis diff --git a/thermo/units.py b/thermo/units.py index 6c95fc67..3baeecb6 100644 --- a/thermo/units.py +++ b/thermo/units.py @@ -41,7 +41,7 @@ for name in dir(thermo): - if name == '__getattr__' or name == '__test__': + if name in ('__getattr__', '__test__'): continue obj = getattr(thermo, name) if isinstance(obj, types.FunctionType): @@ -62,8 +62,8 @@ obj = wrap_numpydoc_obj(obj) except Exception as e: failed_wrapping = True - print('Current implementation of %s contains documentation not ' - 'parseable and cound not be wrapped to use pint:' %str(obj)) + print('Current implementation of {} contains documentation not ' + 'parseable and cound not be wrapped to use pint:'.format(str(obj))) print(e) elif isinstance(obj, str): continue diff --git a/thermo/utils/mixture_property.py b/thermo/utils/mixture_property.py index c27369d1..d48f7202 100644 --- a/thermo/utils/mixture_property.py +++ b/thermo/utils/mixture_property.py @@ -70,14 +70,14 @@ def __init_subclass__(cls): def __repr__(self): clsname = self.__class__.__name__ - base = '%s(' % (clsname) + base = '{}('.format(clsname) for k in self.custom_args: v = getattr(self, k) if v is not None: base += f'{k}={v}, ' - base += 'CASs=%s, ' %(self.CASs) - base += 'correct_pressure_pure=%s, ' %(self._correct_pressure_pure) - base += 'method="%s", ' %(self.method) + base += 'CASs={}, '.format(self.CASs) + base += 'correct_pressure_pure={}, '.format(self._correct_pressure_pure) + base += 'method="{}", '.format(self.method) for attr in self.pure_references: base += f'{attr}={getattr(self, attr)}, ' @@ -129,7 +129,7 @@ def __init__(self, **kwargs): # Attempt to load json data CASs = self.CASs - if CASs and not None in CASs and ENABLE_MIXTURE_JSON: + if CASs and None not in CASs and ENABLE_MIXTURE_JSON: cls_name = self.__class__.__name__ outer = [] for CAS1 in CASs: @@ -169,7 +169,7 @@ def __init__(self, **kwargs): kwargs['redlick_kister_parameters']['Combined Json'] = {'N_T': N_T, 'N_terms': N_terms, 'coeffs': rk_struct} if kwargs: - mixture_excess_models = set(['redlick_kister_parameters']) + mixture_excess_models = {'redlick_kister_parameters'} # Iterate over all the dictionaries in reverse such that the first one is left as the default for key in reversed(list(kwargs.keys())): if key in mixture_excess_models: @@ -232,7 +232,7 @@ def calculate(self, T, P, zs, ws, method): excess = redlich_kister_excess_inner(N_T, N_terms, Ais_matrix_for_calc, zs) base_property = mixing_simple(zs, pure_props) return base_property + excess - raise ValueError("Unknown method; methods are %s" %(self.all_methods)) + raise ValueError("Unknown method; methods are {}".format(self.all_methods)) def calculate_pures_corrected(self, T, P, fallback=False, objs=None): if self._correct_pressure_pure: @@ -932,10 +932,10 @@ def plot_isobaric_isothermal(self, T, P, methods=[], pts=50, only_valid=True, xs_plot.append(x0) except: pass - plt.plot(xs_plot, properties, label=method + ' at %g K and %g Pa' %(T, P) ) + plt.plot(xs_plot, properties, label=method + ' at {:g} K and {:g} Pa'.format(T, P) ) else: properties = [func(T, P, [x0, 1.0 - x0], None, method) for x0 in xs] - plt.plot(xs, properties, label=method + ' at %g K and %g Pa' %(T, P)) + plt.plot(xs, properties, label=method + ' at {:g} K and {:g} Pa'.format(T, P)) plt.legend(loc='best') plt.ylabel(prop_name + ', ' + self.units) plt.xlabel('Mole fraction x0') diff --git a/thermo/utils/t_dependent_property.py b/thermo/utils/t_dependent_property.py index 245b4eba..807e5e0b 100644 --- a/thermo/utils/t_dependent_property.py +++ b/thermo/utils/t_dependent_property.py @@ -490,7 +490,7 @@ def f_int_over_T(self, Ta, Tb): PROPERTY_TRANSFORM_D_X = 'dxdToverx' PROPERTY_TRANSFORM_D2_X = 'd2xdT2overx' -skipped_parameter_combinations = {'REFPROP_sigma': set([('sigma1',), ('sigma1', 'n1', 'sigma2')])} +skipped_parameter_combinations = {'REFPROP_sigma': {('sigma1',), ('sigma1', 'n1', 'sigma2')}} DEFAULT_PHASE_TRANSITIONS = 'Default phase transitions' @@ -1490,9 +1490,9 @@ def __repr__(self): def as_string(self, tabular=True, references=True, json_parameters=False): clsname = self.__class__.__name__ - base = '%s(' % (clsname) + base = '{}('.format(clsname) if self.CASRN: - base += 'CASRN="%s", ' %(self.CASRN) + base += 'CASRN="{}", '.format(self.CASRN) for k in self.custom_args: v = getattr(self, k) if v is not None: @@ -1500,29 +1500,29 @@ def as_string(self, tabular=True, references=True, json_parameters=False): continue base += f'{k}={v}, ' - extrap_str = '"%s"' %(self.extrapolation) if self.extrapolation is not None else 'None' - base += 'extrapolation=%s, ' %(extrap_str) + extrap_str = '"{}"'.format(self.extrapolation) if self.extrapolation is not None else 'None' + base += 'extrapolation={}, '.format(extrap_str) if self._extrapolation_min != self.DEFAULT_EXTRAPOLATION_MIN: - extrap_str = '%s' %(self._extrapolation_min) if self._extrapolation_min is not None else 'None' - base += 'extrapolation_min=%s, ' %(extrap_str) + extrap_str = '{}'.format(self._extrapolation_min) if self._extrapolation_min is not None else 'None' + base += 'extrapolation_min={}, '.format(extrap_str) if self._extrapolation_max != self.DEFAULT_EXTRAPOLATION_MAX: - extrap_str = '%s' %(self._extrapolation_max) if self._extrapolation_max is not None else 'None' - base += 'extrapolation_max=%s, ' %(extrap_str) + extrap_str = '{}'.format(self._extrapolation_max) if self._extrapolation_max is not None else 'None' + base += 'extrapolation_max={}, '.format(extrap_str) - method_str = '"%s"' %(self.method) if self.method is not None else 'None' - base += 'method=%s, ' %(method_str) + method_str = '"{}"'.format(self.method) if self.method is not None else 'None' + base += 'method={}, '.format(method_str) if self.tabular_data and tabular: if not (len(self.tabular_data) == 1 and VDI_TABULAR in self.tabular_data): - base += 'tabular_data=%s, ' %(self.tabular_data) + base += 'tabular_data={}, '.format(self.tabular_data) if self.P_dependent: - method_P_str = '"%s"' %(self.method_P) if self.method_P is not None else 'None' - base += 'method_P=%s, ' %(method_P_str) + method_P_str = '"{}"'.format(self.method_P) if self.method_P is not None else 'None' + base += 'method_P={}, '.format(method_P_str) if self.tabular_data_P and tabular: - base += 'tabular_data_P=%s, ' %(self.tabular_data_P) + base += 'tabular_data_P={}, '.format(self.tabular_data_P) if 'tabular_extrapolation_permitted' in self.__dict__ and tabular: - base += 'tabular_extrapolation_permitted=%s, ' %(self.tabular_extrapolation_permitted) + base += 'tabular_extrapolation_permitted={}, '.format(self.tabular_extrapolation_permitted) if hasattr(self, 'poly_fit_Tmin') and self.poly_fit_Tmin is not None: @@ -1783,7 +1783,7 @@ def _fit_export_polynomials(cls, method=None, start_n=3, max_n=30, for method, index in zip(methods, indexes): method_dat = {} n = cls._fit_force_n.get(method, None) - max_n_method = fit_max_n[method] if method in fit_max_n else max_n + max_n_method = fit_max_n.get(method, max_n) for CAS in index: print(CAS) obj = cls(CASRN=CAS) @@ -2184,7 +2184,7 @@ def fit_data_to_model(cls, Ts, data, model, model_kwargs=None, best_fit_aic, stats_aic, aic_aic, _, parameters_aic, _ = min(all_fits, key=sel) sel = lambda x: x[3] best_fit_bic, stats_bic, _, bic_bic, parameters_bic, _ = min(all_fits, key=sel) - if parameters_aic <= parameters_bic and not (1e200 in [v[2] for v in all_fits]) and not parameters_aic == 1: + if parameters_aic <= parameters_bic and 1e200 not in [v[2] for v in all_fits] and not parameters_aic == 1: # aic score is unreliable for points = parameters + 1 best_fit, stats = best_fit_aic, stats_aic else: @@ -2775,7 +2775,7 @@ def _base_calculate(self, T, method): return self.calculate(T, a_method) return self.calculate(T, method_names[-1]) else: - raise ValueError("Unknown method; methods are %s" %(self.all_methods)) + raise ValueError("Unknown method; methods are {}".format(self.all_methods)) def _base_calculate_P(self, T, P, method): if method in self.tabular_data_P: @@ -4396,7 +4396,7 @@ def extrapolate(self, T, method, in_range='error'): v0, n = coeffs T_lim = T_low if low else T_high val = Watson(T, Hvap_ref=v0, T_ref=T_lim, Tc=self.Tc, exponent=n) - elif extrapolation == 'EXP_POLY_LN_TAU2' or extrapolation == 'EXP_POLY_LN_TAU3': + elif extrapolation in ('EXP_POLY_LN_TAU2', 'EXP_POLY_LN_TAU3'): val = exp_horner_backwards_ln_tau(T, self.Tc, coeffs) elif extrapolation == 'interp1d': extrapolator = coeffs @@ -4407,7 +4407,7 @@ def extrapolate(self, T, method, in_range='error'): prop = self.interpolation_property_inv(prop) val = float(prop) else: - raise RuntimeError("Unknown extrapolation '%s'" %extrapolation) + raise RuntimeError("Unknown extrapolation '{}'".format(extrapolation)) if self._extrapolation_min is not None and val < self._extrapolation_min: val = self._extrapolation_min @@ -4487,7 +4487,7 @@ def extrapolate_derivative(self, T, method, order, in_range='error'): if order in (0, 1, 2, 3): A, B, C = coeffs return EQ106(T, self.Tc, A, B, C, order=order) - elif extrapolation == 'EXP_POLY_LN_TAU2' or extrapolation == 'EXP_POLY_LN_TAU3': + elif extrapolation in ('EXP_POLY_LN_TAU2', 'EXP_POLY_LN_TAU3'): if order == 1: return exp_horner_backwards_ln_tau_and_der(T, self.Tc, coeffs)[1] elif order == 2: @@ -4885,5 +4885,5 @@ def test_method_validity(self, T, method): Ts, properties = self.tabular_data[method] validity = Ts[0] < T < Ts[-1] else: - raise ValueError("method '%s' not valid" %method) + raise ValueError("method '{}' not valid".format(method)) return validity diff --git a/thermo/utils/tp_dependent_property.py b/thermo/utils/tp_dependent_property.py index 373da7d5..3df11855 100644 --- a/thermo/utils/tp_dependent_property.py +++ b/thermo/utils/tp_dependent_property.py @@ -413,7 +413,7 @@ def test_method_validity_P(self, T, P, method): Tmin, Tmax = self.T_limits[method] validity = Tmin < T < Tmax else: - raise ValueError("method '%s' not valid" %method) + raise ValueError("method '{}' not valid".format(method)) return validity def interpolate_P(self, T, P, name): From b80217c049d5be3b3aa54a150a2ca182bc5a754a Mon Sep 17 00:00:00 2001 From: Caleb Bell Date: Fri, 26 Jul 2024 14:10:53 -0600 Subject: [PATCH 5/9] More ruff --- thermo/__init__.py | 1 - thermo/coolprop.py | 6 ------ thermo/datasheet.py | 1 - thermo/flash/flash_utils.py | 1 - thermo/phases/coolprop_phase.py | 2 -- thermo/serialize.py | 1 - thermo/unifac.py | 1 - thermo/utils/functional.py | 1 - 8 files changed, 14 deletions(-) diff --git a/thermo/__init__.py b/thermo/__init__.py index d59b67b5..3d18a0a1 100644 --- a/thermo/__init__.py +++ b/thermo/__init__.py @@ -271,7 +271,6 @@ def complete_lazy_loading(): # pytest timings are hard to measure with lazy loading complete_lazy_loading() - global vectorized, numba, units, numba_vectorized if numerics.PY37: def __getattr__(name): global vectorized, numba, units, numba_vectorized diff --git a/thermo/coolprop.py b/thermo/coolprop.py index ef48bac1..930ecbc7 100644 --- a/thermo/coolprop.py +++ b/thermo/coolprop.py @@ -49,9 +49,6 @@ #has_CoolProp = False # For testing CPiP_min = 17 -global _PropsSI - -global _has_CoolProp _has_CoolProp = None @mark_numba_incompatible def has_CoolProp(): @@ -72,7 +69,6 @@ def PropsSI(*args, **kwargs): from CoolProp.CoolProp import PropsSI as _PropsSI return _PropsSI(*args, **kwargs) -global _HAPropsSI _HAPropsSI = None @mark_numba_incompatible def HAPropsSI(*args, **kwargs): @@ -81,7 +77,6 @@ def HAPropsSI(*args, **kwargs): from CoolProp.CoolProp import HAPropsSI as _HAPropsSI return _HAPropsSI(*args, **kwargs) -global _PhaseSI _PhaseSI = None @mark_numba_incompatible def PhaseSI(*args, **kwargs): @@ -90,7 +85,6 @@ def PhaseSI(*args, **kwargs): from CoolProp.CoolProp import PhaseSI as _PhaseSI return _PhaseSI(*args, **kwargs) -global _AbstractState _AbstractState = None @mark_numba_incompatible def AbstractState(*args, **kwargs): diff --git a/thermo/datasheet.py b/thermo/datasheet.py index 9ad73478..01961aaa 100644 --- a/thermo/datasheet.py +++ b/thermo/datasheet.py @@ -30,7 +30,6 @@ from thermo.chemical import Chemical -global pd pd = None def pandas(): global pd diff --git a/thermo/flash/flash_utils.py b/thermo/flash/flash_utils.py index e9fa6d35..78a43825 100644 --- a/thermo/flash/flash_utils.py +++ b/thermo/flash/flash_utils.py @@ -4492,7 +4492,6 @@ def S_model_l(T, P, zs): return val, info[0], info[1], info[2] -global cm_flash cm_flash = None def cm_flash_tol(): global cm_flash diff --git a/thermo/phases/coolprop_phase.py b/thermo/phases/coolprop_phase.py index 0a155f7a..4e22485f 100644 --- a/thermo/phases/coolprop_phase.py +++ b/thermo/phases/coolprop_phase.py @@ -33,8 +33,6 @@ SORTED_DICT = sys.version_info >= (3, 6) # Emperically measured to be ~140 KB/instance, do not want to cache too many - 35 is 5 MB max_CoolProp_states = 35 -global CoolProp -global CoolProp_constants_set CoolProp_constants_set = False def set_coolprop_constants(): global CPPT_INPUTS, CPrhoT_INPUTS, CPrhoP_INPUTS, CPiP, CPiT, CPiDmolar, CPiHmolar, CPiSmolar diff --git a/thermo/serialize.py b/thermo/serialize.py index 5beda833..e2a85e7f 100644 --- a/thermo/serialize.py +++ b/thermo/serialize.py @@ -171,7 +171,6 @@ def _load_json(): import json json_loaded = True -global json, orjson orjson = None if PY37: diff --git a/thermo/unifac.py b/thermo/unifac.py index 5b559989..0daa3f06 100644 --- a/thermo/unifac.py +++ b/thermo/unifac.py @@ -2498,7 +2498,6 @@ def priority_from_atoms(atoms, bonds=None): group.priority = priority_from_atoms(group.atoms, group.bonds) -global _unifac_ip_loaded _unifac_ip_loaded = False def load_unifac_ip(): global _unifac_ip_loaded, UFIP, LLEUFIP, LUFIP, DOUFIP2006, DOUFIP2016, NISTUFIP, NISTKTUFIP, PSRKIP, VTPRIP diff --git a/thermo/utils/functional.py b/thermo/utils/functional.py index 49df676c..bcd4d093 100644 --- a/thermo/utils/functional.py +++ b/thermo/utils/functional.py @@ -29,7 +29,6 @@ from fluids.numerics import assert_close, log, trunc_log from fluids.numerics import numpy as np -global _has_matplotlib _has_matplotlib = None def has_matplotlib(): global _has_matplotlib From 42ebf53d1d809f1ad8273dcfd990092a38d5a28d Mon Sep 17 00:00:00 2001 From: Caleb Bell Date: Fri, 26 Jul 2024 14:11:58 -0600 Subject: [PATCH 6/9] More ruff --- thermo/chemical.py | 8 ++-- thermo/chemical_package.py | 2 +- thermo/coolprop.py | 4 +- thermo/datasheet.py | 8 ++-- thermo/electrochem.py | 10 ++--- thermo/eos.py | 30 +++++++------- thermo/eos_mix.py | 2 +- thermo/equilibrium.py | 58 +++++++++++++-------------- thermo/flash/flash_base.py | 22 +++++----- thermo/flash/flash_pure_vls.py | 16 ++++---- thermo/flash/flash_utils.py | 8 ++-- thermo/nrtl.py | 4 +- thermo/phases/helmholtz_eos.py | 2 +- thermo/phases/phase.py | 2 +- thermo/stream.py | 10 ++--- thermo/test_utils.py | 2 +- thermo/unifac.py | 2 +- thermo/units.py | 4 +- thermo/utils/mixture_property.py | 14 +++---- thermo/utils/t_dependent_property.py | 36 ++++++++--------- thermo/utils/tp_dependent_property.py | 2 +- 21 files changed, 123 insertions(+), 123 deletions(-) diff --git a/thermo/chemical.py b/thermo/chemical.py index 8acf9346..926ad2c9 100644 --- a/thermo/chemical.py +++ b/thermo/chemical.py @@ -3249,15 +3249,15 @@ def Peclet_heat(self, V=None, D=None): # Add the functional groups def _make_getter_group(name): def get(self): - base_name = 'is_{}'.format(name) + base_name = f'is_{name}' ref = getattr(functional_groups, base_name) return ref(self.rdkitmol) return get for _name in group_names: getter = property(_make_getter_group(_name)) - name = 'is_{}'.format(_name) - _add_attrs_doc = r"""Method to return whether or not this chemical is in the category {}, [-] - """.format(_name) + name = f'is_{_name}' + _add_attrs_doc = rf"""Method to return whether or not this chemical is in the category {_name}, [-] + """ getter.__doc__ = _add_attrs_doc setattr(Chemical, name, getter) diff --git a/thermo/chemical_package.py b/thermo/chemical_package.py index edcf52c2..f52a1be1 100644 --- a/thermo/chemical_package.py +++ b/thermo/chemical_package.py @@ -1868,7 +1868,7 @@ def as_poly_fit(self, props=None): else: iter_props = self.pure_correlations - s = '{}('.format(self.__class__.__name__) + s = f'{self.__class__.__name__}(' s += 'constants=constants, skip_missing=True,\n' for prop in iter_props: prop_attr = getattr(self, prop) diff --git a/thermo/coolprop.py b/thermo/coolprop.py index 930ecbc7..2cd02c8b 100644 --- a/thermo/coolprop.py +++ b/thermo/coolprop.py @@ -224,7 +224,7 @@ def store_coolprop_fluids(): data = {CASRN: coolprop_fluids[CASRN].as_json() for CASRN in coolprop_dict} ver = CoolProp.__version__ - file = open(os.path.join(data_dir, 'CoolPropFluids{}.json'.format(ver)), 'w') + file = open(os.path.join(data_dir, f'CoolPropFluids{ver}.json'), 'w') json.dump(data, file) file.close() @@ -234,7 +234,7 @@ def load_coolprop_fluids(depth=0): import CoolProp ver = CoolProp.__version__ - pth = os.path.join(data_dir, 'CoolPropFluids{}.json'.format(ver)) + pth = os.path.join(data_dir, f'CoolPropFluids{ver}.json') try: file = open(pth) except: diff --git a/thermo/datasheet.py b/thermo/datasheet.py index 01961aaa..7a98537c 100644 --- a/thermo/datasheet.py +++ b/thermo/datasheet.py @@ -287,25 +287,25 @@ def tabulate_streams(names=None, *args, **kwargs): if kwargs.get('Mole flows', True): for i, CAS in enumerate(CASs): - s = 'Mole flow, mol/s {}'.format(IDs[CAS]) + s = f'Mole flow, mol/s {IDs[CAS]}' vals = [j[i] for j in mole_flows] dat[s] = vals if kwargs.get('Mass flows', True): for i, CAS in enumerate(CASs): - s = 'Mass flow, kg/s {}'.format(IDs[CAS]) + s = f'Mass flow, kg/s {IDs[CAS]}' vals = [j[i] for j in mass_flows] dat[s] = vals if kwargs.get('Mass fractions', True): for i, CAS in enumerate(CASs): - s = 'Mass fraction {}'.format(IDs[CAS]) + s = f'Mass fraction {IDs[CAS]}' vals = [j[i] for j in mass_fractions] dat[s] = vals if kwargs.get('Mole fractions', True): for i, CAS in enumerate(CASs): - s = 'Mole fraction {}'.format(IDs[CAS]) + s = f'Mole fraction {IDs[CAS]}' vals = [j[i] for j in mole_fractions] dat[s] = vals diff --git a/thermo/electrochem.py b/thermo/electrochem.py index 72f1df14..d03e716c 100644 --- a/thermo/electrochem.py +++ b/thermo/electrochem.py @@ -1487,9 +1487,9 @@ def ion_balance_adjust_wrapper(charges, zs, n_anions, n_cations, anion_zs, cation_zs, z_water = ion_balance_adjust_one(charges, zs, n_anions, n_cations, adjust=adjust) new_zi = cation_zs[cation_index] if positive else anion_zs[anion_index] if increase is True and new_zi < old_zi: - raise ValueError('Adjusting specified ion {} resulted in a decrease of its quantity but an increase was specified'.format(selected_ion.formula)) + raise ValueError(f'Adjusting specified ion {selected_ion.formula} resulted in a decrease of its quantity but an increase was specified') elif increase is False and new_zi > old_zi: - raise ValueError('Adjusting specified ion {} resulted in a increase of its quantity but an decrease was specified'.format(selected_ion.formula)) + raise ValueError(f'Adjusting specified ion {selected_ion.formula} resulted in a increase of its quantity but an decrease was specified') return anion_zs, cation_zs, z_water @@ -1497,7 +1497,7 @@ def ion_balance_adjust_one(charges, zs, n_anions, n_cations, adjust): main_tot = sum([zs[i]*charges[i] for i in range(len(charges)) if i != adjust]) zs[adjust] = -main_tot/charges[adjust] if zs[adjust] < 0: - raise ValueError('A negative value of {:f} ion mole fraction was required to balance the charge'.format(zs[adjust])) + raise ValueError(f'A negative value of {zs[adjust]:f} ion mole fraction was required to balance the charge') z_water = 1. - sum(zs[0:-1]) anion_zs = zs[0:n_anions] @@ -1528,7 +1528,7 @@ def ion_balance_dominant(impacts, balance_error, charges, zs, n_anions, else: adjust = impacts.index(min(impacts)) else: - raise ValueError('Allowable methods are {}'.format(charge_balance_methods)) + raise ValueError(f'Allowable methods are {charge_balance_methods}') return ion_balance_adjust_one(charges, zs, n_anions, n_cations, adjust) @@ -1563,7 +1563,7 @@ def ion_balance_proportional(anion_charges, cation_charges, zs, n_anions, multiplier = -cation_balance_error/anion_balance_error anion_zs = [i*multiplier for i in anion_zs] else: - raise Exception('Allowable methods are {}'.format(charge_balance_methods)) + raise Exception(f'Allowable methods are {charge_balance_methods}') z_water = 1. - sum(anion_zs) - sum(cation_zs) return anion_zs, cation_zs, z_water diff --git a/thermo/eos.py b/thermo/eos.py index 1d65c342..8def44f8 100644 --- a/thermo/eos.py +++ b/thermo/eos.py @@ -1131,7 +1131,7 @@ def solve(self, pure_a_alphas=True, only_l=False, only_g=False, full_alphas=True T = mp.mpf(T) self.P = float(R*T/(V-self.b) - self.a_alpha/(V*V + self.delta*V + self.epsilon)) if self.P <= 0.0: - raise ValueError("TV inputs result in negative pressure of {:f} Pa".format(self.P)) + raise ValueError(f"TV inputs result in negative pressure of {self.P:f} Pa") # self.P = R*self.T/(V-self.b) - self.a_alpha/(V*(V + self.delta) + self.epsilon) else: raise ValueError("Two specs are required") @@ -1263,7 +1263,7 @@ def set_from_PT(self, Vs, only_l=False, only_g=False): # Even in the case of three real roots, it is still the min/max that make sense print([self.T, self.P, b, self.delta, self.epsilon, self.a_alpha, 'coordinates of failure']) if self.multicomponent: - extra = ', zs is {}'.format(self.zs) + extra = f', zs is {self.zs}' else: extra = '' raise ValueError(f'No acceptable roots were found; the roots are {Vs!s}, T is {self.T!s} K, P is {self.P!s} Pa, a_alpha is {[self.a_alpha]!s}, b is {[self.b]!s}{extra}') @@ -2135,7 +2135,7 @@ def volume_errors(self, Tmin=1e-4, Tmax=1e4, Pmin=1e-2, Pmax=1e9, if timing: ax.set_title('Volume timings; max %.2e us' %(max_err*1e6)) else: - ax.set_title('Volume solution validation; max err {:.4e}'.format(max_err)) + ax.set_title(f'Volume solution validation; max err {max_err:.4e}') if show: plt.show() @@ -2323,7 +2323,7 @@ def PT_surface_special(self, Tmin=1e-4, Tmax=1e4, Pmin=1e-2, Pmax=1e9, norm = LogNorm() if base_positive else None im = ax.pcolormesh(X, Y, z, cmap=color_map, norm=norm) cbar = fig.colorbar(im, ax=ax) - cbar.set_label('{}'.format(base_property)) + cbar.set_label(f'{base_property}') if Psat: plt.plot(Ts_Psats, Psats, label='Psat') @@ -2349,7 +2349,7 @@ def PT_surface_special(self, Tmin=1e-4, Tmax=1e4, Pmin=1e-2, Pmax=1e9, plt.legend() - ax.set_title('{} vs minimum Gibbs validation'.format(base_property)) + ax.set_title(f'{base_property} vs minimum Gibbs validation') if show: plt.show() @@ -2453,10 +2453,10 @@ def saturation_prop_plot(self, prop, Tmin=None, Tmax=None, pts=100, plt.plot(Ts, props) ax.set_xlabel('Temperature [K]') - ax.set_ylabel(r'{}'.format(prop)) + ax.set_ylabel(rf'{prop}') - ax.set_title(r'Saturation {} curve'.format(prop)) + ax.set_title(rf'Saturation {prop} curve') if show: plt.show() @@ -2546,14 +2546,14 @@ def Psat_errors(self, Tmin=None, Tmax=None, pts=50, plot=False, show=False, # Trust the fit - do not continue if no good continue except Exception as e: - raise ValueError("Failed to converge at {:.16f} K with unexpected error".format(T), e, self) + raise ValueError(f"Failed to converge at {T:.16f} K with unexpected error", e, self) try: Psat_polished = self.Psat(T, polish=True) Psats_num.append(Psat_polished) except Exception as e: failed = True - raise ValueError("Failed to converge at {:.16f} K with unexpected error".format(T), e, self) + raise ValueError(f"Failed to converge at {T:.16f} K with unexpected error", e, self) Ts_worked.append(T) Ts = Ts_worked @@ -2590,7 +2590,7 @@ def Psat_errors(self, Tmin=None, Tmax=None, pts=50, plot=False, show=False, if trunc_err_high is not None and max_err > trunc_err_high: max_err = trunc_err_high - ax1.set_title('Vapor pressure validation; max rel err {:.4e}'.format(max_err)) + ax1.set_title(f'Vapor pressure validation; max rel err {max_err:.4e}') if show: plt.show() @@ -2924,7 +2924,7 @@ def Psat(self, T, polish=False, guess=None): Psat_ranges_low = self.Psat_ranges_low if x > Psat_ranges_low[-1]: if not polish: - raise NoSolutionError("T {:.8f} K is too low for equations to converge".format(T)) + raise NoSolutionError(f"T {T:.8f} K is too low for equations to converge") else: # Needs to still be here for generating better data x = Psat_ranges_low[-1] @@ -2943,7 +2943,7 @@ def Psat(self, T, polish=False, guess=None): if polish: Psat = 1e-100 else: - raise NoSolutionError("T {:.8f} K is too low for equations to converge".format(T)) + raise NoSolutionError(f"T {T:.8f} K is too low for equations to converge") except OverflowError: # coefficients sometimes overflow before T is lowered to 0.32Tr # For @@ -3074,7 +3074,7 @@ def to_solve_bisect(P): converged = False if not converged: - raise ValueError("Could not converge at T={:.6f} K".format(T)) + raise ValueError(f"Could not converge at T={T:.6f} K") return Psat @@ -3160,7 +3160,7 @@ def dPsat_dT(self, T, polish=False, also_Psat=False): Psat_ranges_low = self.Psat_ranges_low x = alpha/Tr - 1. if x > Psat_ranges_low[-1]: - raise NoSolutionError("T {:.8f} K is too low for equations to converge".format(T)) + raise NoSolutionError(f"T {T:.8f} K is too low for equations to converge") for i in range(len(Psat_ranges_low)): if x < Psat_ranges_low[i]: @@ -10035,7 +10035,7 @@ def solve_T(self, P, V, solution=None): x30 = b*x12 T_calc = -Tc*(2.*a*m*x9*(V*x21*x21*x21*(V + b)*(P*x2 + P*x7 + x17 + x18 + x22 + x23 - x24))**0.5*(m + 1.) - x20*x21*(-P*x16*x6 + x1*x22 + x10*x26 + x13*x28 - x13*x30 + x15*x23 + x15*x24 + x19*x26 + x22*x3 + x25*x5 + x25 + x27*x5 + x27 + x28*x29 + x28*x5 - x29*x30 - x30*x5))/(x20*x9) if abs(T_calc.imag) > 1e-12: - raise ValueError("Calculated imaginary temperature {}".format(T_calc)) + raise ValueError(f"Calculated imaginary temperature {T_calc}") return T_calc else: return Tc*(-2*a*m*sqrt(V*(V - b)**3*(V + b)*(P*R*Tc*V**2 + P*R*Tc*V*b - P*V*a*m**2 + P*a*b*m**2 + R*Tc*a*m**2 + 2*R*Tc*a*m + R*Tc*a))*(m + 1)*(R*Tc*V**2 + R*Tc*V*b - V*a*m**2 + a*b*m**2)**2 + (V - b)*(R**2*Tc**2*V**4 + 2*R**2*Tc**2*V**3*b + R**2*Tc**2*V**2*b**2 - 2*R*Tc*V**3*a*m**2 + 2*R*Tc*V*a*b**2*m**2 + V**2*a**2*m**4 - 2*V*a**2*b*m**4 + a**2*b**2*m**4)*(P*R*Tc*V**4 + 2*P*R*Tc*V**3*b + P*R*Tc*V**2*b**2 - P*V**3*a*m**2 + P*V*a*b**2*m**2 + R*Tc*V**2*a*m**2 + 2*R*Tc*V**2*a*m + R*Tc*V**2*a + R*Tc*V*a*b*m**2 + 2*R*Tc*V*a*b*m + R*Tc*V*a*b + V*a**2*m**4 + 2*V*a**2*m**3 + V*a**2*m**2 - a**2*b*m**4 - 2*a**2*b*m**3 - a**2*b*m**2))/((R*Tc*V**2 + R*Tc*V*b - V*a*m**2 + a*b*m**2)**2*(R**2*Tc**2*V**4 + 2*R**2*Tc**2*V**3*b + R**2*Tc**2*V**2*b**2 - 2*R*Tc*V**3*a*m**2 + 2*R*Tc*V*a*b**2*m**2 + V**2*a**2*m**4 - 2*V*a**2*b*m**4 + a**2*b**2*m**4)) diff --git a/thermo/eos_mix.py b/thermo/eos_mix.py index a688d039..a2b517e1 100644 --- a/thermo/eos_mix.py +++ b/thermo/eos_mix.py @@ -415,7 +415,7 @@ def __repr__(self): for k, v in self.kwargs.items(): s += f'{k}={v!r}, ' - s += 'zs={}, '.format(repr(self.zs)) + s += f'zs={repr(self.zs)}, ' if hasattr(self, 'no_T_spec') and self.no_T_spec: s += f'P={self.P!r}, V={self.V!r}' elif self.V is not None: diff --git a/thermo/equilibrium.py b/thermo/equilibrium.py index 8311a20e..efbe70b0 100644 --- a/thermo/equilibrium.py +++ b/thermo/equilibrium.py @@ -250,9 +250,9 @@ def __str__(self): def __repr__(self): s = f'{self.__class__.__name__}(T={self.T}, P={self.P}, zs={self.zs}, betas={self.betas}' - s += ', gas={}'.format(self.gas.__repr__()) - s += ', liquids={}'.format(self.liquids.__repr__()) - s += ', solids={}'.format(self.solids.__repr__()) + s += f', gas={self.gas.__repr__()}' + s += f', liquids={self.liquids.__repr__()}' + s += f', solids={self.solids.__repr__()}' s += ')' return s @@ -3265,8 +3265,8 @@ def _make_getter_correlations(name): def get_correlation(self): return getattr(self.correlations, name) - text = """Wrapper to obtain the list of {} objects of the associated -:obj:`PropertyCorrelationsPackage `.""".format(name) + text = f"""Wrapper to obtain the list of {name} objects of the associated +:obj:`PropertyCorrelationsPackage `.""" try: get_correlation.__doc__ = text except: @@ -3490,11 +3490,11 @@ def get_atom_fraction(self): for ele in periodic_table: getter = _make_getter_atom_fraction(ele.symbol) - name = '{}_atom_fraction'.format(ele.name) + name = f'{ele.name}_atom_fraction' - _add_attrs_doc = r"""Method to calculate and return the mole fraction that - is {} element, [-] - """.format(ele.name) + _add_attrs_doc = rf"""Method to calculate and return the mole fraction that + is {ele.name} element, [-] + """ getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3514,11 +3514,11 @@ def get_atom_mass_fraction(self): return get_atom_mass_fraction for ele in periodic_table: getter = _make_getter_atom_mass_fraction(ele.symbol) - name = '{}_atom_mass_fraction'.format(ele.name) + name = f'{ele.name}_atom_mass_fraction' - _add_attrs_doc = r"""Method to calculate and return the mass fraction of the phase - that is {} element, [-] - """.format(ele.name) + _add_attrs_doc = rf"""Method to calculate and return the mass fraction of the phase + that is {ele.name} element, [-] + """ getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3538,11 +3538,11 @@ def get_atom_mass_flow(self): for ele in periodic_table: getter = _make_getter_atom_mass_flow(ele.symbol) - name = '{}_atom_mass_flow'.format(ele.name) + name = f'{ele.name}_atom_mass_flow' - _add_attrs_doc = r"""Method to calculate and return the mass flow of atoms - that are {} element, [kg/s] - """.format(ele.name) + _add_attrs_doc = rf"""Method to calculate and return the mass flow of atoms + that are {ele.name} element, [kg/s] + """ getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3562,11 +3562,11 @@ def get_atom_flow(self): for ele in periodic_table: getter = _make_getter_atom_flow(ele.symbol) - name = '{}_atom_flow'.format(ele.name) + name = f'{ele.name}_atom_flow' - _add_attrs_doc = r"""Method to calculate and return the mole flow that is - {}, [mol/s] - """.format(ele.name) + _add_attrs_doc = rf"""Method to calculate and return the mole flow that is + {ele.name}, [mol/s] + """ getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3586,11 +3586,11 @@ def get_atom_count_flow(self): for ele in periodic_table: getter = _make_getter_atom_count_flow(ele.symbol) - name = '{}_atom_count_flow'.format(ele.name) + name = f'{ele.name}_atom_count_flow' - _add_attrs_doc = r"""Method to calculate and return the number of atoms in the - flow which are {}, [atoms/s] - """.format(ele.name) + _add_attrs_doc = rf"""Method to calculate and return the number of atoms in the + flow which are {ele.name}, [atoms/s] + """ getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3618,10 +3618,10 @@ def get(self): return get for _name, _CAS in _comonent_specific_properties.items(): getter = _make_getter_partial_pressure(_CAS) - name = '{}_partial_pressure'.format(_name) + name = f'{_name}_partial_pressure' - _add_attrs_doc = r"""Method to calculate and return the ideal partial pressure of {}, [Pa] - """.format(_name) + _add_attrs_doc = rf"""Method to calculate and return the ideal partial pressure of {_name}, [Pa] + """ getter.__doc__ = _add_attrs_doc setattr(EquilibriumState, name, getter) setattr(Phase, name, getter) @@ -3640,7 +3640,7 @@ def get(self): for _name, _CAS in _comonent_specific_properties.items(): getter = _make_getter_component_molar_weight(_CAS) - name = '{}_molar_weight'.format(_name) + name = f'{_name}_molar_weight' _add_attrs_doc = rf"""Method to calculate and return the effective quantiy of {_name} in the phase as a molar weight, [g/mol]. diff --git a/thermo/flash/flash_base.py b/thermo/flash/flash_base.py index 0c6ae8e2..a34a01f9 100644 --- a/thermo/flash/flash_base.py +++ b/thermo/flash/flash_base.py @@ -1355,7 +1355,7 @@ def debug_PT(self, zs, Pmin=None, Pmax=None, Tmin=None, Tmax=None, pts=50, if len(zs) > 4: zs = '...' - plt.title('PT system flashes, zs={}'.format(zs)) + plt.title(f'PT system flashes, zs={zs}') if show: plt.show() else: @@ -1467,10 +1467,10 @@ def plot_TP(self, zs, Tmin=None, Tmax=None, pts=50, branches=None, plt.semilogy(Ts, P_bubbles, label='TP bubble point curve') plt.xlabel('System temperature, K') plt.ylabel('System pressure, Pa') - plt.title('PT system curve, zs={}'.format(zs)) + plt.title(f'PT system curve, zs={zs}') if branch: for VF, Ps in zip(branches, branch_Ps): - plt.semilogy(Ts, Ps, label='TP curve for VF={}'.format(VF)) + plt.semilogy(Ts, Ps, label=f'TP curve for VF={VF}') plt.legend(loc='best') if show: plt.show() @@ -1583,10 +1583,10 @@ def plot_PT(self, zs, Pmin=None, Pmax=None, pts=50, branches=[], plt.plot(Ps, T_bubbles, label='PT bubble point curve') plt.xlabel('System pressure, Pa') plt.ylabel('System temperature, K') - plt.title('PT system curve, zs={}'.format(zs)) + plt.title(f'PT system curve, zs={zs}') if branch: for VF, Ts in zip(branches, branch_Ts): - plt.plot(Ps, Ts, label='PT curve for VF={}'.format(VF)) + plt.plot(Ps, Ts, label=f'PT curve for VF={VF}') plt.legend(loc='best') if show: @@ -1682,9 +1682,9 @@ def bubble_at_zs(zs): cb.update_ticks() # plt.tight_layout() if is_T_spec: - text = "Bubble pressure vs composition (left) and dew pressure vs composition (right) at {} K".format(T) + text = f"Bubble pressure vs composition (left) and dew pressure vs composition (right) at {T} K" else: - text = "Bubble temperature vs composition (left) and dew temperature vs composition (right) at {} Pa".format(P) + text = f"Bubble temperature vs composition (left) and dew temperature vs composition (right) at {P} Pa" fig.suptitle(text, fontsize=14) fig.subplots_adjust(top=0.85) plt.show() @@ -1757,7 +1757,7 @@ def plot_Txy(self, P, pts=30, ignore_errors=True, values=False, show=True): # pr import matplotlib.pyplot as plt fig, ax = plt.subplots() names = self.constants.aliases - plt.title('Txy diagram at P={} Pa'.format(P)) + plt.title(f'Txy diagram at P={P} Pa') plt.plot(z1, Ts_dew, label='Dew temperature, K') plt.plot(z1, Ts_bubble, label='Bubble temperature, K') plt.xlabel(f'Mole fraction {names[0]}') @@ -1836,7 +1836,7 @@ def plot_Pxy(self, T, pts=30, ignore_errors=True, values=False, show=True): # pr import matplotlib.pyplot as plt fig, ax = plt.subplots() - plt.title('Pxy diagram at T={} K'.format(T)) + plt.title(f'Pxy diagram at T={T} K') plt.plot(z1, Ps_dew, label='Dew pressure') plt.plot(z1, Ps_bubble, label='Bubble pressure') plt.xlabel(f'Mole fraction {names[0]}') @@ -1912,9 +1912,9 @@ def plot_xy(self, P=None, T=None, pts=30, ignore_errors=True, values=False, import matplotlib.pyplot as plt fig, ax = plt.subplots() if T is not None: - plt.title('xy diagram at T={} K (varying P)'.format(T)) + plt.title(f'xy diagram at T={T} K (varying P)') else: - plt.title('xy diagram at P={} Pa (varying T)'.format(P)) + plt.title(f'xy diagram at P={P} Pa (varying T)') names = self.constants.aliases plt.xlabel(f'Liquid mole fraction {names[0]}') plt.ylabel(f'Vapor mole fraction {names[0]}') diff --git a/thermo/flash/flash_pure_vls.py b/thermo/flash/flash_pure_vls.py index ba064516..3f571776 100644 --- a/thermo/flash/flash_pure_vls.py +++ b/thermo/flash/flash_pure_vls.py @@ -349,7 +349,7 @@ def flash_TPV(self, T, P, V, zs=None, solution=None, hot_start=None): elif callable(solution): fun = solution else: - raise ValueError("Did not recognize solution {}".format(solution)) + raise ValueError(f"Did not recognize solution {solution}") if self.phase_count == 1: phase = self.phases[0].to(zs=zs, T=T, P=P, V=V) @@ -950,7 +950,7 @@ def selection_fun_1P(new, prev): if S_min_spec <= spec_val <= S_max_spec: had_solution = True if had_solution: - raise UnconvergedError("Could not converge but solution detected in bounds: {}".format(s)) + raise UnconvergedError(f"Could not converge but solution detected in bounds: {s}") elif uncertain_solution: raise UnconvergedError("Could not converge and unable to detect if solution detected in bounds") else: @@ -1126,8 +1126,8 @@ def flash_VF_HSGUA(self, fixed_var_val, spec_val, fixed_var='VF', spec_var='H', dfug_dT_idx = props.index('dfugacity_dT') dfug_dP_idx = props.index('dfugacity_dP') - dspec_dT_var = 'd{}_dT'.format(spec_var) - dspec_dP_var = 'd{}_dP'.format(spec_var) + dspec_dT_var = f'd{spec_var}_dT' + dspec_dP_var = f'd{spec_var}_dP' dspec_dT_idx = props.index(dspec_dT_var) dspec_dP_idx = props.index(dspec_dP_var) @@ -1256,8 +1256,8 @@ def flash_VF_HSGUA(self, fixed_var_val, spec_val, fixed_var='VF', spec_var='H', return self.flash_VF_HSGUA_bounded(T_guess, T_low, T_high, fixed_var_val, spec_val, fixed_var=fixed_var, spec_var=spec_var) def _VF_HSGUA_der_root(self, guess, low, high, fixed_var_val, spec_val, fixed_var='VF', spec_var='H'): - dspec_dT_var = 'd{}_dT'.format(spec_var) - dspec_dP_var = 'd{}_dP'.format(spec_var) + dspec_dT_var = f'd{spec_var}_dT' + dspec_dP_var = f'd{spec_var}_dP' VF = fixed_var_val val_cache = [None, 0] @@ -1291,8 +1291,8 @@ def to_solve(T): return T_zero, val_cache[0] def flash_VF_HSGUA_bounded(self, guess, low, high, fixed_var_val, spec_val, fixed_var='VF', spec_var='H'): - dspec_dT_var = 'd{}_dT'.format(spec_var) - dspec_dP_var = 'd{}_dP'.format(spec_var) + dspec_dT_var = f'd{spec_var}_dT' + dspec_dP_var = f'd{spec_var}_dP' VF = fixed_var_val cache = [0] diff --git a/thermo/flash/flash_utils.py b/thermo/flash/flash_utils.py index 78a43825..a40d9b32 100644 --- a/thermo/flash/flash_utils.py +++ b/thermo/flash/flash_utils.py @@ -845,7 +845,7 @@ def nonlin_spec_NP(guess, fixed_val, spec_val, zs, compositions_guesses, betas_g dspec_diter_s = f'd{spec}_d{iter_var}' dspec_diter_callables = [getattr(phase.__class__, dspec_diter_s) for phase in phases] - dspec_dn_s = 'd{}_dns'.format(spec) + dspec_dn_s = f'd{spec}_dns' dspec_dn_callables = [getattr(phase.__class__, dspec_dn_s) for phase in phases] jac = True @@ -1826,7 +1826,7 @@ def dew_bubble_newton_zs(guess, fixed_val, zs, liquid_phase, gas_phase, for i in cmps: JN[i] = -comp_factor - s = 'dlnphis_d{}'.format(iter_var) + s = f'dlnphis_d{iter_var}' dlnphis_diter_var_iter = getattr(iter_phase.__class__, s) dlnphis_diter_var_const = getattr(const_phase.__class__, s) dlnphis_dzs = iter_phase.__class__.dlnphis_dzs @@ -1996,7 +1996,7 @@ def dew_bubble_Michelsen_Mollerup(guess, fixed_val, zs, liquid_phase, gas_phase, else: iter_msg, const_msg = g_undefined_P_msg, l_undefined_P_msg - s = 'dlnphis_d{}'.format(iter_var) + s = f'dlnphis_d{iter_var}' dlnphis_diter_var_iter = getattr(iter_phase.__class__, s) dlnphis_diter_var_const = getattr(const_phase.__class__, s) @@ -2166,7 +2166,7 @@ def existence_3P_Michelsen_Mollerup(guess, fixed_val, zs, iter_phase, liquid0, l elif iter_var == 'P': iter_msg, const_msg = g_undefined_P_msg, l_undefined_P_msg - s = 'dlnphis_d{}'.format(iter_var) + s = f'dlnphis_d{iter_var}' dlnphis_diter_var_iter = getattr(iter_phase.__class__, s) dlnphis_diter_var_liquid0 = getattr(liquid0.__class__, s) # dlnphis_diter_var_liquid1 = getattr(liquid1.__class__, s) diff --git a/thermo/nrtl.py b/thermo/nrtl.py index 549e73dd..3fa46ce6 100644 --- a/thermo/nrtl.py +++ b/thermo/nrtl.py @@ -738,9 +738,9 @@ def __repr__(self): for i, attr in enumerate(self._model_attributes[:6]): if self.tau_coeffs_nonzero[i]: s += f', {attr}={getattr(self, attr)}' - s += ', alpha_cs={}'.format(self.alpha_cs) + s += f', alpha_cs={self.alpha_cs}' if not self.alpha_temperature_independent: - s += ', alpha_ds={}'.format(self.alpha_ds) + s += f', alpha_ds={self.alpha_ds}' s += ')' return s diff --git a/thermo/phases/helmholtz_eos.py b/thermo/phases/helmholtz_eos.py index cca0a62f..51ec5879 100644 --- a/thermo/phases/helmholtz_eos.py +++ b/thermo/phases/helmholtz_eos.py @@ -50,7 +50,7 @@ def __repr__(self): >>> phase IAPWS95Gas(T=300, P=100000.0, zs=[1.0]) ''' - base = '{}('.format(self.__class__.__name__) + base = f'{self.__class__.__name__}(' iter_props = ('Hfs', 'Gfs', 'Sfs', 'T', 'P', 'zs') if self.__class__.__name__ not in ('IAPWS95Gas', 'IAPWS95Liquid') else ('T', 'P', 'zs') for s in iter_props: if hasattr(self, s) and getattr(self, s) is not None: diff --git a/thermo/phases/phase.py b/thermo/phases/phase.py index e762a942..ef8799d8 100644 --- a/thermo/phases/phase.py +++ b/thermo/phases/phase.py @@ -184,7 +184,7 @@ def __init_subclass__(cls): __full_path__ = None def __str__(self): - s = '<{}, '.format(self.__class__.__name__) + s = f'<{self.__class__.__name__}, ' try: s += f'T={self.T:g} K, P={self.P:g} Pa' except: diff --git a/thermo/stream.py b/thermo/stream.py index f985ecd6..27cf8e74 100644 --- a/thermo/stream.py +++ b/thermo/stream.py @@ -2409,8 +2409,8 @@ def __sub__(self, other): if not all(components_in_self): for i, in_self in enumerate(components_in_self): if not in_self and other.zs[i] > 0: - raise Exception('Not all components to be removed are \ -present in the first stream; {} is not present.'.format(other.IDs[i])) + raise Exception(f'Not all components to be removed are \ +present in the first stream; {other.IDs[i]} is not present.') # Calculate the mole flows of each species ns_self = list(self.ns) @@ -2425,8 +2425,8 @@ def __sub__(self, other): relative_difference_product = abs(ns_self[i] - nj)/n_product relative_difference_self = abs(ns_self[i] - nj)/ns_self[i] if ns_self[i] - nj < 0 and (relative_difference_product > 1E-12 or relative_difference_self > 1E-9): - raise Exception('Attempting to remove more {} than is in the \ -first stream.'.format(self.IDs[i])) + raise Exception(f'Attempting to remove more {self.IDs[i]} than is in the \ +first stream.') if ns_self[i] - nj < 0.: ns_self[i] = 0. elif relative_difference_product < 1E-12: @@ -2583,7 +2583,7 @@ class EquilibriumStream(EquilibriumState): def __repr__(self): flow_spec, flow_spec_val = self.flow_spec - s = '{}({}={}, '.format(self.__class__.__name__, flow_spec, flow_spec_val) + s = f'{self.__class__.__name__}({flow_spec}={flow_spec_val}, ' s += 'flasher=flasher' s += ', existing_flash={}'.format(EquilibriumState.__repr__(self).replace('EquilibriumStream', 'EquilibriumState')) s += ')' diff --git a/thermo/test_utils.py b/thermo/test_utils.py index e08a9aa3..1bb752b0 100644 --- a/thermo/test_utils.py +++ b/thermo/test_utils.py @@ -107,5 +107,5 @@ def mark_plot_unsupported(plot_fig, reason, color='r'): def flash_rounding(x): if isinstance(x, float): - return float('{:.10e}'.format(x)) + return float(f'{x:.10e}') return x diff --git a/thermo/unifac.py b/thermo/unifac.py index 0daa3f06..233fe5fb 100644 --- a/thermo/unifac.py +++ b/thermo/unifac.py @@ -168,7 +168,7 @@ class UNIFAC_subgroup: 'priority', 'atoms', 'bonds'] def __repr__(self): # pragma: no cover - return '<{}>'.format(self.group) + return f'<{self.group}>' def __init__(self, group_id, group, main_group_id, main_group, R, Q, smarts=None, priority=None, atoms=None, bonds=None, hydrogen_from_smarts=False): diff --git a/thermo/units.py b/thermo/units.py index 3baeecb6..fea3f901 100644 --- a/thermo/units.py +++ b/thermo/units.py @@ -62,8 +62,8 @@ obj = wrap_numpydoc_obj(obj) except Exception as e: failed_wrapping = True - print('Current implementation of {} contains documentation not ' - 'parseable and cound not be wrapped to use pint:'.format(str(obj))) + print(f'Current implementation of {str(obj)} contains documentation not ' + 'parseable and cound not be wrapped to use pint:') print(e) elif isinstance(obj, str): continue diff --git a/thermo/utils/mixture_property.py b/thermo/utils/mixture_property.py index d48f7202..e9be69ad 100644 --- a/thermo/utils/mixture_property.py +++ b/thermo/utils/mixture_property.py @@ -70,14 +70,14 @@ def __init_subclass__(cls): def __repr__(self): clsname = self.__class__.__name__ - base = '{}('.format(clsname) + base = f'{clsname}(' for k in self.custom_args: v = getattr(self, k) if v is not None: base += f'{k}={v}, ' - base += 'CASs={}, '.format(self.CASs) - base += 'correct_pressure_pure={}, '.format(self._correct_pressure_pure) - base += 'method="{}", '.format(self.method) + base += f'CASs={self.CASs}, ' + base += f'correct_pressure_pure={self._correct_pressure_pure}, ' + base += f'method="{self.method}", ' for attr in self.pure_references: base += f'{attr}={getattr(self, attr)}, ' @@ -232,7 +232,7 @@ def calculate(self, T, P, zs, ws, method): excess = redlich_kister_excess_inner(N_T, N_terms, Ais_matrix_for_calc, zs) base_property = mixing_simple(zs, pure_props) return base_property + excess - raise ValueError("Unknown method; methods are {}".format(self.all_methods)) + raise ValueError(f"Unknown method; methods are {self.all_methods}") def calculate_pures_corrected(self, T, P, fallback=False, objs=None): if self._correct_pressure_pure: @@ -932,10 +932,10 @@ def plot_isobaric_isothermal(self, T, P, methods=[], pts=50, only_valid=True, xs_plot.append(x0) except: pass - plt.plot(xs_plot, properties, label=method + ' at {:g} K and {:g} Pa'.format(T, P) ) + plt.plot(xs_plot, properties, label=method + f' at {T:g} K and {P:g} Pa' ) else: properties = [func(T, P, [x0, 1.0 - x0], None, method) for x0 in xs] - plt.plot(xs, properties, label=method + ' at {:g} K and {:g} Pa'.format(T, P)) + plt.plot(xs, properties, label=method + f' at {T:g} K and {P:g} Pa') plt.legend(loc='best') plt.ylabel(prop_name + ', ' + self.units) plt.xlabel('Mole fraction x0') diff --git a/thermo/utils/t_dependent_property.py b/thermo/utils/t_dependent_property.py index 807e5e0b..e69adad9 100644 --- a/thermo/utils/t_dependent_property.py +++ b/thermo/utils/t_dependent_property.py @@ -1490,9 +1490,9 @@ def __repr__(self): def as_string(self, tabular=True, references=True, json_parameters=False): clsname = self.__class__.__name__ - base = '{}('.format(clsname) + base = f'{clsname}(' if self.CASRN: - base += 'CASRN="{}", '.format(self.CASRN) + base += f'CASRN="{self.CASRN}", ' for k in self.custom_args: v = getattr(self, k) if v is not None: @@ -1500,29 +1500,29 @@ def as_string(self, tabular=True, references=True, json_parameters=False): continue base += f'{k}={v}, ' - extrap_str = '"{}"'.format(self.extrapolation) if self.extrapolation is not None else 'None' - base += 'extrapolation={}, '.format(extrap_str) + extrap_str = f'"{self.extrapolation}"' if self.extrapolation is not None else 'None' + base += f'extrapolation={extrap_str}, ' if self._extrapolation_min != self.DEFAULT_EXTRAPOLATION_MIN: - extrap_str = '{}'.format(self._extrapolation_min) if self._extrapolation_min is not None else 'None' - base += 'extrapolation_min={}, '.format(extrap_str) + extrap_str = f'{self._extrapolation_min}' if self._extrapolation_min is not None else 'None' + base += f'extrapolation_min={extrap_str}, ' if self._extrapolation_max != self.DEFAULT_EXTRAPOLATION_MAX: - extrap_str = '{}'.format(self._extrapolation_max) if self._extrapolation_max is not None else 'None' - base += 'extrapolation_max={}, '.format(extrap_str) + extrap_str = f'{self._extrapolation_max}' if self._extrapolation_max is not None else 'None' + base += f'extrapolation_max={extrap_str}, ' - method_str = '"{}"'.format(self.method) if self.method is not None else 'None' - base += 'method={}, '.format(method_str) + method_str = f'"{self.method}"' if self.method is not None else 'None' + base += f'method={method_str}, ' if self.tabular_data and tabular: if not (len(self.tabular_data) == 1 and VDI_TABULAR in self.tabular_data): - base += 'tabular_data={}, '.format(self.tabular_data) + base += f'tabular_data={self.tabular_data}, ' if self.P_dependent: - method_P_str = '"{}"'.format(self.method_P) if self.method_P is not None else 'None' - base += 'method_P={}, '.format(method_P_str) + method_P_str = f'"{self.method_P}"' if self.method_P is not None else 'None' + base += f'method_P={method_P_str}, ' if self.tabular_data_P and tabular: - base += 'tabular_data_P={}, '.format(self.tabular_data_P) + base += f'tabular_data_P={self.tabular_data_P}, ' if 'tabular_extrapolation_permitted' in self.__dict__ and tabular: - base += 'tabular_extrapolation_permitted={}, '.format(self.tabular_extrapolation_permitted) + base += f'tabular_extrapolation_permitted={self.tabular_extrapolation_permitted}, ' if hasattr(self, 'poly_fit_Tmin') and self.poly_fit_Tmin is not None: @@ -2775,7 +2775,7 @@ def _base_calculate(self, T, method): return self.calculate(T, a_method) return self.calculate(T, method_names[-1]) else: - raise ValueError("Unknown method; methods are {}".format(self.all_methods)) + raise ValueError(f"Unknown method; methods are {self.all_methods}") def _base_calculate_P(self, T, P, method): if method in self.tabular_data_P: @@ -4407,7 +4407,7 @@ def extrapolate(self, T, method, in_range='error'): prop = self.interpolation_property_inv(prop) val = float(prop) else: - raise RuntimeError("Unknown extrapolation '{}'".format(extrapolation)) + raise RuntimeError(f"Unknown extrapolation '{extrapolation}'") if self._extrapolation_min is not None and val < self._extrapolation_min: val = self._extrapolation_min @@ -4885,5 +4885,5 @@ def test_method_validity(self, T, method): Ts, properties = self.tabular_data[method] validity = Ts[0] < T < Ts[-1] else: - raise ValueError("method '{}' not valid".format(method)) + raise ValueError(f"method '{method}' not valid") return validity diff --git a/thermo/utils/tp_dependent_property.py b/thermo/utils/tp_dependent_property.py index 3df11855..eadd5b06 100644 --- a/thermo/utils/tp_dependent_property.py +++ b/thermo/utils/tp_dependent_property.py @@ -413,7 +413,7 @@ def test_method_validity_P(self, T, P, method): Tmin, Tmax = self.T_limits[method] validity = Tmin < T < Tmax else: - raise ValueError("method '{}' not valid".format(method)) + raise ValueError(f"method '{method}' not valid") return validity def interpolate_P(self, T, P, name): From bef69b0120256da6d2442f54a3fd3f2d0392f08c Mon Sep 17 00:00:00 2001 From: Caleb Bell Date: Fri, 26 Jul 2024 14:20:37 -0600 Subject: [PATCH 7/9] More ruff --- thermo/activity.py | 1 - thermo/bulk.py | 2 +- thermo/chemical.py | 2 +- thermo/chemical_package.py | 2 +- thermo/chemical_utils.py | 2 +- thermo/coolprop.py | 1 - thermo/eos.py | 1 - thermo/eos_mix.py | 3 +-- thermo/equilibrium.py | 4 ++-- thermo/fitting.py | 4 +--- thermo/flash/flash_base.py | 4 ++-- thermo/flash/flash_utils.py | 2 +- thermo/flash/flash_vl.py | 4 +--- thermo/functional_groups.py | 4 +--- thermo/interface.py | 2 +- thermo/phases/ceos.py | 2 +- thermo/phases/gibbs_eos.py | 3 ++- thermo/phases/gibbs_excess.py | 1 - thermo/phases/iapws_phase.py | 2 +- thermo/phases/phase.py | 6 ++--- thermo/redlich_kister.py | 2 +- thermo/serialize.py | 2 +- thermo/stream.py | 34 +++++++++++----------------- thermo/thermal_conductivity.py | 2 +- thermo/utils/mixture_property.py | 7 ++---- thermo/utils/t_dependent_property.py | 6 ++--- thermo/viscosity.py | 4 ++-- 27 files changed, 42 insertions(+), 67 deletions(-) diff --git a/thermo/activity.py b/thermo/activity.py index 396c3b1f..a9efd73f 100644 --- a/thermo/activity.py +++ b/thermo/activity.py @@ -72,7 +72,6 @@ from fluids.numerics import exp, log, trunc_exp, derivative, jacobian, hessian from fluids.numerics import numpy as np -from thermo import serialize from thermo.fitting import fit_customized from thermo.serialize import JsonOptEncodable diff --git a/thermo/bulk.py b/thermo/bulk.py index ce4bda27..24d51fe8 100644 --- a/thermo/bulk.py +++ b/thermo/bulk.py @@ -77,7 +77,7 @@ from fluids.constants import R, atm from fluids.numerics import exp, log, sqrt from fluids.two_phase_voidage import gas_liquid_viscosity -from thermo.serialize import arrays_to_lists, JsonOptEncodable, object_lookups +from thermo.serialize import JsonOptEncodable, object_lookups from thermo.phase_identification import DENSITY_MASS, PROP_SORT, S_ID_D2P_DVDT, VL_ID_PIP, WATER_NOT_SPECIAL from thermo.phases import Phase diff --git a/thermo/chemical.py b/thermo/chemical.py index 926ad2c9..ebc27a8a 100644 --- a/thermo/chemical.py +++ b/thermo/chemical.py @@ -71,7 +71,7 @@ from chemicals.volume import ideal_gas from fluids.constants import epsilon_0 from fluids.core import Bond, Capillary, Grashof, Jakob, Peclet_heat, Prandtl, Reynolds, Weber, nu_mu_converter, thermal_diffusivity -from fluids.numerics import exp, log, newton, secant +from fluids.numerics import exp, log, secant from thermo import functional_groups from thermo.electrochem import conductivity, conductivity_methods diff --git a/thermo/chemical_package.py b/thermo/chemical_package.py index f52a1be1..bb76acd8 100644 --- a/thermo/chemical_package.py +++ b/thermo/chemical_package.py @@ -84,7 +84,7 @@ from chemicals.safety import LFL, STEL, TWA, UFL, Carcinogen, Ceiling, Skin, T_autoignition, T_flash from chemicals.solubility import solubility_parameter from chemicals.triple import Pt, Tt -from chemicals.utils import Parachor, hash_any_primitive, property_molar_to_mass +from chemicals.utils import Parachor, hash_any_primitive from fluids.constants import R from thermo.chemical import user_chemical_property_lookup diff --git a/thermo/chemical_utils.py b/thermo/chemical_utils.py index 857d8827..be43ac3d 100644 --- a/thermo/chemical_utils.py +++ b/thermo/chemical_utils.py @@ -291,7 +291,7 @@ def _standard_state_ideal_gas_formation_direct(T, Hf_ref, Sf_ref, atoms, gas_Cp, liquid_ele = {''} for coeff, ele_data in zip(elemental_counts, elemental_composition): - ele = list(ele_data.keys())[0] + ele = next(iter(ele_data.keys())) element_obj = periodic_table[ele] # element = Chemical(element_obj.CAS_standard) solid_obj = element_HeatCapacitySolid_cache(element_obj.CAS_standard) diff --git a/thermo/coolprop.py b/thermo/coolprop.py index 2cd02c8b..852e8f91 100644 --- a/thermo/coolprop.py +++ b/thermo/coolprop.py @@ -34,7 +34,6 @@ from math import exp, log from chemicals.utils import mark_numba_incompatible -from fluids.numerics import assert_close1d from fluids.numerics import numpy as np from thermo.base import data_dir diff --git a/thermo/eos.py b/thermo/eos.py index 8def44f8..6d2d5c09 100644 --- a/thermo/eos.py +++ b/thermo/eos.py @@ -293,7 +293,6 @@ ) from fluids.numerics import numpy as np -from thermo import serialize from thermo.serialize import JsonOptEncodable from thermo.eos_alpha_functions import Mathias_Copeman_poly_a_alpha, Poly_a_alpha, Soave_1979_a_alpha, Twu91_a_alpha, TwuPR95_a_alpha, TwuSRK95_a_alpha from thermo.eos_volume import volume_solutions_halley, volume_solutions_ideal, volume_solutions_mpmath, volume_solutions_mpmath_float, volume_solutions_NR diff --git a/thermo/eos_mix.py b/thermo/eos_mix.py index a2b517e1..98019706 100644 --- a/thermo/eos_mix.py +++ b/thermo/eos_mix.py @@ -204,7 +204,6 @@ from fluids.numerics import numpy as np from fluids.numerics.arrays import det, subset_matrix -from thermo import serialize from thermo.serialize import JsonOptEncodable from thermo.eos import ( APISRK, @@ -7526,7 +7525,7 @@ def dlnphis_dzs(self, Z): dE_dxs_i = [] a_alpha_ijs_i = a_alpha_ijs[i] - for k in range(0, i+1): + for k in range(i+1): # Sign was wrong in article - should be a plus second = t2*(t31*a_alpha_j_rows[k] - t32*a_alpha_ijs_i[k] - bs[i]*bs[k]*a_alpha2) dE_dxs[i][k] = dE_dxs[k][i] = t30*t50s[k] + second diff --git a/thermo/equilibrium.py b/thermo/equilibrium.py index efbe70b0..895320f8 100644 --- a/thermo/equilibrium.py +++ b/thermo/equilibrium.py @@ -40,11 +40,11 @@ __all__ = ['EquilibriumState'] from chemicals.elements import mass_fractions, periodic_table -from chemicals.utils import SG, Vm_to_rho, mixing_simple, normalize, vapor_mass_quality, zs_to_ws, object_data, hash_any_primitive +from chemicals.utils import SG, Vm_to_rho, mixing_simple, normalize, vapor_mass_quality, zs_to_ws, hash_any_primitive from fluids.constants import N_A, R from fluids.numerics import log from fluids.numerics import numpy as np -from thermo.serialize import arrays_to_lists, object_lookups +from thermo.serialize import object_lookups from thermo.bulk import Bulk, default_settings, JsonOptEncodable from thermo.chemical_package import ChemicalConstantsPackage, PropertyCorrelationsPackage, constants_docstrings from thermo.phases import Phase, derivatives_jacobian, derivatives_thermodynamic, derivatives_thermodynamic_mass, gas_phases, liquid_phases, solid_phases diff --git a/thermo/fitting.py b/thermo/fitting.py index 315f2eae..afe0c7fc 100644 --- a/thermo/fitting.py +++ b/thermo/fitting.py @@ -567,9 +567,7 @@ def poly_check_params(coeffs, domain=None): return False if not is_poly_positive(coeffs_d2, domain): return False - if not is_poly_negative(coeffs_d3, domain): - return False - return True + return is_poly_negative(coeffs_d3, domain) def alpha_poly_objf(params, Trs, alphas_over_a, domain=None): try: diff --git a/thermo/flash/flash_base.py b/thermo/flash/flash_base.py index a34a01f9..7eef456c 100644 --- a/thermo/flash/flash_base.py +++ b/thermo/flash/flash_base.py @@ -35,7 +35,7 @@ from fluids.constants import R from fluids.numerics import linspace, logspace from fluids.numerics import numpy as np -from thermo.serialize import JsonOptEncodable, object_lookups +from thermo.serialize import JsonOptEncodable from thermo import phases from thermo.equilibrium import EquilibriumState from thermo.flash.flash_utils import ( @@ -440,7 +440,7 @@ def flash(self, zs=None, T=None, P=None, VF=None, SF=None, V=None, H=None, constants=constants, correlations=correlations, settings=settings, flasher=self) elif VF_spec and any([H_spec, S_spec, U_spec, G_spec, A_spec]): - spec_var, spec_val = [(k, v) for k, v in flash_specs.items() if k not in ('VF', 'zs')][0] + spec_var, spec_val = next((k, v) for k, v in flash_specs.items() if k not in ('VF', 'zs')) T, Psat, liquid, gas, iters_inner, err_inner, err, iterations = self.flash_VF_HSGUA(VF, spec_val, fixed_var='VF', spec_var=spec_var, zs=zs, solution=solution, hot_start=hot_start) flash_convergence = {'iterations': iterations, 'err': err, 'inner_flash_convergence': {'iterations': iters_inner, 'err': err_inner}} return dest(T, Psat, zs, gas=gas, liquids=[liquid], solids=[], diff --git a/thermo/flash/flash_utils.py b/thermo/flash/flash_utils.py index a40d9b32..6db9b277 100644 --- a/thermo/flash/flash_utils.py +++ b/thermo/flash/flash_utils.py @@ -5209,7 +5209,7 @@ def incipient_liquid_bounded_PT_sat(flasher, specs, zs_existing, zs_added, check has_P = True else: raise ValueError("This algorithm requires T or P as a specification") - other_spec, other_spec_value = list(specs_working.keys())[0], list(specs_working.values())[0] + other_spec, other_spec_value = next(iter(specs_working.keys())), next(iter(specs_working.values())) zs_existing = flash_mixing_remove_overlap(zs_existing, zs_added) (negative_bound, positive_bound, negative_bound_res, positive_bound_res, diff --git a/thermo/flash/flash_vl.py b/thermo/flash/flash_vl.py index 0df14aa8..ad218e74 100644 --- a/thermo/flash/flash_vl.py +++ b/thermo/flash/flash_vl.py @@ -851,9 +851,7 @@ def flash_TPV_HSGUA(self, fixed_val, spec_val, fixed_var='P', spec='H', if selection_fun_1P is None: def selection_fun_1P(new, prev): - if new[-1] < prev[-1]: - return True - return False + return new[-1] < prev[-1] if 0: try: diff --git a/thermo/functional_groups.py b/thermo/functional_groups.py index 323ec997..bb35a843 100644 --- a/thermo/functional_groups.py +++ b/thermo/functional_groups.py @@ -2594,9 +2594,7 @@ def is_branched_alkane(mol): return False alkane_matches = mol.GetSubstructMatches(smarts_mol_cache(alkane_smarts)) only_aliphatic = substructures_are_entire_structure(mol, alkane_matches) - if only_aliphatic and mol.GetSubstructMatches(smarts_mol_cache(branched_alkane_smarts)): - return True - return False + return bool(only_aliphatic and mol.GetSubstructMatches(smarts_mol_cache(branched_alkane_smarts))) hardcoded_organic_smiles = frozenset([ diff --git a/thermo/interface.py b/thermo/interface.py index 9ea0d7fe..ff825459 100644 --- a/thermo/interface.py +++ b/thermo/interface.py @@ -80,7 +80,7 @@ sigma_IAPWS, ) from chemicals.miscdata import lookup_VDI_tabular_data -from chemicals.utils import Vm_to_rho, mixing_simple, none_and_length_check, property_molar_to_mass +from chemicals.utils import Vm_to_rho, none_and_length_check, property_molar_to_mass from fluids.numerics import isnan from thermo.heat_capacity import HeatCapacityLiquid diff --git a/thermo/phases/ceos.py b/thermo/phases/ceos.py index 32e972a4..20edc520 100644 --- a/thermo/phases/ceos.py +++ b/thermo/phases/ceos.py @@ -82,7 +82,7 @@ class CEOSPhase(IdealGasDeparturePhase): __slots__ = ('eos_class', 'eos_kwargs', 'vectorized', 'HeatCapacityGases', 'N', 'Hfs', 'Gfs', 'Sfs', 'Cpgs_poly_fit', '_Cpgs_data', 'composition_independent', - 'eos_mix', 'T', 'P' 'zs', '_model_hash_ignore_phase', '_model_hash') + 'eos_mix', 'T', 'P', 'zs', '_model_hash_ignore_phase', '_model_hash') ideal_gas_basis = True pure_references = ('HeatCapacityGases',) diff --git a/thermo/phases/gibbs_eos.py b/thermo/phases/gibbs_eos.py index 918f8970..155ba790 100644 --- a/thermo/phases/gibbs_eos.py +++ b/thermo/phases/gibbs_eos.py @@ -37,7 +37,8 @@ def dV_dP(self): T, P = symbols('T, P') G = symbols('G', cls=Function) V = diff(G(T, P), P) - diff(V, P)''' + diff(V, P) + ''' return self.d2G_dP2() dV_dP_T = dV_dP diff --git a/thermo/phases/gibbs_excess.py b/thermo/phases/gibbs_excess.py index 1504c54e..da8449a7 100644 --- a/thermo/phases/gibbs_excess.py +++ b/thermo/phases/gibbs_excess.py @@ -1299,7 +1299,6 @@ def Vms_sat(self): @staticmethod def _dVms_sat_dT_at(T, Vms_sat_data, cmps): - Vms_sat_data = Vms_sat_data Vms_sat_dT = [] Tmins, Tmaxes, dcoeffs = Vms_sat_data[0], Vms_sat_data[3], Vms_sat_data[7] for i in cmps: diff --git a/thermo/phases/iapws_phase.py b/thermo/phases/iapws_phase.py index c79c0de2..95a397f6 100644 --- a/thermo/phases/iapws_phase.py +++ b/thermo/phases/iapws_phase.py @@ -24,7 +24,7 @@ from cmath import log as logc from math import exp -from fluids.numerics import secant, newton +from fluids.numerics import secant from chemicals import iapws from chemicals.interface import sigma_IAPWS from chemicals.thermal_conductivity import k_IAPWS diff --git a/thermo/phases/phase.py b/thermo/phases/phase.py index ef8799d8..8e5565d1 100644 --- a/thermo/phases/phase.py +++ b/thermo/phases/phase.py @@ -66,8 +66,7 @@ from fluids.numerics import numpy as np from thermo import phases -from thermo.phases.phase_utils import object_lookups -from thermo.serialize import arrays_to_lists, JsonOptEncodable +from thermo.serialize import JsonOptEncodable from thermo.utils import POLY_FIT try: @@ -4216,8 +4215,7 @@ def _set_ideal_gas_standard_state(self): CASs = self.CASs T = self.T zs = self.zs - from thermo.chemical_utils import standard_state_ideal_gas_formation, _standard_state_ideal_gas_formation_direct - from thermo import Chemical + from thermo.chemical_utils import _standard_state_ideal_gas_formation_direct H_chemicals = [] S_chemicals = [] G_chemicals = [] diff --git a/thermo/redlich_kister.py b/thermo/redlich_kister.py index 48e2788d..aef86c1a 100644 --- a/thermo/redlich_kister.py +++ b/thermo/redlich_kister.py @@ -97,7 +97,7 @@ def redlich_kister_excess_inner(N, N_terms, a_tensor, xs): inner = 0.0 factor = 1.0 diff = (xs[i] - xs[j]) - for k in range(0, N_terms): + for k in range(N_terms): inner += a_tensor[i][j][k]*factor factor *= diff outer += inner*xs[j] diff --git a/thermo/serialize.py b/thermo/serialize.py index e2a85e7f..5cf0c231 100644 --- a/thermo/serialize.py +++ b/thermo/serialize.py @@ -337,7 +337,7 @@ def from_json(cls, json_repr, cache=None, ref_name='pyid_0'): new = original_obj.__new__(original_obj) cache[ref_name] = new search_recurse = new.obj_references if new.obj_references is not None else list(d.keys()) - if 'vectorized' in d and d['vectorized']: + if d.get('vectorized'): d = naive_lists_to_arrays(d) for obj_name in search_recurse: diff --git a/thermo/stream.py b/thermo/stream.py index 27cf8e74..23b9f44a 100644 --- a/thermo/stream.py +++ b/thermo/stream.py @@ -48,7 +48,6 @@ ) from chemicals.volume import ideal_gas from fluids.constants import R -from fluids.pump import residential_power_frequencies, voltages_1_phase_residential, voltages_3_phase from thermo.serialize import JsonOptEncodable from thermo.equilibrium import EquilibriumState from thermo.mixture import Mixture @@ -396,7 +395,8 @@ def energy(self): @energy.setter def energy(self, energy): r'''Set the flowing energy of the stream [W]. This variable can set either the - flow rate, or act as an enthalpy spec if another flow rate specification is specified.''' + flow rate, or act as an enthalpy spec if another flow rate specification is specified. + ''' if energy is None: self.specifications['energy'] = energy return None @@ -411,7 +411,8 @@ def energy_reactive(self): @energy_reactive.setter def energy_reactive(self, energy_reactive): r'''Set the flowing energy of the stream on a reactive basis [W]. This variable can set either the - flow rate, or act as an enthalpy spec if another flow rate specification is specified.''' + flow rate, or act as an enthalpy spec if another flow rate specification is specified. + ''' if energy_reactive is None: self.specifications['energy_reactive'] = energy_reactive return None @@ -1442,9 +1443,7 @@ def clean(self): '''If no variables have been specified, True, otherwis False. ''' - if self.composition_specified or self.state_specs or self.flow_specified: - return False - return True + return not (self.composition_specified or self.state_specs or self.flow_specified) @property @@ -1469,9 +1468,7 @@ def composition_specified(self): return True if s['Qls'] is not None and None not in s['Qls']: return True - if s['Qgs'] is not None and None not in s['Qgs']: - return True - return False + return bool(s['Qgs'] is not None and None not in s['Qgs']) def clear_state_specs(self): '''Removes any state specification(s) that are set, otherwise @@ -1621,9 +1618,7 @@ def state_specified(self): state_vars += 1 if s['H_reactive'] is not None: state_vars += 1 - if state_vars == 2: - return True - return False + return state_vars == 2 @property def non_pressure_spec_specified(self): @@ -1643,9 +1638,7 @@ def non_pressure_spec_specified(self): self.H_mass, self.H, self.S_mass, self.S, self.U_mass, self.U, self.A_mass, self.A, self.G_mass, self.G, self.energy, self.energy_reactive, self.H_reactive)) - if sum(state_vars) >= 1: - return True - return False + return sum(state_vars) >= 1 def clear_flow_spec(self): @@ -1733,9 +1726,7 @@ def flow_specified(self): return True if s['Ql'] is not None: return True - if s['Qg'] is not None: - return True - return False + return s['Qg'] is not None def update(self, **kwargs): """Update the specifications of the StreamArgs instance with new values provided as keyword arguments. @@ -1784,7 +1775,7 @@ def stream(self, existing_flash=None, hot_start=None): state specs of this object [-] hot_start : EquilibriumState, optional Flash at nearby conditions that may be used to initialize the flash [-] - + Returns ------- stream : EquilibriumStream @@ -1806,7 +1797,7 @@ def flash_state(self, hot_start=None): ---------- hot_start : EquilibriumState, optional Flash at nearby conditions that may be used to initialize the flash [-] - + Returns ------- flash : EquilibriumState @@ -1895,7 +1886,8 @@ def flash_state(self, hot_start=None): def value(self, name): r'''Wrapper around getattr that obtains a property specified. This method exists to unify e.g. H() on a EquilibriumState with H here which is a property. - Either object can simply be called obj.value("H"). [various]''' + Either object can simply be called obj.value("H"). [various] + ''' v = getattr(self, name) try: v = v() diff --git a/thermo/thermal_conductivity.py b/thermo/thermal_conductivity.py index 219c7ea5..55ddc565 100644 --- a/thermo/thermal_conductivity.py +++ b/thermo/thermal_conductivity.py @@ -155,7 +155,7 @@ Sheffy_Johnson, Stiel_Thodos_dense, ) -from chemicals.utils import mixing_simple, none_and_length_check +from chemicals.utils import none_and_length_check from fluids.constants import R from fluids.numerics import horner, sqrt diff --git a/thermo/utils/mixture_property.py b/thermo/utils/mixture_property.py index e9be69ad..f2a03822 100644 --- a/thermo/utils/mixture_property.py +++ b/thermo/utils/mixture_property.py @@ -28,9 +28,8 @@ from chemicals.utils import mixing_simple from thermo.redlich_kister import redlich_kister_T_dependence, redlich_kister_excess_inner, redlich_kister_build_structure -from thermo.eos_mix import GCEOSMIX from thermo.utils.functional import has_matplotlib -from thermo.utils.names import POLY_FIT, LINEAR, MIXING_LOG_MOLAR, MIXING_LOG_MASS +from thermo.utils.names import LINEAR, MIXING_LOG_MOLAR, MIXING_LOG_MASS from thermo.utils.t_dependent_property import json_mixture_correlation_lookup, ENABLE_MIXTURE_JSON from thermo.serialize import JsonOptEncodable try: @@ -149,7 +148,7 @@ def __init__(self, **kwargs): rk_dicts_ij = outer[i][j].get('redlick_kister_parameters', {}) if rk_dicts_ij: # What to do about other data sets? - first_data = list(rk_dicts_ij.values())[0] + first_data = next(iter(rk_dicts_ij.values())) if first_data['N_T'] > N_T: N_T = first_data['N_T'] if first_data['N_terms'] > N_terms: @@ -983,7 +982,6 @@ def plot_property(self, zs=None, ws=None, Tmin=None, Tmax=None, Pmin=1E5, raise Exception('Optional dependency matplotlib is required for plotting') else: import matplotlib.pyplot as plt - from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import FormatStrFormatter from numpy import ma if zs is None or ws is None: @@ -1059,7 +1057,6 @@ def plot_binary(self, P=None, T=None, pts=30, Tmin=None, Tmax=None, Pmin=1E5, raise Exception('Optional dependency matplotlib is required for plotting') else: import matplotlib.pyplot as plt - from mpl_toolkits.mplot3d import Axes3D from matplotlib.ticker import FormatStrFormatter from numpy import ma diff --git a/thermo/utils/t_dependent_property.py b/thermo/utils/t_dependent_property.py index e69adad9..c0316ccc 100644 --- a/thermo/utils/t_dependent_property.py +++ b/thermo/utils/t_dependent_property.py @@ -74,7 +74,7 @@ from chemicals.interface import PPDS14, ISTExpansion, Jasper, REFPROP_sigma, Somayajulu, Watson_sigma from chemicals.phase_change import PPDS12, Alibakhshi, Watson, Watson_n from chemicals.thermal_conductivity import PPDS3, PPDS8, Chemsep_16 -from chemicals.utils import hash_any_primitive, property_molar_to_mass +from chemicals.utils import hash_any_primitive from chemicals.vapor_pressure import ( Antoine, Antoine_AB_coeffs_from_point, @@ -184,7 +184,6 @@ trunc_exp, trunc_log, polyint_over_x_stable, - horner_log, horner_stable_log, ) from fluids.numerics import numpy as np @@ -192,7 +191,6 @@ import thermo from thermo.base import source_path from thermo.coolprop import coolprop_fluids -from thermo.eos import GCEOS from thermo.eos_alpha_functions import ( Almeida_alpha_pure, Androulakis_alpha_pure, @@ -3181,7 +3179,7 @@ def interpolate(self, T, name): if key in self.tabular_data_interpolators: extrapolator, spline = self.tabular_data_interpolators[key] else: - from scipy.interpolate import interp1d, PchipInterpolator + from scipy.interpolate import interp1d Ts, properties = self.tabular_data[name] if self.interpolation_T is not None: # Transform ths Ts with interpolation_T if set diff --git a/thermo/viscosity.py b/thermo/viscosity.py index d51401b6..6587e960 100644 --- a/thermo/viscosity.py +++ b/thermo/viscosity.py @@ -100,7 +100,7 @@ from chemicals.dippr import EQ101, EQ102 from chemicals.identifiers import CAS_to_int from chemicals.miscdata import JOBACK, lookup_VDI_tabular_data -from chemicals.utils import mixing_simple, none_and_length_check +from chemicals.utils import none_and_length_check from chemicals.viscosity import ( PPDS9, Brokaw, @@ -119,7 +119,7 @@ dPPDS9_dT, viscosity_gas_Gharagheizi, ) -from fluids.numerics import brenth, exp, sqrt, horner, isinf, isnan, log, trunc_log +from fluids.numerics import brenth, exp, sqrt, horner, isinf, isnan, log from thermo import electrochem from thermo.coolprop import CoolProp_failing_PT_flashes, CoolProp_T_dependent_property, PhaseSI, PropsSI, coolprop_dict, coolprop_fluids, has_CoolProp From 928bd1d25a1382439efcfd8e96b9759ecb417f49 Mon Sep 17 00:00:00 2001 From: Caleb Bell Date: Fri, 26 Jul 2024 14:25:23 -0600 Subject: [PATCH 8/9] More ruff --- thermo/__init__.py | 4 ++-- thermo/activity.py | 2 +- thermo/bulk.py | 5 +++-- thermo/chemical_package.py | 13 ++++++++++--- thermo/chemical_utils.py | 8 +++++--- thermo/eos.py | 2 +- thermo/eos_mix.py | 2 +- thermo/equilibrium.py | 8 +++++--- thermo/fitting.py | 3 ++- thermo/flash/__init__.py | 2 ++ thermo/flash/flash_base.py | 5 +++-- thermo/flash/flash_utils.py | 4 ++-- thermo/heat_capacity.py | 2 +- thermo/phases/__init__.py | 4 ++-- thermo/phases/iapws_phase.py | 6 ++++-- thermo/phases/phase.py | 2 +- thermo/phases/phase_utils.py | 3 ++- thermo/phases/virial_phase.py | 1 + thermo/property_package.py | 1 + thermo/redlich_kister.py | 1 + thermo/stream.py | 8 ++++---- thermo/thermal_conductivity.py | 14 +++++++++++++- thermo/utils/__init__.py | 10 +++++----- thermo/utils/mixture_property.py | 14 +++++++------- thermo/utils/t_dependent_property.py | 16 ++++++++-------- thermo/vapor_pressure.py | 2 +- thermo/viscosity.py | 17 ++++++++++++++--- 27 files changed, 102 insertions(+), 57 deletions(-) diff --git a/thermo/__init__.py b/thermo/__init__.py index 3d18a0a1..1b4ab96e 100644 --- a/thermo/__init__.py +++ b/thermo/__init__.py @@ -97,6 +97,7 @@ phase_identification, phases, property_package, + redlich_kister, regular_solution, stream, thermal_conductivity, @@ -107,7 +108,6 @@ viscosity, volume, wilson, - redlich_kister, ) from .activity import * # noqa: F403 from .bulk import * # noqa: F403 @@ -138,6 +138,7 @@ from .phase_identification import * # noqa: F403 from .phases import * # noqa: F403 from .property_package import * # noqa: F403 + from .redlich_kister import * # noqa: F403 from .regular_solution import * # noqa: F403 from .stream import * # noqa: F403 from .thermal_conductivity import * # noqa: F403 @@ -148,7 +149,6 @@ from .viscosity import * # noqa: F403 from .volume import * # noqa: F403 from .wilson import * # noqa: F403 - from .redlich_kister import * # noqa: F403 #from chemicals import * diff --git a/thermo/activity.py b/thermo/activity.py index a9efd73f..cdcf6f43 100644 --- a/thermo/activity.py +++ b/thermo/activity.py @@ -69,7 +69,7 @@ __all__ = ['GibbsExcess', 'IdealSolution'] from chemicals.utils import d2xs_to_dxdn_partials, dns_to_dn_partials, dxs_to_dn_partials, dxs_to_dns, hash_any_primitive, normalize, object_data from fluids.constants import R, R_inv -from fluids.numerics import exp, log, trunc_exp, derivative, jacobian, hessian +from fluids.numerics import derivative, exp, hessian, jacobian, log, trunc_exp from fluids.numerics import numpy as np from thermo.fitting import fit_customized diff --git a/thermo/bulk.py b/thermo/bulk.py index 24d51fe8..203eb1bf 100644 --- a/thermo/bulk.py +++ b/thermo/bulk.py @@ -73,13 +73,14 @@ __all__ = ['Bulk', 'BulkSettings', 'default_settings'] -from chemicals.utils import Joule_Thomson, isobaric_expansion, isothermal_compressibility, object_data, speed_of_sound, hash_any_primitive +from chemicals.utils import Joule_Thomson, hash_any_primitive, isobaric_expansion, isothermal_compressibility, object_data, speed_of_sound from fluids.constants import R, atm from fluids.numerics import exp, log, sqrt from fluids.two_phase_voidage import gas_liquid_viscosity -from thermo.serialize import JsonOptEncodable, object_lookups + from thermo.phase_identification import DENSITY_MASS, PROP_SORT, S_ID_D2P_DVDT, VL_ID_PIP, WATER_NOT_SPECIAL from thermo.phases import Phase +from thermo.serialize import JsonOptEncodable, object_lookups """Class designed to have multiple phases. diff --git a/thermo/chemical_package.py b/thermo/chemical_package.py index bb76acd8..dee40126 100644 --- a/thermo/chemical_package.py +++ b/thermo/chemical_package.py @@ -101,14 +101,21 @@ from thermo.interface import SurfaceTension, SurfaceTensionMixture from thermo.permittivity import PermittivityLiquid from thermo.phase_change import EnthalpySublimation, EnthalpyVaporization -from thermo.thermal_conductivity import ThermalConductivityGas, ThermalConductivityGasMixture, ThermalConductivityLiquid, ThermalConductivityLiquidMixture, ThermalConductivitySolid +from thermo.serialize import JsonOptEncodable +from thermo.thermal_conductivity import ( + ThermalConductivityGas, + ThermalConductivityGasMixture, + ThermalConductivityLiquid, + ThermalConductivityLiquidMixture, + ThermalConductivitySolid, +) from thermo.unifac import UNIFAC_RQ, UNIFAC_group_assignment_DDBST, Van_der_Waals_area, Van_der_Waals_volume from thermo.utils import identify_phase +from thermo.utils.mixture_property import MixtureProperty from thermo.vapor_pressure import SublimationPressure, VaporPressure from thermo.viscosity import ViscosityGas, ViscosityGasMixture, ViscosityLiquid, ViscosityLiquidMixture from thermo.volume import VolumeGas, VolumeGasMixture, VolumeLiquid, VolumeLiquidMixture, VolumeSolid, VolumeSolidMixture -from thermo.utils.mixture_property import MixtureProperty -from thermo.serialize import JsonOptEncodable + CAS_H2O = '7732-18-5' diff --git a/thermo/chemical_utils.py b/thermo/chemical_utils.py index be43ac3d..f6738ab8 100644 --- a/thermo/chemical_utils.py +++ b/thermo/chemical_utils.py @@ -23,10 +23,12 @@ __all__ = ['standard_entropy', 'S0_basis_converter', 'standard_state_ideal_gas_formation'] -from fluids.numerics import quad -from chemicals.reaction import standard_formation_reaction -from thermo.heat_capacity import HeatCapacitySolid, HeatCapacityLiquid, HeatCapacityGas from chemicals.elements import periodic_table +from chemicals.reaction import standard_formation_reaction +from fluids.numerics import quad + +from thermo.heat_capacity import HeatCapacityGas, HeatCapacityLiquid, HeatCapacitySolid + def standard_entropy(c=None, dS_trans_s=None, dH_trans_s=None, T_trans_s=None, Cp_s_fun=None, diff --git a/thermo/eos.py b/thermo/eos.py index 6d2d5c09..662fb27e 100644 --- a/thermo/eos.py +++ b/thermo/eos.py @@ -293,9 +293,9 @@ ) from fluids.numerics import numpy as np -from thermo.serialize import JsonOptEncodable from thermo.eos_alpha_functions import Mathias_Copeman_poly_a_alpha, Poly_a_alpha, Soave_1979_a_alpha, Twu91_a_alpha, TwuPR95_a_alpha, TwuSRK95_a_alpha from thermo.eos_volume import volume_solutions_halley, volume_solutions_ideal, volume_solutions_mpmath, volume_solutions_mpmath_float, volume_solutions_NR +from thermo.serialize import JsonOptEncodable R2 = R*R R_2 = 0.5*R diff --git a/thermo/eos_mix.py b/thermo/eos_mix.py index 98019706..cf5f0c39 100644 --- a/thermo/eos_mix.py +++ b/thermo/eos_mix.py @@ -204,7 +204,6 @@ from fluids.numerics import numpy as np from fluids.numerics.arrays import det, subset_matrix -from thermo.serialize import JsonOptEncodable from thermo.eos import ( APISRK, GCEOS, @@ -282,6 +281,7 @@ a_alpha_quadratic_terms, eos_mix_dV_dzs, ) +from thermo.serialize import JsonOptEncodable try: (zeros, array, npexp, npsqrt, empty, full, npwhere, npmin, npmax, ndarray, dot, prodsum) = ( diff --git a/thermo/equilibrium.py b/thermo/equilibrium.py index 895320f8..3a646c40 100644 --- a/thermo/equilibrium.py +++ b/thermo/equilibrium.py @@ -40,14 +40,15 @@ __all__ = ['EquilibriumState'] from chemicals.elements import mass_fractions, periodic_table -from chemicals.utils import SG, Vm_to_rho, mixing_simple, normalize, vapor_mass_quality, zs_to_ws, hash_any_primitive +from chemicals.utils import SG, Vm_to_rho, hash_any_primitive, mixing_simple, normalize, vapor_mass_quality, zs_to_ws from fluids.constants import N_A, R from fluids.numerics import log from fluids.numerics import numpy as np -from thermo.serialize import object_lookups -from thermo.bulk import Bulk, default_settings, JsonOptEncodable + +from thermo.bulk import Bulk, JsonOptEncodable, default_settings from thermo.chemical_package import ChemicalConstantsPackage, PropertyCorrelationsPackage, constants_docstrings from thermo.phases import Phase, derivatives_jacobian, derivatives_thermodynamic, derivatives_thermodynamic_mass, gas_phases, liquid_phases, solid_phases +from thermo.serialize import object_lookups all_phases = gas_phases + liquid_phases + solid_phases @@ -3659,6 +3660,7 @@ def get(self): object_lookups[PropertyCorrelationsPackage.__full_path__] = PropertyCorrelationsPackage from thermo.chemical_package import mix_properties_to_classes, properties_to_classes + for o in mix_properties_to_classes.values(): object_lookups[o.__full_path__] = o for o in properties_to_classes.values(): diff --git a/thermo/fitting.py b/thermo/fitting.py index afe0c7fc..5aebc58d 100644 --- a/thermo/fitting.py +++ b/thermo/fitting.py @@ -57,12 +57,13 @@ except: pass try: - from random import uniform, Random + from random import Random, uniform except: pass from math import log, pi + def split_data(x, y, folds=5, seed=42): pts = len(x) if pts != len(y): diff --git a/thermo/flash/__init__.py b/thermo/flash/__init__.py index 4ea4e85c..bd9e4560 100644 --- a/thermo/flash/__init__.py +++ b/thermo/flash/__init__.py @@ -77,12 +77,14 @@ __all__ = ('Flash', 'FlashPureVLS', 'FlashVL', 'FlashVLN') from thermo.serialize import object_lookups + object_lookups[FlashPureVLS.__full_path__] = FlashPureVLS object_lookups[FlashVL.__full_path__] = FlashVL object_lookups[FlashVLN.__full_path__] = FlashVLN from thermo.property_package import StabilityTester + object_lookups[StabilityTester.__full_path__] = StabilityTester diff --git a/thermo/flash/flash_base.py b/thermo/flash/flash_base.py index 7eef456c..51f303b1 100644 --- a/thermo/flash/flash_base.py +++ b/thermo/flash/flash_base.py @@ -31,11 +31,11 @@ from math import floor, log10, nan -from chemicals.utils import mixing_simple, property_mass_to_molar, rho_to_Vm, hash_any_primitive +from chemicals.utils import hash_any_primitive, mixing_simple, property_mass_to_molar, rho_to_Vm from fluids.constants import R from fluids.numerics import linspace, logspace from fluids.numerics import numpy as np -from thermo.serialize import JsonOptEncodable + from thermo import phases from thermo.equilibrium import EquilibriumState from thermo.flash.flash_utils import ( @@ -50,6 +50,7 @@ incipient_phase_one_sided_secant, ) from thermo.phase_identification import identify_sort_phases +from thermo.serialize import JsonOptEncodable from thermo.utils import has_matplotlib try: diff --git a/thermo/flash/flash_utils.py b/thermo/flash/flash_utils.py index 6db9b277..d3984699 100644 --- a/thermo/flash/flash_utils.py +++ b/thermo/flash/flash_utils.py @@ -88,6 +88,7 @@ from fluids.numerics import ( NotBoundedError, OscillationError, + SolverInterface, UnconvergedError, assert_close, assert_close1d, @@ -97,6 +98,7 @@ damping_maintain_sign, exp, fsolve, + gdem, isclose, isinf, isnan, @@ -118,8 +120,6 @@ translate_bound_f_jac, trunc_exp, trunc_log, - SolverInterface, - gdem, ) from fluids.numerics import numpy as np diff --git a/thermo/heat_capacity.py b/thermo/heat_capacity.py index db43a4fb..0d890ec5 100644 --- a/thermo/heat_capacity.py +++ b/thermo/heat_capacity.py @@ -149,7 +149,7 @@ has_CoolProp, ) from thermo.electrochem import Laliberte_heat_capacity -from thermo.utils import COOLPROP, HEOS_FIT, LINEAR, UNARY, JANAF_FIT, VDI_TABULAR, MixtureProperty, TDependentProperty +from thermo.utils import COOLPROP, HEOS_FIT, JANAF_FIT, LINEAR, UNARY, VDI_TABULAR, MixtureProperty, TDependentProperty TRCIG = 'TRCIG' POLING_POLY = 'POLING_POLY' diff --git a/thermo/phases/__init__.py b/thermo/phases/__init__.py index e949923b..6a6f7426 100644 --- a/thermo/phases/__init__.py +++ b/thermo/phases/__init__.py @@ -184,11 +184,10 @@ from thermo.phases.coolprop_phase import CoolPropGas, CoolPropLiquid, CoolPropPhase from thermo.phases.gibbs_excess import GibbsExcessLiquid, GibbsExcessSolid from thermo.phases.helmholtz_eos import HelmholtzEOS -from thermo.phases.iapws_phase import IAPWS95, IAPWS97, IAPWS95Gas, IAPWS95Liquid, IAPWS06 +from thermo.phases.iapws_phase import IAPWS06, IAPWS95, IAPWS97, IAPWS95Gas, IAPWS95Liquid from thermo.phases.ideal_gas import IdealGas from thermo.phases.petroleum import ChaoSeader, GraysonStreed from thermo.phases.phase import IdealGasDeparturePhase, Phase, derivatives_jacobian, derivatives_thermodynamic, derivatives_thermodynamic_mass -from thermo.serialize import object_lookups from thermo.phases.virial_phase import ( VIRIAL_B_ABBOTT, VIRIAL_B_MENG, @@ -206,6 +205,7 @@ VirialCSP, VirialGas, ) +from thermo.serialize import object_lookups __all__ = ('air_phase', 'ceos', 'combined', 'coolprop_phase', 'gibbs_excess', 'helmholtz_eos', 'iapws_phase', 'ideal_gas', 'petroleum', 'phase', 'virial_phase', diff --git a/thermo/phases/iapws_phase.py b/thermo/phases/iapws_phase.py index 95a397f6..7f51e904 100644 --- a/thermo/phases/iapws_phase.py +++ b/thermo/phases/iapws_phase.py @@ -24,16 +24,18 @@ from cmath import log as logc from math import exp -from fluids.numerics import secant + from chemicals import iapws from chemicals.interface import sigma_IAPWS from chemicals.thermal_conductivity import k_IAPWS from chemicals.utils import Vm_to_rho, rho_to_Vm from chemicals.viscosity import mu_IAPWS +from fluids.numerics import secant -from thermo.phases.helmholtz_eos import HelmholtzEOS from thermo.phases.gibbs_eos import GibbsEOS +from thermo.phases.helmholtz_eos import HelmholtzEOS from thermo.phases.phase import Phase + # from thermo.chemical_package import iapws_correlations class IAPWS95(HelmholtzEOS): diff --git a/thermo/phases/phase.py b/thermo/phases/phase.py index 8e5565d1..a1c0eca2 100644 --- a/thermo/phases/phase.py +++ b/thermo/phases/phase.py @@ -39,12 +39,12 @@ isentropic_exponent_PT, isentropic_exponent_PV, isentropic_exponent_TV, + mixing_simple, normalize, object_data, phase_identification_parameter, property_molar_to_mass, speed_of_sound, - mixing_simple ) from chemicals.virial import B_from_Z from fluids.constants import R, R_inv diff --git a/thermo/phases/phase_utils.py b/thermo/phases/phase_utils.py index 010762ea..ca008e3a 100644 --- a/thermo/phases/phase_utils.py +++ b/thermo/phases/phase_utils.py @@ -29,7 +29,7 @@ ] from fluids.numerics import log, trunc_exp -from thermo.serialize import object_lookups + from thermo.activity import IdealSolution from thermo.eos import eos_full_path_dict from thermo.eos_mix import eos_mix_full_path_dict @@ -43,6 +43,7 @@ ) from thermo.nrtl import NRTL, nrtl_gammas_from_args from thermo.regular_solution import RegularSolution, regular_solution_gammas +from thermo.serialize import object_lookups from thermo.unifac import UNIFAC, unifac_gammas_from_args from thermo.uniquac import UNIQUAC, uniquac_gammas_from_args from thermo.wilson import Wilson, wilson_gammas_from_args diff --git a/thermo/phases/virial_phase.py b/thermo/phases/virial_phase.py index 92230114..b9a6da5c 100644 --- a/thermo/phases/virial_phase.py +++ b/thermo/phases/virial_phase.py @@ -68,6 +68,7 @@ from fluids.constants import R from fluids.numerics import log, newton from fluids.numerics import numpy as np + from thermo.heat_capacity import HeatCapacityGas from thermo.phases.phase import IdealGasDeparturePhase, Phase from thermo.serialize import JsonOptEncodable diff --git a/thermo/property_package.py b/thermo/property_package.py index 8a80508e..fd9f5b9b 100644 --- a/thermo/property_package.py +++ b/thermo/property_package.py @@ -47,6 +47,7 @@ from fluids.constants import R from fluids.numerics import UnconvergedError, brenth, derivative, exp, log, secant from fluids.numerics import numpy as np + from thermo.serialize import JsonOptEncodable DIRECT_1P = 'Direct 1 Phase' diff --git a/thermo/redlich_kister.py b/thermo/redlich_kister.py index aef86c1a..60676258 100644 --- a/thermo/redlich_kister.py +++ b/thermo/redlich_kister.py @@ -34,6 +34,7 @@ 'redlich_kister_excess_binary', 'redlich_kister_fitting_to_use'] from math import log + def redlich_kister_reverse_2d(data_2d): data_2d = [d.copy() for d in data_2d] params = len(data_2d) diff --git a/thermo/stream.py b/thermo/stream.py index 23b9f44a..0bebd3e8 100644 --- a/thermo/stream.py +++ b/thermo/stream.py @@ -35,23 +35,23 @@ from chemicals.utils import ( Vfs_to_zs, Vm_to_rho, + hash_any_primitive, mixing_simple, normalize, + object_data, property_mass_to_molar, property_molar_to_mass, solve_flow_composition_mix, ws_to_zs, zs_to_Vfs, zs_to_ws, - object_data, - hash_any_primitive, ) from chemicals.volume import ideal_gas from fluids.constants import R -from thermo.serialize import JsonOptEncodable + from thermo.equilibrium import EquilibriumState from thermo.mixture import Mixture -from thermo.serialize import object_lookups +from thermo.serialize import JsonOptEncodable, object_lookups class StreamArgs: diff --git a/thermo/thermal_conductivity.py b/thermo/thermal_conductivity.py index 55ddc565..e255c2d0 100644 --- a/thermo/thermal_conductivity.py +++ b/thermo/thermal_conductivity.py @@ -163,7 +163,19 @@ from thermo.coolprop import CoolProp_failing_PT_flashes, CoolProp_T_dependent_property, PhaseSI, PropsSI, coolprop_dict, coolprop_fluids, has_CoolProp from thermo.electrochem import thermal_conductivity_Magomedov from thermo.heat_capacity import HeatCapacityGas -from thermo.utils import COOLPROP, DIPPR_PERRY_8E, HO1972, LINEAR, NEGLECT_P, REFPROP_FIT, VDI_PPDS, VDI_TABULAR, MixtureProperty, TDependentProperty, TPDependentProperty +from thermo.utils import ( + COOLPROP, + DIPPR_PERRY_8E, + HO1972, + LINEAR, + NEGLECT_P, + REFPROP_FIT, + VDI_PPDS, + VDI_TABULAR, + MixtureProperty, + TDependentProperty, + TPDependentProperty, +) from thermo.viscosity import ViscosityGas from thermo.volume import VolumeGas diff --git a/thermo/utils/__init__.py b/thermo/utils/__init__.py index 34854f31..c1e642a8 100644 --- a/thermo/utils/__init__.py +++ b/thermo/utils/__init__.py @@ -88,21 +88,21 @@ EXP_STABLEPOLY_FIT, EXP_STABLEPOLY_FIT_LN_TAU, HEOS_FIT, + HO1972, IAPWS, + JANAF_FIT, LINEAR, + MIXING_LOG_MASS, + MIXING_LOG_MOLAR, NEGLECT_P, POLY_FIT, POLY_FIT_LN_TAU, REFPROP_FIT, STABLEPOLY_FIT, STABLEPOLY_FIT_LN_TAU, + UNARY, VDI_PPDS, VDI_TABULAR, - MIXING_LOG_MOLAR, - MIXING_LOG_MASS, - UNARY, - HO1972, - JANAF_FIT ) from .t_dependent_property import * from .tp_dependent_property import * diff --git a/thermo/utils/mixture_property.py b/thermo/utils/mixture_property.py index f2a03822..fc6ddf76 100644 --- a/thermo/utils/mixture_property.py +++ b/thermo/utils/mixture_property.py @@ -22,16 +22,16 @@ __all__ = ['MixtureProperty'] -from chemicals.utils import hash_any_primitive, normalize, ws_to_zs, zs_to_ws -from fluids.numerics import derivative, linspace, trunc_log, trunc_exp +from chemicals.utils import hash_any_primitive, mixing_simple, normalize, ws_to_zs, zs_to_ws +from fluids.numerics import derivative, linspace, trunc_exp, trunc_log from fluids.numerics import numpy as np -from chemicals.utils import mixing_simple -from thermo.redlich_kister import redlich_kister_T_dependence, redlich_kister_excess_inner, redlich_kister_build_structure -from thermo.utils.functional import has_matplotlib -from thermo.utils.names import LINEAR, MIXING_LOG_MOLAR, MIXING_LOG_MASS -from thermo.utils.t_dependent_property import json_mixture_correlation_lookup, ENABLE_MIXTURE_JSON +from thermo.redlich_kister import redlich_kister_build_structure, redlich_kister_excess_inner, redlich_kister_T_dependence from thermo.serialize import JsonOptEncodable +from thermo.utils.functional import has_matplotlib +from thermo.utils.names import LINEAR, MIXING_LOG_MASS, MIXING_LOG_MOLAR +from thermo.utils.t_dependent_property import ENABLE_MIXTURE_JSON, json_mixture_correlation_lookup + try: from itertools import product except: diff --git a/thermo/utils/t_dependent_property.py b/thermo/utils/t_dependent_property.py index c0316ccc..1b695867 100644 --- a/thermo/utils/t_dependent_property.py +++ b/thermo/utils/t_dependent_property.py @@ -35,7 +35,6 @@ import chemicals import fluids -from chemicals.elements import solid_allotrope_map, allotrope_CAS_to_name from chemicals.dippr import ( EQ100, EQ101, @@ -56,6 +55,7 @@ EQ106_fitting_jacobian, EQ107_fitting_jacobian, ) +from chemicals.elements import allotrope_CAS_to_name, solid_allotrope_map from chemicals.heat_capacity import ( Poling, Poling_integral, @@ -160,7 +160,6 @@ horner_backwards_ln_tau_and_der3, horner_stable, horner_stable_and_der, - mean_squared_error, horner_stable_and_der2, horner_stable_and_der3, horner_stable_and_der4, @@ -168,23 +167,24 @@ horner_stable_ln_tau_and_der, horner_stable_ln_tau_and_der2, horner_stable_ln_tau_and_der3, + horner_stable_log, inf, interp, isinf, isnan, linspace, log, + mean_squared_error, polyder, polyint, polyint_over_x, + polyint_over_x_stable, polyint_stable, polynomial_offset_scale, quad, secant, trunc_exp, trunc_log, - polyint_over_x_stable, - horner_stable_log, ) from fluids.numerics import numpy as np @@ -214,7 +214,8 @@ Twu91_alpha_pure, Yu_Lu_alpha_pure, ) -from thermo.fitting import BIC, AICc, fit_customized, assemble_fit_test_groups, split_data, round_to_digits +from thermo.fitting import BIC, AICc, assemble_fit_test_groups, fit_customized, round_to_digits, split_data +from thermo.serialize import JsonOptEncodable from thermo.utils.functional import has_matplotlib from thermo.utils.names import ( CHEB_FIT, @@ -226,18 +227,17 @@ EXP_STABLEPOLY_FIT, EXP_STABLEPOLY_FIT_LN_TAU, HEOS_FIT, - UNARY, HO1972, + JANAF_FIT, NEGLECT_P, POLY_FIT, POLY_FIT_LN_TAU, REFPROP_FIT, STABLEPOLY_FIT, STABLEPOLY_FIT_LN_TAU, + UNARY, VDI_TABULAR, - JANAF_FIT, ) -from thermo.serialize import JsonOptEncodable """This section is intended to be used in being able to add new data without changing code for each object. diff --git a/thermo/vapor_pressure.py b/thermo/vapor_pressure.py index 3faae807..14d1d4cf 100644 --- a/thermo/vapor_pressure.py +++ b/thermo/vapor_pressure.py @@ -64,7 +64,7 @@ from chemicals import miscdata, vapor_pressure from chemicals.dippr import EQ101 -from chemicals.iapws import iapws95_dPsat_dT, iapws95_Psat, iapws95_Tc, iapws11_Psub, iapws95_Tt +from chemicals.iapws import iapws11_Psub, iapws95_dPsat_dT, iapws95_Psat, iapws95_Tc, iapws95_Tt from chemicals.identifiers import CAS_to_int from chemicals.miscdata import lookup_VDI_tabular_data from chemicals.vapor_pressure import ( diff --git a/thermo/viscosity.py b/thermo/viscosity.py index 6587e960..0f53302b 100644 --- a/thermo/viscosity.py +++ b/thermo/viscosity.py @@ -119,13 +119,24 @@ dPPDS9_dT, viscosity_gas_Gharagheizi, ) -from fluids.numerics import brenth, exp, sqrt, horner, isinf, isnan, log +from fluids.numerics import brenth, exp, horner, isinf, isnan, log, sqrt from thermo import electrochem from thermo.coolprop import CoolProp_failing_PT_flashes, CoolProp_T_dependent_property, PhaseSI, PropsSI, coolprop_dict, coolprop_fluids, has_CoolProp from thermo.electrochem import Laliberte_viscosity -from thermo.utils import (COOLPROP, DIPPR_PERRY_8E, LINEAR, NEGLECT_P, REFPROP_FIT, VDI_PPDS, VDI_TABULAR, - MIXING_LOG_MOLAR, MIXING_LOG_MASS, MixtureProperty, TPDependentProperty) +from thermo.utils import ( + COOLPROP, + DIPPR_PERRY_8E, + LINEAR, + MIXING_LOG_MASS, + MIXING_LOG_MOLAR, + NEGLECT_P, + REFPROP_FIT, + VDI_PPDS, + VDI_TABULAR, + MixtureProperty, + TPDependentProperty, +) from thermo.vapor_pressure import VaporPressure from thermo.volume import VolumeGas, VolumeLiquid From 7ede76354106601aeb6aec14f65236614700d223 Mon Sep 17 00:00:00 2001 From: Caleb Bell Date: Fri, 26 Jul 2024 14:29:23 -0600 Subject: [PATCH 9/9] Ruff Q001,UP039,W292,SIM103,B009,B010 --- thermo/activity.py | 4 ++-- thermo/bulk.py | 2 +- thermo/chemical_package.py | 2 +- thermo/eos_mix.py | 2 +- thermo/equilibrium.py | 2 +- thermo/phases/__init__.py | 2 +- thermo/serialize.py | 14 +++++++------- thermo/stream.py | 6 +++--- 8 files changed, 17 insertions(+), 17 deletions(-) diff --git a/thermo/activity.py b/thermo/activity.py index cdcf6f43..fe445361 100644 --- a/thermo/activity.py +++ b/thermo/activity.py @@ -447,9 +447,9 @@ def from_json(cls, json_repr, cache=None): def _custom_from_json(self, *args): vectorized = self.vectorized if vectorized and hasattr(self, 'cmp_group_idx'): - setattr(self, 'cmp_group_idx', tuple(array(v) for v in getattr(self, 'cmp_group_idx'))) + self.cmp_group_idx = tuple(array(v) for v in self.cmp_group_idx) if vectorized and hasattr(self, 'group_cmp_idx'): - setattr(self, 'group_cmp_idx', tuple(array(v) for v in getattr(self, 'group_cmp_idx'))) + self.group_cmp_idx = tuple(array(v) for v in self.group_cmp_idx) def HE(self): r'''Calculate and return the excess entropy of a liquid phase using an diff --git a/thermo/bulk.py b/thermo/bulk.py index 203eb1bf..a57e7e81 100644 --- a/thermo/bulk.py +++ b/thermo/bulk.py @@ -1716,4 +1716,4 @@ def G_min_criteria(self): object_lookups[Bulk.__full_path__] = Bulk -object_lookups[BulkSettings.__full_path__] = BulkSettings \ No newline at end of file +object_lookups[BulkSettings.__full_path__] = BulkSettings diff --git a/thermo/chemical_package.py b/thermo/chemical_package.py index dee40126..4ac40f71 100644 --- a/thermo/chemical_package.py +++ b/thermo/chemical_package.py @@ -135,7 +135,7 @@ fairly easily once the data entry is complete.""" -class ChemicalConstantsPackage(): +class ChemicalConstantsPackage: non_vector_properties = ('atomss', 'Carcinogens', 'CASs', 'Ceilings', 'charges', 'conductivities', 'dipoles', 'economic_statuses', 'formulas', 'Gfgs', 'Gfgs_mass', 'GWPs', 'Hcs', 'Hcs_lower', 'Hcs_lower_mass', 'Hcs_mass', diff --git a/thermo/eos_mix.py b/thermo/eos_mix.py index cf5f0c39..bbc73120 100644 --- a/thermo/eos_mix.py +++ b/thermo/eos_mix.py @@ -442,7 +442,7 @@ def _custom_from_json(self, *args): except: pass try: - setattr(self, 'one_minus_kijs', one_minus_kijs(self.kijs)) + self.one_minus_kijs = one_minus_kijs(self.kijs) except: pass diff --git a/thermo/equilibrium.py b/thermo/equilibrium.py index 3a646c40..f46bb931 100644 --- a/thermo/equilibrium.py +++ b/thermo/equilibrium.py @@ -3664,4 +3664,4 @@ def get(self): for o in mix_properties_to_classes.values(): object_lookups[o.__full_path__] = o for o in properties_to_classes.values(): - object_lookups[o.__full_path__] = o \ No newline at end of file + object_lookups[o.__full_path__] = o diff --git a/thermo/phases/__init__.py b/thermo/phases/__init__.py index 6a6f7426..58ee07ba 100644 --- a/thermo/phases/__init__.py +++ b/thermo/phases/__init__.py @@ -249,4 +249,4 @@ phase_full_path_dict = {c.__full_path__: c for c in all_phases} object_lookups.update(phase_full_path_dict) -object_lookups[VirialCSP.__full_path__] = VirialCSP \ No newline at end of file +object_lookups[VirialCSP.__full_path__] = VirialCSP diff --git a/thermo/serialize.py b/thermo/serialize.py index 5cf0c231..0f35bbfe 100644 --- a/thermo/serialize.py +++ b/thermo/serialize.py @@ -210,22 +210,22 @@ def json_default(obj): JSON_DEFAULT = 0 JSON_DROP_RECALCULABLE = 1 -class JsonOptEncodable(): +class JsonOptEncodable: json_version = 1 - '''This attribute will be encoded into the produced json blob. + """This attribute will be encoded into the produced json blob. It is specific to each object. When backwards incompatible changes are made to an object's structure, be sure to increment this to avoid deserializations - producing broken objects.''' + producing broken objects.""" obj_references = None - '''If this attribute is not None, instead of inspecting each object for whether it is a json-supported type, + """If this attribute is not None, instead of inspecting each object for whether it is a json-supported type, only these attribute names are inspected for recursion. These are also the only references subject to deduplication. - ''' + """ non_json_attributes = [] - '''List of attributes to remove from a dict - ''' + """List of attributes to remove from a dict + """ def _custom_as_json(self, cache): # Handle anything custom diff --git a/thermo/stream.py b/thermo/stream.py index 0bebd3e8..4e99efe8 100644 --- a/thermo/stream.py +++ b/thermo/stream.py @@ -202,8 +202,8 @@ class StreamArgs: ''' flashed = False - '''`flashed` can be checked to quickly determine if an object is already flashed. It is always False for `StreamArgs`, - and True for `EquilibriumState` and `EquilibriumStream`''' + """`flashed` can be checked to quickly determine if an object is already flashed. It is always False for `StreamArgs`, + and True for `EquilibriumState` and `EquilibriumStream`""" __full_path__ = f"{__module__}.{__qualname__}" __slots__ = ('specifications', 'multiple_composition_basis', 'Vf_TP', 'Q_TP', 'flasher', '_state_cache', '_flash') @@ -3654,4 +3654,4 @@ def energy_balance(inlets, outlets, reactive=False, use_mass=False): object_lookups[StreamArgs.__full_path__] = StreamArgs object_lookups[EquilibriumStream.__full_path__] = EquilibriumStream -object_lookups[EnergyStream.__full_path__] = EnergyStream \ No newline at end of file +object_lookups[EnergyStream.__full_path__] = EnergyStream