Search is not available for this dataset
text
stringlengths
75
104k
def calculate_derivative_T(self, T, P, zs, ws, method, order=1): r'''Method to calculate a derivative of a mixture property with respect to temperature at constant pressure and composition of a given order using a specified method. Uses SciPy's derivative function, with a delta of 1E-6 K and a number of points equal to 2*order + 1. This method can be overwritten by subclasses who may perfer to add analytical methods for some or all methods as this is much faster. If the calculation does not succeed, returns the actual error encountered. Parameters ---------- T : float Temperature at which to calculate the derivative, [K] P : float Pressure at which to calculate the derivative, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] method : str Method for which to find the derivative order : int Order of the derivative, >= 1 Returns ------- d_prop_d_T_at_P : float Calculated derivative property at constant pressure, [`units/K^order`] ''' return derivative(self.calculate, T, dx=1e-6, args=[P, zs, ws, method], n=order, order=1+order*2)
def calculate_derivative_P(self, P, T, zs, ws, method, order=1): r'''Method to calculate a derivative of a mixture property with respect to pressure at constant temperature and composition of a given order using a specified method. Uses SciPy's derivative function, with a delta of 0.01 Pa and a number of points equal to 2*order + 1. This method can be overwritten by subclasses who may perfer to add analytical methods for some or all methods as this is much faster. If the calculation does not succeed, returns the actual error encountered. Parameters ---------- P : float Pressure at which to calculate the derivative, [Pa] T : float Temperature at which to calculate the derivative, [K] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] method : str Method for which to find the derivative order : int Order of the derivative, >= 1 Returns ------- d_prop_d_P_at_T : float Calculated derivative property at constant temperature, [`units/Pa^order`] ''' f = lambda P: self.calculate(T, P, zs, ws, method) return derivative(f, P, dx=1e-2, n=order, order=1+order*2)
def property_derivative_T(self, T, P, zs, ws, order=1): r'''Method to calculate a derivative of a mixture property with respect to temperature at constant pressure and composition, of a given order. Methods found valid by `select_valid_methods` are attempted until a method succeeds. If no methods are valid and succeed, None is returned. Calls `calculate_derivative_T` internally to perform the actual calculation. .. math:: \text{derivative} = \frac{d (\text{property})}{d T}|_{P, z} Parameters ---------- T : float Temperature at which to calculate the derivative, [K] P : float Pressure at which to calculate the derivative, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] order : int Order of the derivative, >= 1 Returns ------- d_prop_d_T_at_P : float Calculated derivative property, [`units/K^order`] ''' sorted_valid_methods = self.select_valid_methods(T, P, zs, ws) for method in sorted_valid_methods: try: return self.calculate_derivative_T(T, P, zs, ws, method, order) except: pass return None
def property_derivative_P(self, T, P, zs, ws, order=1): r'''Method to calculate a derivative of a mixture property with respect to pressure at constant temperature and composition, of a given order. Methods found valid by `select_valid_methods` are attempted until a method succeeds. If no methods are valid and succeed, None is returned. Calls `calculate_derivative_P` internally to perform the actual calculation. .. math:: \text{derivative} = \frac{d (\text{property})}{d P}|_{T, z} Parameters ---------- T : float Temperature at which to calculate the derivative, [K] P : float Pressure at which to calculate the derivative, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] order : int Order of the derivative, >= 1 Returns ------- d_prop_d_P_at_T : float Calculated derivative property, [`units/Pa^order`] ''' sorted_valid_methods = self.select_valid_methods(T, P, zs, ws) for method in sorted_valid_methods: try: return self.calculate_derivative_P(P, T, zs, ws, method, order) except: pass return None
def plot_isotherm(self, T, zs, ws, Pmin=None, Pmax=None, methods=[], pts=50, only_valid=True): # pragma: no cover r'''Method to create a plot of the property vs pressure at a specified temperature and composition according to either a specified list of methods, or the user methods (if set), or all methods. User-selectable number of points, and pressure range. If only_valid is set, `test_method_validity` will be used to check if each condition in the specified range is valid, and `test_property_validity` will be used to test the answer, and the method is allowed to fail; only the valid points will be plotted. Otherwise, the result will be calculated and displayed as-is. This will not suceed if the method fails. Parameters ---------- T : float Temperature at which to create the plot, [K] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] Pmin : float Minimum pressure, to begin calculating the property, [Pa] Pmax : float Maximum pressure, to stop calculating the property, [Pa] methods : list, optional List of methods to consider pts : int, optional A list of points to calculate the property at; if Pmin to Pmax covers a wide range of method validities, only a few points may end up calculated for a given method so this may need to be large only_valid : bool If True, only plot successful methods and calculated properties, and handle errors; if False, attempt calculation without any checking and use methods outside their bounds ''' # This function cannot be tested if not has_matplotlib: raise Exception('Optional dependency matplotlib is required for plotting') if Pmin is None: if self.Pmin is not None: Pmin = self.Pmin else: raise Exception('Minimum pressure could not be auto-detected; please provide it') if Pmax is None: if self.Pmax is not None: Pmax = self.Pmax else: raise Exception('Maximum pressure could not be auto-detected; please provide it') if not methods: if self.user_methods: methods = self.user_methods else: methods = self.all_methods Ps = np.linspace(Pmin, Pmax, pts) for method in methods: if only_valid: properties, Ps2 = [], [] for P in Ps: if self.test_method_validity(T, P, zs, ws, method): try: p = self.calculate(T, P, zs, ws, method) if self.test_property_validity(p): properties.append(p) Ps2.append(P) except: pass plt.plot(Ps2, properties, label=method) else: properties = [self.calculate(T, P, zs, ws, method) for P in Ps] plt.plot(Ps, properties, label=method) plt.legend(loc='best') plt.ylabel(self.name + ', ' + self.units) plt.xlabel('Pressure, Pa') plt.title(self.name + ' of a mixture of ' + ', '.join(self.CASs) + ' at mole fractions of ' + ', '.join(str(round(i, 4)) for i in zs) + '.') plt.show()
def plot_isobar(self, P, zs, ws, Tmin=None, Tmax=None, methods=[], pts=50, only_valid=True): # pragma: no cover r'''Method to create a plot of the property vs temperature at a specific pressure and composition according to either a specified list of methods, or user methods (if set), or all methods. User-selectable number of points, and temperature range. If only_valid is set,`test_method_validity` will be used to check if each condition in the specified range is valid, and `test_property_validity` will be used to test the answer, and the method is allowed to fail; only the valid points will be plotted. Otherwise, the result will be calculated and displayed as-is. This will not suceed if the method fails. Parameters ---------- P : float Pressure for the isobar, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] Tmin : float Minimum temperature, to begin calculating the property, [K] Tmax : float Maximum temperature, to stop calculating the property, [K] methods : list, optional List of methods to consider pts : int, optional A list of points to calculate the property at; if Tmin to Tmax covers a wide range of method validities, only a few points may end up calculated for a given method so this may need to be large only_valid : bool If True, only plot successful methods and calculated properties, and handle errors; if False, attempt calculation without any checking and use methods outside their bounds ''' if not has_matplotlib: raise Exception('Optional dependency matplotlib is required for plotting') if Tmin is None: if self.Tmin is not None: Tmin = self.Tmin else: raise Exception('Minimum pressure could not be auto-detected; please provide it') if Tmax is None: if self.Tmax is not None: Tmax = self.Tmax else: raise Exception('Maximum pressure could not be auto-detected; please provide it') if not methods: if self.user_methods: methods = self.user_methods else: methods = self.all_methods Ts = np.linspace(Tmin, Tmax, pts) for method in methods: if only_valid: properties, Ts2 = [], [] for T in Ts: if self.test_method_validity(T, P, zs, ws, method): try: p = self.calculate(T, P, zs, ws, method) if self.test_property_validity(p): properties.append(p) Ts2.append(T) except: pass plt.plot(Ts2, properties, label=method) else: properties = [self.calculate(T, P, zs, ws, method) for T in Ts] plt.plot(Ts, properties, label=method) plt.legend(loc='best') plt.ylabel(self.name + ', ' + self.units) plt.xlabel('Temperature, K') plt.title(self.name + ' of a mixture of ' + ', '.join(self.CASs) + ' at mole fractions of ' + ', '.join(str(round(i, 4)) for i in zs) + '.') plt.show()
def plot_property(self, zs, ws, Tmin=None, Tmax=None, Pmin=1E5, Pmax=1E6, methods=[], pts=15, only_valid=True): # pragma: no cover r'''Method to create a plot of the property vs temperature and pressure according to either a specified list of methods, or user methods (if set), or all methods. User-selectable number of points for each variable. If only_valid is set,`test_method_validity` will be used to check if each condition in the specified range is valid, and `test_property_validity` will be used to test the answer, and the method is allowed to fail; only the valid points will be plotted. Otherwise, the result will be calculated and displayed as-is. This will not suceed if the any method fails for any point. Parameters ---------- Tmin : float Minimum temperature, to begin calculating the property, [K] Tmax : float Maximum temperature, to stop calculating the property, [K] Pmin : float Minimum pressure, to begin calculating the property, [Pa] Pmax : float Maximum pressure, to stop calculating the property, [Pa] methods : list, optional List of methods to consider pts : int, optional A list of points to calculate the property at for both temperature and pressure; pts^2 points will be calculated. only_valid : bool If True, only plot successful methods and calculated properties, and handle errors; if False, attempt calculation without any checking and use methods outside their bounds ''' if not has_matplotlib: raise Exception('Optional dependency matplotlib is required for plotting') from mpl_toolkits.mplot3d import axes3d from matplotlib.ticker import FormatStrFormatter import numpy.ma as ma if Pmin is None: if self.Pmin is not None: Pmin = self.Pmin else: raise Exception('Minimum pressure could not be auto-detected; please provide it') if Pmax is None: if self.Pmax is not None: Pmax = self.Pmax else: raise Exception('Maximum pressure could not be auto-detected; please provide it') if Tmin is None: if self.Tmin is not None: Tmin = self.Tmin else: raise Exception('Minimum pressure could not be auto-detected; please provide it') if Tmax is None: if self.Tmax is not None: Tmax = self.Tmax else: raise Exception('Maximum pressure could not be auto-detected; please provide it') if not methods: methods = self.user_methods if self.user_methods else self.all_methods Ps = np.linspace(Pmin, Pmax, pts) Ts = np.linspace(Tmin, Tmax, pts) Ts_mesh, Ps_mesh = np.meshgrid(Ts, Ps) fig = plt.figure() ax = fig.gca(projection='3d') handles = [] for method in methods: if only_valid: properties = [] for T in Ts: T_props = [] for P in Ps: if self.test_method_validity(T, P, zs, ws, method): try: p = self.calculate(T, P, zs, ws, method) if self.test_property_validity(p): T_props.append(p) else: T_props.append(None) except: T_props.append(None) else: T_props.append(None) properties.append(T_props) properties = ma.masked_invalid(np.array(properties, dtype=np.float).T) handles.append(ax.plot_surface(Ts_mesh, Ps_mesh, properties, cstride=1, rstride=1, alpha=0.5)) else: properties = [[self.calculate(T, P, zs, ws, method) for P in Ps] for T in Ts] handles.append(ax.plot_surface(Ts_mesh, Ps_mesh, properties, cstride=1, rstride=1, alpha=0.5)) ax.yaxis.set_major_formatter(FormatStrFormatter('%.4g')) ax.zaxis.set_major_formatter(FormatStrFormatter('%.4g')) ax.xaxis.set_major_formatter(FormatStrFormatter('%.4g')) ax.set_xlabel('Temperature, K') ax.set_ylabel('Pressure, Pa') ax.set_zlabel(self.name + ', ' + self.units) plt.title(self.name + ' of a mixture of ' + ', '.join(self.CASs) + ' at mole fractions of ' + ', '.join(str(round(i, 4)) for i in zs) + '.') plt.show(block=False) # The below is a workaround for a matplotlib bug ax.legend(handles, methods) plt.show(block=False)
def refractive_index(CASRN, T=None, AvailableMethods=False, Method=None, full_info=True): r'''This function handles the retrieval of a chemical's refractive index. Lookup is based on CASRNs. Will automatically select a data source to use if no Method is provided; returns None if the data is not available. Function has data for approximately 4500 chemicals. Parameters ---------- CASRN : string CASRN [-] Returns ------- RI : float Refractive Index on the Na D line, [-] T : float, only returned if full_info == True Temperature at which refractive index reading was made methods : list, only returned if AvailableMethods == True List of methods which can be used to obtain RI with the given inputs Other Parameters ---------------- Method : string, optional A string for the method name to use, as defined by constants in RI_methods AvailableMethods : bool, optional If True, function will determine which methods can be used to obtain RI for the desired chemical, and will return methods instead of RI full_info : bool, optional If True, function will return the temperature at which the refractive index reading was made Notes ----- Only one source is available in this function. It is: * 'CRC', a compillation of Organic RI data in [1]_. Examples -------- >>> refractive_index(CASRN='64-17-5') (1.3611, 293.15) References ---------- .. [1] Haynes, W.M., Thomas J. Bruno, and David R. Lide. CRC Handbook of Chemistry and Physics, 95E. Boca Raton, FL: CRC press, 2014. ''' def list_methods(): methods = [] if CASRN in CRC_RI_organic.index: methods.append(CRC) methods.append(NONE) return methods if AvailableMethods: return list_methods() if not Method: Method = list_methods()[0] if Method == CRC: _RI = float(CRC_RI_organic.at[CASRN, 'RI']) if full_info: _T = float(CRC_RI_organic.at[CASRN, 'RIT']) elif Method == NONE: _RI, _T = None, None else: raise Exception('Failure in in function') if full_info: return _RI, _T else: return _RI
def a_alpha_and_derivatives(self, T, full=True, quick=True): r'''Method to calculate `a_alpha` and its first and second derivatives for an EOS with the Van der Waals mixing rules. Uses the parent class's interface to compute pure component values. Returns `a_alpha`, `da_alpha_dT`, and `d2a_alpha_dT2`. Calls `setup_a_alpha_and_derivatives` before calling `a_alpha_and_derivatives` for each species, which typically sets `a` and `Tc`. Calls `cleanup_a_alpha_and_derivatives` to remove the set properties after the calls are done. For use in `solve_T` this returns only `a_alpha` if `full` is False. .. math:: a \alpha = \sum_i \sum_j z_i z_j {(a\alpha)}_{ij} (a\alpha)_{ij} = (1-k_{ij})\sqrt{(a\alpha)_{i}(a\alpha)_{j}} Parameters ---------- T : float Temperature, [K] full : bool, optional If False, calculates and returns only `a_alpha` quick : bool, optional Only the quick variant is implemented; it is little faster anyhow Returns ------- a_alpha : float Coefficient calculated by EOS-specific method, [J^2/mol^2/Pa] da_alpha_dT : float Temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K] d2a_alpha_dT2 : float Second temperature derivative of coefficient calculated by EOS-specific method, [J^2/mol^2/Pa/K**2] Notes ----- The exact expressions can be obtained with the following SymPy expression below, commented out for brevity. >>> from sympy import * >>> a_alpha_i, a_alpha_j, kij, T = symbols('a_alpha_i, a_alpha_j, kij, T') >>> a_alpha_ij = (1-kij)*sqrt(a_alpha_i(T)*a_alpha_j(T)) >>> #diff(a_alpha_ij, T) >>> #diff(a_alpha_ij, T, T) ''' zs, kijs = self.zs, self.kijs a_alphas, da_alpha_dTs, d2a_alpha_dT2s = [], [], [] for i in self.cmps: self.setup_a_alpha_and_derivatives(i, T=T) # Abuse method resolution order to call the a_alpha_and_derivatives # method of the original pure EOS # -4 goes back from object, GCEOS, SINGLEPHASEEOS, up to GCEOSMIX ds = super(type(self).__mro__[self.a_alpha_mro], self).a_alpha_and_derivatives(T) a_alphas.append(ds[0]) da_alpha_dTs.append(ds[1]) d2a_alpha_dT2s.append(ds[2]) self.cleanup_a_alpha_and_derivatives() da_alpha_dT, d2a_alpha_dT2 = 0.0, 0.0 a_alpha_ijs = [[(1. - kijs[i][j])*(a_alphas[i]*a_alphas[j])**0.5 for j in self.cmps] for i in self.cmps] # Needed in calculation of fugacity coefficients a_alpha = sum([a_alpha_ijs[i][j]*zs[i]*zs[j] for j in self.cmps for i in self.cmps]) self.a_alpha_ijs = a_alpha_ijs if full: for i in self.cmps: for j in self.cmps: a_alphai, a_alphaj = a_alphas[i], a_alphas[j] x0 = a_alphai*a_alphaj x0_05 = x0**0.5 zi_zj = zs[i]*zs[j] da_alpha_dT += zi_zj*((1. - kijs[i][j])/(2.*x0_05) *(a_alphai*da_alpha_dTs[j] + a_alphaj*da_alpha_dTs[i])) x1 = a_alphai*da_alpha_dTs[j] x2 = a_alphaj*da_alpha_dTs[i] x3 = 2.*a_alphai*da_alpha_dTs[j] + 2.*a_alphaj*da_alpha_dTs[i] d2a_alpha_dT2 += (-x0_05*(kijs[i][j] - 1.)*(x0*( 2.*a_alphai*d2a_alpha_dT2s[j] + 2.*a_alphaj*d2a_alpha_dT2s[i] + 4.*da_alpha_dTs[i]*da_alpha_dTs[j]) - x1*x3 - x2*x3 + (x1 + x2)**2)/(4.*x0*x0))*zi_zj return a_alpha, da_alpha_dT, d2a_alpha_dT2 else: return a_alpha
def fugacities(self, xs=None, ys=None): r'''Helper method for calculating fugacity coefficients for any phases present, using either the overall mole fractions for both phases or using specified mole fractions for each phase. Requires `fugacity_coefficients` to be implemented by each subclassing EOS. In addition to setting `fugacities_l` and/or `fugacities_g`, this also sets the fugacity coefficients `phis_l` and/or `phis_g`. .. math:: \hat \phi_i^g = \frac{\hat f_i^g}{x_i P} \hat \phi_i^l = \frac{\hat f_i^l}{x_i P} Parameters ---------- xs : list[float], optional Liquid-phase mole fractions of each species, [-] ys : list[float], optional Vapor-phase mole fractions of each species, [-] Notes ----- It is helpful to check that `fugacity_coefficients` has been implemented correctly using the following expression, from [1]_. .. math:: \ln \hat \phi_i = \left[\frac{\partial (n\log \phi)}{\partial n_i}\right]_{T,P,n_j,V_t} For reference, several expressions for fugacity of a component are as follows, shown in [1]_ and [2]_. .. math:: \ln \hat \phi_i = \int_{0}^P\left(\frac{\hat V_i} {RT} - \frac{1}{P}\right)dP \ln \hat \phi_i = \int_V^\infty \left[ \frac{1}{RT}\frac{\partial P}{ \partial n_i} - \frac{1}{V}\right] d V - \ln Z References ---------- .. [1] Hu, Jiawen, Rong Wang, and Shide Mao. "Some Useful Expressions for Deriving Component Fugacity Coefficients from Mixture Fugacity Coefficient." Fluid Phase Equilibria 268, no. 1-2 (June 25, 2008): 7-13. doi:10.1016/j.fluid.2008.03.007. .. [2] Walas, Stanley M. Phase Equilibria in Chemical Engineering. Butterworth-Heinemann, 1985. ''' if self.phase in ['l', 'l/g']: if xs is None: xs = self.zs self.phis_l = self.fugacity_coefficients(self.Z_l, zs=xs) self.fugacities_l = [phi*x*self.P for phi, x in zip(self.phis_l, xs)] self.lnphis_l = [log(i) for i in self.phis_l] if self.phase in ['g', 'l/g']: if ys is None: ys = self.zs self.phis_g = self.fugacity_coefficients(self.Z_g, zs=ys) self.fugacities_g = [phi*y*self.P for phi, y in zip(self.phis_g, ys)] self.lnphis_g = [log(i) for i in self.phis_g]
def solve_T(self, P, V, quick=True): r'''Generic method to calculate `T` from a specified `P` and `V`. Provides SciPy's `newton` solver, and iterates to solve the general equation for `P`, recalculating `a_alpha` as a function of temperature using `a_alpha_and_derivatives` each iteration. Parameters ---------- P : float Pressure, [Pa] V : float Molar volume, [m^3/mol] quick : bool, optional Unimplemented, although it may be possible to derive explicit expressions as done for many pure-component EOS Returns ------- T : float Temperature, [K] ''' self.Tc = sum(self.Tcs)/self.N # -4 goes back from object, GCEOS return super(type(self).__mro__[-3], self).solve_T(P=P, V=V, quick=quick)
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `kappa`, and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives` for every component.''' self.a, self.kappa, self.Tc = self.ais[i], self.kappas[i], self.Tcs[i]
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `m`, and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives` for every component.''' self.a, self.m, self.Tc = self.ais[i], self.ms[i], self.Tcs[i]
def fugacity_coefficients(self, Z, zs): r'''Literature formula for calculating fugacity coefficients for each species in a mixture. Verified numerically. Applicable to most derivatives of the SRK equation of state as well. Called by `fugacities` on initialization, or by a solver routine which is performing a flash calculation. .. math:: \ln \hat \phi_i = \frac{B_i}{B}(Z-1) - \ln(Z-B) + \frac{A}{B} \left[\frac{B_i}{B} - \frac{2}{a \alpha}\sum_i y_i(a\alpha)_{ij} \right]\ln\left(1+\frac{B}{Z}\right) A=\frac{a\alpha P}{R^2T^2} B = \frac{bP}{RT} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] zs : list[float], optional List of mole factions, either overall or in a specific phase, [-] Returns ------- phis : float Fugacity coefficient for each species, [-] References ---------- .. [1] Soave, Giorgio. "Equilibrium Constants from a Modified Redlich-Kwong Equation of State." Chemical Engineering Science 27, no. 6 (June 1972): 1197-1203. doi:10.1016/0009-2509(72)80096-4. .. [2] Walas, Stanley M. Phase Equilibria in Chemical Engineering. Butterworth-Heinemann, 1985. ''' A = self.a_alpha*self.P/R2/self.T**2 B = self.b*self.P/R/self.T phis = [] for i in self.cmps: Bi = self.bs[i]*self.P/R/self.T t1 = Bi/B*(Z-1) - log(Z - B) t2 = A/B*(Bi/B - 2./self.a_alpha*sum([zs[j]*self.a_alpha_ijs[i][j] for j in self.cmps])) t3 = log(1. + B/Z) t4 = t1 + t2*t3 phis.append(exp(t4)) return phis
def fugacity_coefficients(self, Z, zs): r'''Literature formula for calculating fugacity coefficients for each species in a mixture. Verified numerically. Called by `fugacities` on initialization, or by a solver routine which is performing a flash calculation. .. math:: \ln \hat \phi_i = \frac{b_i}{V-b} - \ln\left[Z\left(1 - \frac{b}{V}\right)\right] - \frac{2\sqrt{aa_i}}{RTV} Parameters ---------- Z : float Compressibility of the mixture for a desired phase, [-] zs : list[float], optional List of mole factions, either overall or in a specific phase, [-] Returns ------- phis : float Fugacity coefficient for each species, [-] References ---------- .. [1] Walas, Stanley M. Phase Equilibria in Chemical Engineering. Butterworth-Heinemann, 1985. ''' phis = [] V = Z*R*self.T/self.P for i in self.cmps: phi = self.bs[i]/(V-self.b) - log(Z*(1. - self.b/V)) - 2.*(self.a_alpha*self.ais[i])**0.5/(R*self.T*V) phis.append(exp(phi)) return phis
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `kappa0`, `kappa1`, and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives` for every component.''' if not hasattr(self, 'kappas'): self.kappas = [kappa0 + kappa1*(1 + (T/Tc)**0.5)*(0.7 - (T/Tc)) for kappa0, kappa1, Tc in zip(self.kappa0s, self.kappa1s, self.Tcs)] self.a, self.kappa, self.kappa0, self.kappa1, self.Tc = self.ais[i], self.kappas[i], self.kappa0s[i], self.kappa1s[i], self.Tcs[i]
def cleanup_a_alpha_and_derivatives(self): r'''Removes properties set by `setup_a_alpha_and_derivatives`; run by `GCEOSMIX.a_alpha_and_derivatives` after `a_alpha` is calculated for every component''' del(self.a, self.kappa, self.kappa0, self.kappa1, self.Tc)
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `kappa`, `kappa0`, `kappa1`, `kappa2`, `kappa3` and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives` for every component.''' if not hasattr(self, 'kappas'): self.kappas = [] for Tc, kappa0, kappa1, kappa2, kappa3 in zip(self.Tcs, self.kappa0s, self.kappa1s, self.kappa2s, self.kappa3s): Tr = T/Tc kappa = kappa0 + ((kappa1 + kappa2*(kappa3 - Tr)*(1. - Tr**0.5))*(1. + Tr**0.5)*(0.7 - Tr)) self.kappas.append(kappa) (self.a, self.kappa, self.kappa0, self.kappa1, self.kappa2, self.kappa3, self.Tc) = (self.ais[i], self.kappas[i], self.kappa0s[i], self.kappa1s[i], self.kappa2s[i], self.kappa3s[i], self.Tcs[i])
def cleanup_a_alpha_and_derivatives(self): r'''Removes properties set by `setup_a_alpha_and_derivatives`; run by `GCEOSMIX.a_alpha_and_derivatives` after `a_alpha` is calculated for every component''' del(self.a, self.kappa, self.kappa0, self.kappa1, self.kappa2, self.kappa3, self.Tc)
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `omega`, and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives` for every component.''' self.a, self.Tc, self.omega = self.ais[i], self.Tcs[i], self.omegas[i]
def setup_a_alpha_and_derivatives(self, i, T=None): r'''Sets `a`, `S1`, `S2` and `Tc` for a specific component before the pure-species EOS's `a_alpha_and_derivatives` method is called. Both are called by `GCEOSMIX.a_alpha_and_derivatives` for every component.''' self.a, self.Tc, self.S1, self.S2 = self.ais[i], self.Tcs[i], self.S1s[i], self.S2s[i]
def cleanup_a_alpha_and_derivatives(self): r'''Removes properties set by `setup_a_alpha_and_derivatives`; run by `GCEOSMIX.a_alpha_and_derivatives` after `a_alpha` is calculated for every component''' del(self.a, self.Tc, self.S1, self.S2)
def Sato_Riedel(T, M, Tb, Tc): r'''Calculate the thermal conductivity of a liquid as a function of temperature using the CSP method of Sato-Riedel [1]_, [2]_, published in Reid [3]_. Requires temperature, molecular weight, and boiling and critical temperatures. .. math:: k = \frac{1.1053}{\sqrt{MW}}\frac{3+20(1-T_r)^{2/3}} {3+20(1-T_{br})^{2/3}} Parameters ---------- T : float Temperature of the fluid [K] M : float Molecular weight of the fluid [g/mol] Tb : float Boiling temperature of the fluid [K] Tc : float Critical temperature of the fluid [K] Returns ------- kl : float Estimated liquid thermal conductivity [W/m/k] Notes ----- This equation has a complicated history. It is proposed by Reid [3]_. Limited accuracy should be expected. Uncheecked. Examples -------- >>> Sato_Riedel(300, 47, 390, 520) 0.21037692461337687 References ---------- .. [1] Riedel, L.: Chem. Ing. Tech., 21, 349 (1949); 23: 59, 321, 465 (1951) .. [2] Maejima, T., private communication, 1973 .. [3] Properties of Gases and Liquids", 3rd Ed., McGraw-Hill, 1977 ''' Tr = T/Tc Tbr = Tb/Tc return 1.1053*(3. + 20.*(1 - Tr)**(2/3.))*M**-0.5/(3. + 20.*(1 - Tbr)**(2/3.))
def Gharagheizi_liquid(T, M, Tb, Pc, omega): r'''Estimates the thermal conductivity of a liquid as a function of temperature using the CSP method of Gharagheizi [1]_. A convoluted method claiming high-accuracy and using only statistically significant variable following analalysis. Requires temperature, molecular weight, boiling temperature and critical pressure and acentric factor. .. math:: &k = 10^{-4}\left[10\omega + 2P_c-2T+4+1.908(T_b+\frac{1.009B^2}{MW^2}) +\frac{3.9287MW^4}{B^4}+\frac{A}{B^8}\right] &A = 3.8588MW^8(1.0045B+6.5152MW-8.9756) &B = 16.0407MW+2T_b-27.9074 Parameters ---------- T : float Temperature of the fluid [K] M : float Molecular weight of the fluid [g/mol] Tb : float Boiling temperature of the fluid [K] Pc : float Critical pressure of the fluid [Pa] omega : float Acentric factor of the fluid [-] Returns ------- kl : float Estimated liquid thermal conductivity [W/m/k] Notes ----- Pressure is internally converted into bar, as used in the original equation. This equation was derived with 19000 points representing 1640 unique compounds. Examples -------- >>> Gharagheizi_liquid(300, 40, 350, 1E6, 0.27) 0.2171113029534838 References ---------- .. [1] Gharagheizi, Farhad, Poorandokht Ilani-Kashkouli, Mehdi Sattari, Amir H. Mohammadi, Deresh Ramjugernath, and Dominique Richon. "Development of a General Model for Determination of Thermal Conductivity of Liquid Chemical Compounds at Atmospheric Pressure." AIChE Journal 59, no. 5 (May 1, 2013): 1702-8. doi:10.1002/aic.13938 ''' Pc = Pc/1E5 B = 16.0407*M + 2.*Tb - 27.9074 A = 3.8588*M**8*(1.0045*B + 6.5152*M - 8.9756) kl = 1E-4*(10.*omega + 2.*Pc - 2.*T + 4. + 1.908*(Tb + 1.009*B*B/(M*M)) + 3.9287*M**4*B**-4 + A*B**-8) return kl
def Nicola_original(T, M, Tc, omega, Hfus): r'''Estimates the thermal conductivity of a liquid as a function of temperature using the CSP method of Nicola [1]_. A simpler but long method claiming high-accuracy and using only statistically significant variable following analalysis. Requires temperature, molecular weight, critical temperature, acentric factor and the heat of vaporization. .. math:: \frac{\lambda}{1 \text{Wm/K}}=-0.5694-0.1436T_r+5.4893\times10^{-10} \frac{\Delta_{fus}H}{\text{kmol/J}}+0.0508\omega + \left(\frac{1 \text{kg/kmol}}{MW}\right)^{0.0622} Parameters ---------- T : float Temperature of the fluid [K] M : float Molecular weight of the fluid [g/mol] Tc : float Critical temperature of the fluid [K] omega : float Acentric factor of the fluid [-] Hfus : float Heat of fusion of the fluid [J/mol] Returns ------- kl : float Estimated liquid thermal conductivity [W/m/k] Notes ----- A weird statistical correlation. Recent and yet to be reviewed. This correlation has been superceded by the author's later work. Hfus is internally converted to be in J/kmol. Examples -------- >>> Nicola_original(300, 142.3, 611.7, 0.49, 201853) 0.2305018632230984 References ---------- .. [1] Nicola, Giovanni Di, Eleonora Ciarrocchi, Mariano Pierantozzi, and Roman Stryjek. "A New Equation for the Thermal Conductivity of Organic Compounds." Journal of Thermal Analysis and Calorimetry 116, no. 1 (April 1, 2014): 135-40. doi:10.1007/s10973-013-3422-7 ''' Tr = T/Tc Hfus = Hfus*1000 return -0.5694 - 0.1436*Tr + 5.4893E-10*Hfus + 0.0508*omega + (1./M)**0.0622
def Nicola(T, M, Tc, Pc, omega): r'''Estimates the thermal conductivity of a liquid as a function of temperature using the CSP method of [1]_. A statistically derived equation using any correlated terms. Requires temperature, molecular weight, critical temperature and pressure, and acentric factor. .. math:: \frac{\lambda}{0.5147 W/m/K} = -0.2537T_r+\frac{0.0017Pc}{\text{bar}} +0.1501 \omega + \left(\frac{1}{MW}\right)^{-0.2999} Parameters ---------- T : float Temperature of the fluid [K] M : float Molecular weight of the fluid [g/mol] Tc : float Critical temperature of the fluid [K] Pc : float Critical pressure of the fluid [Pa] omega : float Acentric factor of the fluid [-] Returns ------- kl : float Estimated liquid thermal conductivity [W/m/k] Notes ----- A statistical correlation. A revision of an original correlation. Examples -------- >>> Nicola(300, 142.3, 611.7, 2110000.0, 0.49) 0.10863821554584034 References ---------- .. [1] Di Nicola, Giovanni, Eleonora Ciarrocchi, Gianluca Coccia, and Mariano Pierantozzi. "Correlations of Thermal Conductivity for Liquid Refrigerants at Atmospheric Pressure or near Saturation." International Journal of Refrigeration. 2014. doi:10.1016/j.ijrefrig.2014.06.003 ''' Tr = T/Tc Pc = Pc/1E5 return 0.5147*(-0.2537*Tr + 0.0017*Pc + 0.1501*omega + (1./M)**0.2999)
def Bahadori_liquid(T, M): r'''Estimates the thermal conductivity of parafin liquid hydrocarbons. Fits their data well, and is useful as only MW is required. X is the Molecular weight, and Y the temperature. .. math:: K = a + bY + CY^2 + dY^3 a = A_1 + B_1 X + C_1 X^2 + D_1 X^3 b = A_2 + B_2 X + C_2 X^2 + D_2 X^3 c = A_3 + B_3 X + C_3 X^2 + D_3 X^3 d = A_4 + B_4 X + C_4 X^2 + D_4 X^3 Parameters ---------- T : float Temperature of the fluid [K] M : float Molecular weight of the fluid [g/mol] Returns ------- kl : float Estimated liquid thermal conductivity [W/m/k] Notes ----- The accuracy of this equation has not been reviewed. Examples -------- Data point from [1]_. >>> Bahadori_liquid(273.15, 170) 0.14274278108272603 References ---------- .. [1] Bahadori, Alireza, and Saeid Mokhatab. "Estimating Thermal Conductivity of Hydrocarbons." Chemical Engineering 115, no. 13 (December 2008): 52-54 ''' A = [-6.48326E-2, 2.715015E-3, -1.08580E-5, 9.853917E-9] B = [1.565612E-2, -1.55833E-4, 5.051114E-7, -4.68030E-10] C = [-1.80304E-4, 1.758693E-6, -5.55224E-9, 5.201365E-12] D = [5.880443E-7, -5.65898E-9, 1.764384E-11, -1.65944E-14] X, Y = M, T a = A[0] + B[0]*X + C[0]*X**2 + D[0]*X**3 b = A[1] + B[1]*X + C[1]*X**2 + D[1]*X**3 c = A[2] + B[2]*X + C[2]*X**2 + D[2]*X**3 d = A[3] + B[3]*X + C[3]*X**2 + D[3]*X**3 return a + b*Y + c*Y**2 + d*Y**3
def Mersmann_Kind_thermal_conductivity_liquid(T, MW, Tc, Vc, atoms): r'''Estimates the thermal conductivity of organic liquid substances according to the method of [1]_. .. math:: \lambda^* = \frac{\lambda\cdot V_c^{2/3}\cdot T_c\cdot \text{MW}^{0.5}} {(k\cdot T_c)^{1.5}\cdot N_A^{7/6}} \lambda^* = \frac{2}{3}\left(n_a + 40\sqrt{1-T_r}\right) Parameters ---------- T : float Temperature of the fluid [K] M : float Molecular weight of the fluid [g/mol] Tc : float Critical temperature of the fluid [K] Vc : float Critical volume of the fluid [m^3/mol] atoms : dict Dictionary of atoms and their counts, [-] Returns ------- kl : float Estimated liquid thermal conductivity [W/m/k] Notes ----- In the equation, all quantities must be in SI units but N_A is in a kmol basis and Vc is in units of (m^3/kmol); this is converted internally. Examples -------- Dodecane at 400 K: >>> Mersmann_Kind_thermal_conductivity_liquid(400, 170.33484, 658.0, ... 0.000754, {'C': 12, 'H': 26}) 0.08952713798442789 References ---------- .. [1] Mersmann, Alfons, and Matthias Kind. "Prediction of Mechanical and Thermal Properties of Pure Liquids, of Critical Data, and of Vapor Pressure." Industrial & Engineering Chemistry Research, January 31, 2017. https://doi.org/10.1021/acs.iecr.6b04323. ''' na = sum(atoms.values()) lambda_star = 2/3.*(na + 40.*(1. - T/Tc)**0.5) Vc = Vc*1000 # m^3/mol to m^3/kmol N_A2 = N_A*1000 # Their avogadro's constant is per kmol kl = lambda_star*(k*Tc)**1.5*N_A2**(7/6.)*Vc**(-2/3.)/Tc*MW**-0.5 return kl
def DIPPR9G(T, P, Tc, Pc, kl): r'''Adjustes for pressure the thermal conductivity of a liquid using an emperical formula based on [1]_, but as given in [2]_. .. math:: k = k^* \left[ 0.98 + 0.0079 P_r T_r^{1.4} + 0.63 T_r^{1.2} \left( \frac{P_r}{30 + P_r}\right)\right] Parameters ---------- T : float Temperature of fluid [K] P : float Pressure of fluid [Pa] Tc: float Critical point of fluid [K] Pc : float Critical pressure of the fluid [Pa] kl : float Thermal conductivity of liquid at 1 atm or saturation, [W/m/K] Returns ------- kl_dense : float Thermal conductivity of liquid at P, [W/m/K] Notes ----- This equation is entrely dimensionless; all dimensions cancel. The original source has not been reviewed. This is DIPPR Procedure 9G: Method for the Thermal Conductivity of Pure Nonhydrocarbon Liquids at High Pressures Examples -------- From [2]_, for butyl acetate. >>> DIPPR9G(515.05, 3.92E7, 579.15, 3.212E6, 7.085E-2) 0.0864419738671184 References ---------- .. [1] Missenard, F. A., Thermal Conductivity of Organic Liquids of a Series or a Group of Liquids , Rev. Gen.Thermodyn., 101 649 (1970). .. [2] Danner, Ronald P, and Design Institute for Physical Property Data. Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982. ''' Tr = T/Tc Pr = P/Pc return kl*(0.98 + 0.0079*Pr*Tr**1.4 + 0.63*Tr**1.2*(Pr/(30. + Pr)))
def Missenard(T, P, Tc, Pc, kl): r'''Adjustes for pressure the thermal conductivity of a liquid using an emperical formula based on [1]_, but as given in [2]_. .. math:: \frac{k}{k^*} = 1 + Q P_r^{0.7} Parameters ---------- T : float Temperature of fluid [K] P : float Pressure of fluid [Pa] Tc: float Critical point of fluid [K] Pc : float Critical pressure of the fluid [Pa] kl : float Thermal conductivity of liquid at 1 atm or saturation, [W/m/K] Returns ------- kl_dense : float Thermal conductivity of liquid at P, [W/m/K] Notes ----- This equation is entirely dimensionless; all dimensions cancel. An interpolation routine is used here from tabulated values of Q. The original source has not been reviewed. Examples -------- Example from [2]_, toluene; matches. >>> Missenard(304., 6330E5, 591.8, 41E5, 0.129) 0.2198375777069657 References ---------- .. [1] Missenard, F. A., Thermal Conductivity of Organic Liquids of a Series or a Group of Liquids , Rev. Gen.Thermodyn., 101 649 (1970). .. [2] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition. New York: McGraw-Hill Professional, 2000. ''' Tr = T/Tc Pr = P/Pc Q = float(Qfunc_Missenard(Pr, Tr)) return kl*(1. + Q*Pr**0.7)
def DIPPR9H(ws, ks): r'''Calculates thermal conductivity of a liquid mixture according to mixing rules in [1]_ and also in [2]_. .. math:: \lambda_m = \left( \sum_i w_i \lambda_i^{-2}\right)^{-1/2} Parameters ---------- ws : float Mass fractions of components ks : float Liquid thermal conductivites of all components, [W/m/K] Returns ------- kl : float Thermal conductivity of liquid mixture, [W/m/K] Notes ----- This equation is entirely dimensionless; all dimensions cancel. The example is from [2]_; all results agree. The original source has not been reviewed. DIPPR Procedure 9H: Method for the Thermal Conductivity of Nonaqueous Liquid Mixtures Average deviations of 3%. for 118 nonaqueous systems with 817 data points. Max deviation 20%. According to DIPPR. Examples -------- >>> DIPPR9H([0.258, 0.742], [0.1692, 0.1528]) 0.15657104706719646 References ---------- .. [1] Reid, Robert C.; Prausnitz, John M.; Poling, Bruce E. The Properties of Gases and Liquids. McGraw-Hill Companies, 1987. .. [2] Danner, Ronald P, and Design Institute for Physical Property Data. Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982. ''' if not none_and_length_check([ks, ws]): # check same-length inputs raise Exception('Function inputs are incorrect format') return sum(ws[i]/ks[i]**2 for i in range(len(ws)))**(-0.5)
def Filippov(ws, ks): r'''Calculates thermal conductivity of a binary liquid mixture according to mixing rules in [2]_ as found in [1]_. .. math:: \lambda_m = w_1 \lambda_1 + w_2\lambda_2 - 0.72 w_1 w_2(\lambda_2-\lambda_1) Parameters ---------- ws : float Mass fractions of components ks : float Liquid thermal conductivites of all components, [W/m/K] Returns ------- kl : float Thermal conductivity of liquid mixture, [W/m/K] Notes ----- This equation is entirely dimensionless; all dimensions cancel. The original source has not been reviewed. Only useful for binary mixtures. Examples -------- >>> Filippov([0.258, 0.742], [0.1692, 0.1528]) 0.15929167628799998 References ---------- .. [1] Reid, Robert C.; Prausnitz, John M.; Poling, Bruce E. The Properties of Gases and Liquids. McGraw-Hill Companies, 1987. .. [2] Filippov, L. P.: Vest. Mosk. Univ., Ser. Fiz. Mat. Estestv. Nauk, (8I0E): 67-69A955); Chem. Abstr., 50: 8276 A956). Filippov, L. P., and N. S. Novoselova: Vestn. Mosk. Univ., Ser. F iz. Mat. Estestv.Nauk, CI0B): 37-40A955); Chem. Abstr., 49: 11366 A955). ''' if not none_and_length_check([ks, ws], 2): # check same-length inputs raise Exception('Function inputs are incorrect format') return ws[0]*ks[0] + ws[1]*ks[1] - 0.72*ws[0]*ws[1]*(ks[1] - ks[0])
def Eucken(MW, Cvm, mu): r'''Estimates the thermal conductivity of a gas as a function of temperature using the CSP method of Eucken [1]_. .. math:: \frac{\lambda M}{\eta C_v} = 1 + \frac{9/4}{C_v/R} Parameters ---------- MW : float Molecular weight of the gas [g/mol] Cvm : float Molar contant volume heat capacity of the gas [J/mol/K] mu : float Gas viscosity [Pa*S] Returns ------- kg : float Estimated gas thermal conductivity [W/m/k] Notes ----- Temperature dependence is introduced via heat capacity and viscosity. A theoretical equation. No original author located. MW internally converted to kg/g-mol. Examples -------- 2-methylbutane at low pressure, 373.15 K. Mathes calculation in [1]_. >>> Eucken(MW=72.151, Cvm=135.9, mu=8.77E-6) 0.018792644287722975 References ---------- .. [1] Reid, Robert C.; Prausnitz, John M.; Poling, Bruce E. Properties of Gases and Liquids. McGraw-Hill Companies, 1987. ''' MW = MW/1000. return (1. + 9/4./(Cvm/R))*mu*Cvm/MW
def Eucken_modified(MW, Cvm, mu): r'''Estimates the thermal conductivity of a gas as a function of temperature using the Modified CSP method of Eucken [1]_. .. math:: \frac{\lambda M}{\eta C_v} = 1.32 + \frac{1.77}{C_v/R} Parameters ---------- MW : float Molecular weight of the gas [g/mol] Cvm : float Molar contant volume heat capacity of the gas [J/mol/K] mu : float Gas viscosity [Pa*S] Returns ------- kg : float Estimated gas thermal conductivity [W/m/k] Notes ----- Temperature dependence is introduced via heat capacity and viscosity. A theoretical equation. No original author located. MW internally converted to kg/g-mol. Examples -------- 2-methylbutane at low pressure, 373.15 K. Mathes calculation in [1]_. >>> Eucken_modified(MW=72.151, Cvm=135.9, mu=8.77E-6) 0.023593536999201956 References ---------- .. [1] Reid, Robert C.; Prausnitz, John M.; Poling, Bruce E. Properties of Gases and Liquids. McGraw-Hill Companies, 1987. ''' MW = MW/1000. return (1.32 + 1.77/(Cvm/R))*mu*Cvm/MW
def DIPPR9B(T, MW, Cvm, mu, Tc=None, chemtype=None): r'''Calculates the thermal conductivity of a gas using one of several emperical equations developed in [1]_, [2]_, and presented in [3]_. For monoatomic gases: .. math:: k = 2.5 \frac{\eta C_v}{MW} For linear molecules: .. math:: k = \frac{\eta}{MW} \left( 1.30 C_v + 14644.00 - \frac{2928.80}{T_r}\right) For nonlinear molecules: .. math:: k = \frac{\eta}{MW}(1.15C_v + 16903.36) Parameters ---------- T : float Temperature of the fluid [K] Tc : float Critical temperature of the fluid [K] MW : float Molwcular weight of fluid [g/mol] Cvm : float Molar heat capacity at constant volume of fluid, [J/mol/K] mu : float Viscosity of gas, [Pa*S] Returns ------- k_g : float Thermal conductivity of gas, [W/m/k] Notes ----- Tested with DIPPR values. Cvm is internally converted to J/kmol/K. Examples -------- CO: >>> DIPPR9B(200., 28.01, 20.826, 1.277E-5, 132.92, chemtype='linear') 0.01813208676438415 References ---------- .. [1] Bromley, LeRoy A., Berkeley. University of California, and U.S. Atomic Energy Commission. Thermal Conductivity of Gases at Moderate Pressures. UCRL;1852. Berkeley, CA: University of California Radiation Laboratory, 1952. .. [2] Stiel, Leonard I., and George Thodos. "The Thermal Conductivity of Nonpolar Substances in the Dense Gaseous and Liquid Regions." AIChE Journal 10, no. 1 (January 1, 1964): 26-30. doi:10.1002/aic.690100114 .. [3] Danner, Ronald P, and Design Institute for Physical Property Data. Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982. ''' Cvm = Cvm*1000. # J/g/K to J/kmol/K if not chemtype: chemtype = 'linear' if chemtype == 'monoatomic': return 2.5*mu*Cvm/MW elif chemtype == 'linear': Tr = T/Tc return mu/MW*(1.30*Cvm + 14644 - 2928.80/Tr) elif chemtype == 'nonlinear': return mu/MW*(1.15*Cvm + 16903.36) else: raise Exception('Specified chemical type is not an option')
def Chung(T, MW, Tc, omega, Cvm, mu): r'''Estimates the thermal conductivity of a gas as a function of temperature using the CSP method of Chung [1]_. .. math:: \frac{\lambda M}{\eta C_v} = \frac{3.75 \Psi}{C_v/R} \Psi = 1 + \alpha \left\{[0.215+0.28288\alpha-1.061\beta+0.26665Z]/ [0.6366+\beta Z + 1.061 \alpha \beta]\right\} \alpha = \frac{C_v}{R}-1.5 \beta = 0.7862-0.7109\omega + 1.3168\omega^2 Z=2+10.5T_r^2 Parameters ---------- T : float Temperature of the gas [K] MW : float Molecular weight of the gas [g/mol] Tc : float Critical temperature of the gas [K] omega : float Acentric factor of the gas [-] Cvm : float Molar contant volume heat capacity of the gas [J/mol/K] mu : float Gas viscosity [Pa*S] Returns ------- kg : float Estimated gas thermal conductivity [W/m/k] Notes ----- MW internally converted to kg/g-mol. Examples -------- 2-methylbutane at low pressure, 373.15 K. Mathes calculation in [2]_. >>> Chung(T=373.15, MW=72.151, Tc=460.4, omega=0.227, Cvm=135.9, mu=8.77E-6) 0.023015653729496946 References ---------- .. [1] Chung, Ting Horng, Lloyd L. Lee, and Kenneth E. Starling. "Applications of Kinetic Gas Theories and Multiparameter Correlation for Prediction of Dilute Gas Viscosity and Thermal Conductivity." Industrial & Engineering Chemistry Fundamentals 23, no. 1 (February 1, 1984): 8-13. doi:10.1021/i100013a002 .. [2] Reid, Robert C.; Prausnitz, John M.; Poling, Bruce E. Properties of Gases and Liquids. McGraw-Hill Companies, 1987. ''' MW = MW/1000. alpha = Cvm/R - 1.5 beta = 0.7862 - 0.7109*omega + 1.3168*omega**2 Z = 2 + 10.5*(T/Tc)**2 psi = 1 + alpha*((0.215 + 0.28288*alpha - 1.061*beta + 0.26665*Z) /(0.6366 + beta*Z + 1.061*alpha*beta)) return 3.75*psi/(Cvm/R)/MW*mu*Cvm
def eli_hanley(T, MW, Tc, Vc, Zc, omega, Cvm): r'''Estimates the thermal conductivity of a gas as a function of temperature using the reference fluid method of Eli and Hanley [1]_ as shown in [2]_. .. math:: \lambda = \lambda^* + \frac{\eta^*}{MW}(1.32)\left(C_v - \frac{3R}{2}\right) Tr = \text{min}(Tr, 2) \theta = 1 + (\omega-0.011)\left(0.56553 - 0.86276\ln Tr - \frac{0.69852}{Tr}\right) \psi = [1 + (\omega - 0.011)(0.38560 - 1.1617\ln Tr)]\frac{0.288}{Z_c} f = \frac{T_c}{190.4}\theta h = \frac{V_c}{9.92E-5}\psi T_0 = T/f \eta_0^*(T_0)= \sum_{n=1}^9 C_n T_0^{(n-4)/3} \theta_0 = 1944 \eta_0 \lambda^* = \lambda_0 H \eta^* = \eta^*_0 H \frac{MW}{16.04} H = \left(\frac{16.04}{MW}\right)^{0.5}f^{0.5}/h^{2/3} Parameters ---------- T : float Temperature of the gas [K] MW : float Molecular weight of the gas [g/mol] Tc : float Critical temperature of the gas [K] Vc : float Critical volume of the gas [m^3/mol] Zc : float Critical compressibility of the gas [] omega : float Acentric factor of the gas [-] Cvm : float Molar contant volume heat capacity of the gas [J/mol/K] Returns ------- kg : float Estimated gas thermal conductivity [W/m/k] Notes ----- Reference fluid is Methane. MW internally converted to kg/g-mol. Examples -------- 2-methylbutane at low pressure, 373.15 K. Mathes calculation in [2]_. >>> eli_hanley(T=373.15, MW=72.151, Tc=460.4, Vc=3.06E-4, Zc=0.267, ... omega=0.227, Cvm=135.9) 0.02247951789135337 References ---------- .. [1] Ely, James F., and H. J. M. Hanley. "Prediction of Transport Properties. 2. Thermal Conductivity of Pure Fluids and Mixtures." Industrial & Engineering Chemistry Fundamentals 22, no. 1 (February 1, 1983): 90-97. doi:10.1021/i100009a016. .. [2] Reid, Robert C.; Prausnitz, John M.; Poling, Bruce E. Properties of Gases and Liquids. McGraw-Hill Companies, 1987. ''' Cs = [2.907741307E6, -3.312874033E6, 1.608101838E6, -4.331904871E5, 7.062481330E4, -7.116620750E3, 4.325174400E2, -1.445911210E1, 2.037119479E-1] Tr = T/Tc if Tr > 2: Tr = 2 theta = 1 + (omega - 0.011)*(0.56553 - 0.86276*log(Tr) - 0.69852/Tr) psi = (1 + (omega-0.011)*(0.38560 - 1.1617*log(Tr)))*0.288/Zc f = Tc/190.4*theta h = Vc/9.92E-5*psi T0 = T/f eta0 = 1E-7*sum([Ci*T0**((i+1. - 4.)/3.) for i, Ci in enumerate(Cs)]) k0 = 1944*eta0 H = (16.04/MW)**0.5*f**0.5*h**(-2/3.) etas = eta0*H*MW/16.04 ks = k0*H return ks + etas/(MW/1000.)*1.32*(Cvm - 1.5*R)
def Gharagheizi_gas(T, MW, Tb, Pc, omega): r'''Estimates the thermal conductivity of a gas as a function of temperature using the CSP method of Gharagheizi [1]_. A convoluted method claiming high-accuracy and using only statistically significant variable following analalysis. Requires temperature, molecular weight, boiling temperature and critical pressure and acentric factor. .. math:: k = 7.9505\times 10^{-4} + 3.989\times 10^{-5} T -5.419\times 10^-5 M + 3.989\times 10^{-5} A A = \frac{\left(2\omega + T - \frac{(2\omega + 3.2825)T}{T_b} + 3.2825\right)}{0.1MP_cT} \times (3.9752\omega + 0.1 P_c + 1.9876B + 6.5243)^2 Parameters ---------- T : float Temperature of the fluid [K] MW: float Molecular weight of the fluid [g/mol] Tb : float Boiling temperature of the fluid [K] Pc : float Critical pressure of the fluid [Pa] omega : float Acentric factor of the fluid [-] Returns ------- kg : float Estimated gas thermal conductivity [W/m/k] Notes ----- Pressure is internally converted into 10*kPa but author used correlation with kPa; overall, errors have been corrected in the presentation of the formula. This equation was derived with 15927 points and 1574 compounds. Example value from [1]_ is the first point in the supportinf info, for CH4. Examples -------- >>> Gharagheizi_gas(580., 16.04246, 111.66, 4599000.0, 0.0115478000) 0.09594861261873211 References ---------- .. [1] Gharagheizi, Farhad, Poorandokht Ilani-Kashkouli, Mehdi Sattari, Amir H. Mohammadi, Deresh Ramjugernath, and Dominique Richon. "Development of a General Model for Determination of Thermal Conductivity of Liquid Chemical Compounds at Atmospheric Pressure." AIChE Journal 59, no. 5 (May 1, 2013): 1702-8. doi:10.1002/aic.13938 ''' Pc = Pc/1E4 B = T + (2.*omega + 2.*T - 2.*T*(2.*omega + 3.2825)/Tb + 3.2825)/(2*omega + T - T*(2*omega+3.2825)/Tb + 3.2825) - T*(2*omega+3.2825)/Tb A = (2*omega + T - T*(2*omega + 3.2825)/Tb + 3.2825)/(0.1*MW*Pc*T) * (3.9752*omega + 0.1*Pc + 1.9876*B + 6.5243)**2 return 7.9505E-4 + 3.989E-5*T - 5.419E-5*MW + 3.989E-5*A
def Bahadori_gas(T, MW): r'''Estimates the thermal conductivity of hydrocarbons gases at low P. Fits their data well, and is useful as only MW is required. Y is the Molecular weight, and X the temperature. .. math:: K = a + bY + CY^2 + dY^3 a = A_1 + B_1 X + C_1 X^2 + D_1 X^3 b = A_2 + B_2 X + C_2 X^2 + D_2 X^3 c = A_3 + B_3 X + C_3 X^2 + D_3 X^3 d = A_4 + B_4 X + C_4 X^2 + D_4 X^3 Parameters ---------- T : float Temperature of the gas [K] MW : float Molecular weight of the gas [g/mol] Returns ------- kg : float Estimated gas thermal conductivity [W/m/k] Notes ----- The accuracy of this equation has not been reviewed. Examples -------- >>> Bahadori_gas(40+273.15, 20) # Point from article 0.031968165337873326 References ---------- .. [1] Bahadori, Alireza, and Saeid Mokhatab. "Estimating Thermal Conductivity of Hydrocarbons." Chemical Engineering 115, no. 13 (December 2008): 52-54 ''' A = [4.3931323468E-1, -3.88001122207E-2, 9.28616040136E-4, -6.57828995724E-6] B = [-2.9624238519E-3, 2.67956145820E-4, -6.40171884139E-6, 4.48579040207E-8] C = [7.54249790107E-6, -6.46636219509E-7, 1.5124510261E-8, -1.0376480449E-10] D = [-6.0988433456E-9, 5.20752132076E-10, -1.19425545729E-11, 8.0136464085E-14] X, Y = T, MW a = A[0] + B[0]*X + C[0]*X**2 + D[0]*X**3 b = A[1] + B[1]*X + C[1]*X**2 + D[1]*X**3 c = A[2] + B[2]*X + C[2]*X**2 + D[2]*X**3 d = A[3] + B[3]*X + C[3]*X**2 + D[3]*X**3 return a + b*Y + c*Y**2 + d*Y**3
def stiel_thodos_dense(T, MW, Tc, Pc, Vc, Zc, Vm, kg): r'''Estimates the thermal conductivity of a gas at high pressure as a function of temperature using difference method of Stiel and Thodos [1]_ as shown in [2]_. if \rho_r < 0.5: .. math:: (\lambda-\lambda^\circ)\Gamma Z_c^5=1.22\times 10^{-2} [\exp(0.535 \rho_r)-1] if 0.5 < \rho_r < 2.0: .. math:: (\lambda-\lambda^\circ)\Gamma Z_c^5=1.22\times 10^{-2} [\exp(0.535 \rho_r)-1] if 2 < \rho_r < 2.8: .. math:: (\lambda-\lambda^\circ)\Gamma Z_c^5=1.22\times 10^{-2} [\exp(0.535 \rho_r)-1] \Gamma = 210 \left(\frac{T_cMW^3}{P_c^4}\right)^{1/6} Parameters ---------- T : float Temperature of the gas [K] MW : float Molecular weight of the gas [g/mol] Tc : float Critical temperature of the gas [K] Pc : float Critical pressure of the gas [Pa] Vc : float Critical volume of the gas [m^3/mol] Zc : float Critical compressibility of the gas [-] Vm : float Molar volume of the gas at T and P [m^3/mol] kg : float Low-pressure gas thermal conductivity [W/m/k] Returns ------- kg : float Estimated dense gas thermal conductivity [W/m/k] Notes ----- Pc is internally converted to bar. Examples -------- >>> stiel_thodos_dense(T=378.15, MW=44.013, Tc=309.6, Pc=72.4E5, ... Vc=97.4E-6, Zc=0.274, Vm=144E-6, kg=2.34E-2) 0.041245574404863684 References ---------- .. [1] Stiel, Leonard I., and George Thodos. "The Thermal Conductivity of Nonpolar Substances in the Dense Gaseous and Liquid Regions." AIChE Journal 10, no. 1 (January 1, 1964): 26-30. doi:10.1002/aic.690100114. .. [2] Reid, Robert C.; Prausnitz, John M.; Poling, Bruce E. Properties of Gases and Liquids. McGraw-Hill Companies, 1987. ''' gamma = 210*(Tc*MW**3./(Pc/1E5)**4)**(1/6.) rhor = Vc/Vm if rhor < 0.5: term = 1.22E-2*(exp(0.535*rhor) - 1.) elif rhor < 2: term = 1.14E-2*(exp(0.67*rhor) - 1.069) else: # Technically only up to 2.8 term = 2.60E-3*(exp(1.155*rhor) + 2.016) diff = term/Zc**5/gamma kg = kg + diff return kg
def eli_hanley_dense(T, MW, Tc, Vc, Zc, omega, Cvm, Vm): r'''Estimates the thermal conductivity of a gas at high pressure as a function of temperature using the reference fluid method of Eli and Hanley [1]_ as shown in [2]_. .. math:: Tr = min(Tr, 2) Vr = min(Vr, 2) f = \frac{T_c}{190.4}\theta h = \frac{V_c}{9.92E-5}\psi T_0 = T/f \rho_0 = \frac{16.04}{V}h \theta = 1 + (\omega-0.011)\left(0.09057 - 0.86276\ln Tr + \left( 0.31664 - \frac{0.46568}{Tr}\right) (V_r - 0.5)\right) \psi = [1 + (\omega - 0.011)(0.39490(V_r - 1.02355) - 0.93281(V_r - 0.75464)\ln T_r]\frac{0.288}{Z_c} \lambda_1 = 1944 \eta_0 \lambda_2 = \left\{b_1 + b_2\left[b_3 - \ln \left(\frac{T_0}{b_4} \right)\right]^2\right\}\rho_0 \lambda_3 = \exp\left(a_1 + \frac{a_2}{T_0}\right)\left\{\exp[(a_3 + \frac{a_4}{T_0^{1.5}})\rho_0^{0.1} + (\frac{\rho_0}{0.1617} - 1) \rho_0^{0.5}(a_5 + \frac{a_6}{T_0} + \frac{a_7}{T_0^2})] - 1\right\} \lambda^{**} = [\lambda_1 + \lambda_2 + \lambda_3]H H = \left(\frac{16.04}{MW}\right)^{0.5}f^{0.5}/h^{2/3} X = \left\{\left[1 - \frac{T}{f}\left(\frac{df}{dT}\right)_v \right] \frac{0.288}{Z_c}\right\}^{1.5} \left(\frac{df}{dT}\right)_v = \frac{T_c}{190.4}\left(\frac{d\theta} {d T}\right)_v \left(\frac{d\theta}{d T}\right)_v = (\omega-0.011)\left[ \frac{-0.86276}{T} + (V_r-0.5)\frac{0.46568T_c}{T^2}\right] Parameters ---------- T : float Temperature of the gas [K] MW : float Molecular weight of the gas [g/mol] Tc : float Critical temperature of the gas [K] Vc : float Critical volume of the gas [m^3/mol] Zc : float Critical compressibility of the gas [] omega : float Acentric factor of the gas [-] Cvm : float Molar contant volume heat capacity of the gas [J/mol/K] Vm : float Volume of the gas at T and P [m^3/mol] Returns ------- kg : float Estimated dense gas thermal conductivity [W/m/k] Notes ----- Reference fluid is Methane. MW internally converted to kg/g-mol. Examples -------- >>> eli_hanley_dense(T=473., MW=42.081, Tc=364.9, Vc=1.81E-4, Zc=0.274, ... omega=0.144, Cvm=82.70, Vm=1.721E-4) 0.06038475936515042 References ---------- .. [1] Ely, James F., and H. J. M. Hanley. "Prediction of Transport Properties. 2. Thermal Conductivity of Pure Fluids and Mixtures." Industrial & Engineering Chemistry Fundamentals 22, no. 1 (February 1, 1983): 90-97. doi:10.1021/i100009a016. .. [2] Reid, Robert C.; Prausnitz, John M.; Poling, Bruce E. Properties of Gases and Liquids. McGraw-Hill Companies, 1987. ''' Cs = [2.907741307E6, -3.312874033E6, 1.608101838E6, -4.331904871E5, 7.062481330E4, -7.116620750E3, 4.325174400E2, -1.445911210E1, 2.037119479E-1] Tr = T/Tc if Tr > 2: Tr = 2 Vr = Vm/Vc if Vr > 2: Vr = 2 theta = 1 + (omega - 0.011)*(0.09057 - 0.86276*log(Tr) + (0.31664 - 0.46568/Tr)*(Vr-0.5)) psi = (1 + (omega-0.011)*(0.39490*(Vr-1.02355) - 0.93281*(Vr-0.75464)*log(Tr)))*0.288/Zc f = Tc/190.4*theta h = Vc/9.92E-5*psi T0 = T/f rho0 = 16.04/(Vm*1E6)*h # Vm must be in cm^3/mol here. eta0 = 1E-7*sum([Cs[i]*T0**((i+1-4)/3.) for i in range(len(Cs))]) k1 = 1944*eta0 b1 = -0.25276920E0 b2 = 0.334328590E0 b3 = 1.12 b4 = 0.1680E3 k2 = (b1 + b2*(b3 - log(T0/b4))**2)/1000.*rho0 a1 = -7.19771 a2 = 85.67822 a3 = 12.47183 a4 = -984.6252 a5 = 0.3594685 a6 = 69.79841 a7 = -872.8833 k3 = exp(a1 + a2/T0)*(exp((a3 + a4/T0**1.5)*rho0**0.1 + (rho0/0.1617 - 1)*rho0**0.5*(a5 + a6/T0 + a7/T0**2)) - 1)/1000. if T/Tc > 2: dtheta = 0 else: dtheta = (omega - 0.011)*(-0.86276/T + (Vr-0.5)*0.46568*Tc/T**2) dfdT = Tc/190.4*dtheta X = ((1 - T/f*dfdT)*0.288/Zc)**1.5 H = (16.04/MW)**0.5*f**0.5/h**(2/3.) ks = (k1*X + k2 + k3)*H ### Uses calculations similar to those for pure species here theta = 1 + (omega - 0.011)*(0.56553 - 0.86276*log(Tr) - 0.69852/Tr) psi = (1 + (omega-0.011)*(0.38560 - 1.1617*log(Tr)))*0.288/Zc f = Tc/190.4*theta h = Vc/9.92E-5*psi T0 = T/f eta0 = 1E-7*sum([Cs[i]*T0**((i+1-4)/3.) for i in range(len(Cs))]) H = (16.04/MW)**0.5*f**0.5/h**(2/3.) etas = eta0*H*MW/16.04 k = ks + etas/(MW/1000.)*1.32*(Cvm-3*R/2.) return k
def chung_dense(T, MW, Tc, Vc, omega, Cvm, Vm, mu, dipole, association=0): r'''Estimates the thermal conductivity of a gas at high pressure as a function of temperature using the reference fluid method of Chung [1]_ as shown in [2]_. .. math:: \lambda = \frac{31.2 \eta^\circ \Psi}{M'}(G_2^{-1} + B_6 y)+qB_7y^2T_r^{1/2}G_2 \Psi = 1 + \alpha \left\{[0.215+0.28288\alpha-1.061\beta+0.26665Z]/ [0.6366+\beta Z + 1.061 \alpha \beta]\right\} \alpha = \frac{C_v}{R}-1.5 \beta = 0.7862-0.7109\omega + 1.3168\omega^2 Z=2+10.5T_r^2 q = 3.586\times 10^{-3} (T_c/M')^{1/2}/V_c^{2/3} y = \frac{V_c}{6V} G_1 = \frac{1-0.5y}{(1-y)^3} G_2 = \frac{(B_1/y)[1-\exp(-B_4y)]+ B_2G_1\exp(B_5y) + B_3G_1} {B_1B_4 + B_2 + B_3} B_i = a_i + b_i \omega + c_i \mu_r^4 + d_i \kappa Parameters ---------- T : float Temperature of the gas [K] MW : float Molecular weight of the gas [g/mol] Tc : float Critical temperature of the gas [K] Vc : float Critical volume of the gas [m^3/mol] omega : float Acentric factor of the gas [-] Cvm : float Molar contant volume heat capacity of the gas [J/mol/K] Vm : float Molar volume of the gas at T and P [m^3/mol] mu : float Low-pressure gas viscosity [Pa*S] dipole : float Dipole moment [debye] association : float, optional Association factor [-] Returns ------- kg : float Estimated dense gas thermal conductivity [W/m/k] Notes ----- MW internally converted to kg/g-mol. Vm internally converted to mL/mol. [1]_ is not the latest form as presented in [1]_. Association factor is assumed 0. Relates to the polarity of the gas. Coefficients as follows: ais = [2.4166E+0, -5.0924E-1, 6.6107E+0, 1.4543E+1, 7.9274E-1, -5.8634E+0, 9.1089E+1] bis = [7.4824E-1, -1.5094E+0, 5.6207E+0, -8.9139E+0, 8.2019E-1, 1.2801E+1, 1.2811E+2] cis = [-9.1858E-1, -4.9991E+1, 6.4760E+1, -5.6379E+0, -6.9369E-1, 9.5893E+0, -5.4217E+1] dis = [1.2172E+2, 6.9983E+1, 2.7039E+1, 7.4344E+1, 6.3173E+0, 6.5529E+1, 5.2381E+2] Examples -------- >>> chung_dense(T=473., MW=42.081, Tc=364.9, Vc=184.6E-6, omega=0.142, ... Cvm=82.67, Vm=172.1E-6, mu=134E-7, dipole=0.4) 0.06160570379787278 References ---------- .. [1] Chung, Ting Horng, Mohammad Ajlan, Lloyd L. Lee, and Kenneth E. Starling. "Generalized Multiparameter Correlation for Nonpolar and Polar Fluid Transport Properties." Industrial & Engineering Chemistry Research 27, no. 4 (April 1, 1988): 671-79. doi:10.1021/ie00076a024. .. [2] Poling, Bruce E. The Properties of Gases and Liquids. 5th edition. New York: McGraw-Hill Professional, 2000. ''' ais = [2.4166E+0, -5.0924E-1, 6.6107E+0, 1.4543E+1, 7.9274E-1, -5.8634E+0, 9.1089E+1] bis = [7.4824E-1, -1.5094E+0, 5.6207E+0, -8.9139E+0, 8.2019E-1, 1.2801E+1, 1.2811E+2] cis = [-9.1858E-1, -4.9991E+1, 6.4760E+1, -5.6379E+0, -6.9369E-1, 9.5893E+0, -5.4217E+1] dis = [1.2172E+2, 6.9983E+1, 2.7039E+1, 7.4344E+1, 6.3173E+0, 6.5529E+1, 5.2381E+2] Tr = T/Tc mur = 131.3*dipole/(Vc*1E6*Tc)**0.5 # From Chung Method alpha = Cvm/R - 1.5 beta = 0.7862 - 0.7109*omega + 1.3168*omega**2 Z = 2 + 10.5*(T/Tc)**2 psi = 1 + alpha*((0.215 + 0.28288*alpha - 1.061*beta + 0.26665*Z)/(0.6366 + beta*Z + 1.061*alpha*beta)) y = Vc/(6*Vm) B1, B2, B3, B4, B5, B6, B7 = [ais[i] + bis[i]*omega + cis[i]*mur**4 + dis[i]*association for i in range(7)] G1 = (1 - 0.5*y)/(1. - y)**3 G2 = (B1/y*(1 - exp(-B4*y)) + B2*G1*exp(B5*y) + B3*G1)/(B1*B4 + B2 + B3) q = 3.586E-3*(Tc/(MW/1000.))**0.5/(Vc*1E6)**(2/3.) return 31.2*mu*psi/(MW/1000.)*(G2**-1 + B6*y) + q*B7*y**2*Tr**0.5*G2
def Lindsay_Bromley(T, ys, ks, mus, Tbs, MWs): r'''Calculates thermal conductivity of a gas mixture according to mixing rules in [1]_ and also in [2]_. .. math:: k = \sum \frac{y_i k_i}{\sum y_i A_{ij}} A_{ij} = \frac{1}{4} \left\{ 1 + \left[\frac{\eta_i}{\eta_j} \left(\frac{MW_j}{MW_i}\right)^{0.75} \left( \frac{T+S_i}{T+S_j}\right) \right]^{0.5} \right\}^2 \left( \frac{T+S_{ij}}{T+S_i}\right) S_{ij} = S_{ji} = (S_i S_j)^{0.5} Parameters ---------- T : float Temperature of gas [K] ys : float Mole fractions of gas components ks : float Liquid thermal conductivites of all components, [W/m/K] mus : float Gas viscosities of all components, [Pa*S] Tbs : float Boiling points of all components, [K] MWs : float Molecular weights of all components, [g/mol] Returns ------- kg : float Thermal conductivity of gas mixture, [W/m/K] Notes ----- This equation is entirely dimensionless; all dimensions cancel. The example is from [2]_; all results agree. The original source has not been reviewed. DIPPR Procedure 9D: Method for the Thermal Conductivity of Gas Mixtures Average deviations of 4-5% for 77 binary mixtures reviewed in [2]_, from 1342 points; also six ternary mixtures (70 points); max deviation observed was 40%. (DIPPR) TODO: Finish documenting this. Examples -------- >>> Lindsay_Bromley(323.15, [0.23, 0.77], [1.939E-2, 1.231E-2], [1.002E-5, 1.015E-5], [248.31, 248.93], [46.07, 50.49]) 0.01390264417969313 References ---------- .. [1] Lindsay, Alexander L., and LeRoy A. Bromley. "Thermal Conductivity of Gas Mixtures." Industrial & Engineering Chemistry 42, no. 8 (August 1, 1950): 1508-11. doi:10.1021/ie50488a017. .. [2] Danner, Ronald P, and Design Institute for Physical Property Data. Manual for Predicting Chemical Process Design Data. New York, N.Y, 1982. ''' if not none_and_length_check([ys, ks, mus, Tbs, MWs]): raise Exception('Function inputs are incorrect format') cmps = range(len(ys)) Ss = [1.5*Tb for Tb in Tbs] Sij = [[(Si*Sj)**0.5 for Sj in Ss] for Si in Ss] Aij = [[0.25*(1. + (mus[i]/mus[j]*(MWs[j]/MWs[i])**0.75 *(T+Ss[i])/(T+Ss[j]))**0.5 )**2 *(T+Sij[i][j])/(T+Ss[i]) for j in cmps] for i in cmps] return sum([ys[i]*ks[i]/sum(ys[j]*Aij[i][j] for j in cmps) for i in cmps])
def load_all_methods(self): r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, :obj:`all_methods` and obj:`all_methods_P` as a set of methods for which the data exists for. Called on initialization only. See the source code for the variables at which the coefficients are stored. The coefficients can safely be altered once the class is initialized. This method can be called again to reset the parameters. ''' methods, methods_P = [], [] Tmins, Tmaxs = [], [] if self.CASRN in _VDISaturationDict: methods.append(VDI_TABULAR) Ts, props = VDI_tabular_data(self.CASRN, 'K (l)') self.VDI_Tmin = Ts[0] self.VDI_Tmax = Ts[-1] self.tabular_data[VDI_TABULAR] = (Ts, props) Tmins.append(self.VDI_Tmin); Tmaxs.append(self.VDI_Tmax) if has_CoolProp and self.CASRN in coolprop_dict: methods.append(COOLPROP); methods_P.append(COOLPROP) self.CP_f = coolprop_fluids[self.CASRN] Tmins.append(self.CP_f.Tmin); Tmaxs.append(self.CP_f.Tc) if self.MW: methods.extend([BAHADORI_L, LAKSHMI_PRASAD]) # Tmin and Tmax are not extended by these simple models, who often # give values of 0; BAHADORI_L even has 3 roots. # LAKSHMI_PRASAD works down to 0 K, and has an upper limit of # 50.0*(131.0*sqrt(M) + 2771.0)/(50.0*M**0.5 + 197.0) # where it becomes 0. if self.CASRN in Perrys2_315.index: methods.append(DIPPR_PERRY_8E) _, C1, C2, C3, C4, C5, self.Perrys2_315_Tmin, self.Perrys2_315_Tmax = _Perrys2_315_values[Perrys2_315.index.get_loc(self.CASRN)].tolist() self.Perrys2_315_coeffs = [C1, C2, C3, C4, C5] Tmins.append(self.Perrys2_315_Tmin); Tmaxs.append(self.Perrys2_315_Tmax) if self.CASRN in VDI_PPDS_9.index: _, A, B, C, D, E = _VDI_PPDS_9_values[VDI_PPDS_9.index.get_loc(self.CASRN)].tolist() self.VDI_PPDS_coeffs = [A, B, C, D, E] self.VDI_PPDS_coeffs.reverse() methods.append(VDI_PPDS) if all([self.MW, self.Tm]): methods.append(SHEFFY_JOHNSON) Tmins.append(0); Tmaxs.append(self.Tm + 793.65) # Works down to 0, has a nice limit at T = Tm+793.65 from Sympy if all([self.Tb, self.Pc, self.omega]): methods.append(GHARAGHEIZI_L) Tmins.append(self.Tb); Tmaxs.append(self.Tc) # Chosen as the model is weird if all([self.Tc, self.Pc, self.omega]): methods.append(NICOLA) if all([self.Tb, self.Tc]): methods.append(SATO_RIEDEL) if all([self.Hfus, self.Tc, self.omega]): methods.append(NICOLA_ORIGINAL) if all([self.Tc, self.Pc]): methods_P.extend([DIPPR_9G, MISSENARD]) self.all_methods = set(methods) self.all_methods_P = set(methods_P) if Tmins and Tmaxs: self.Tmin, self.Tmax = min(Tmins), max(Tmaxs)
def calculate(self, T, method): r'''Method to calculate low-pressure liquid thermal conductivity at tempearture `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature of the liquid, [K] method : str Name of the method to use Returns ------- kl : float Thermal conductivity of the liquid at T and a low pressure, [W/m/K] ''' if method == SHEFFY_JOHNSON: kl = Sheffy_Johnson(T, self.MW, self.Tm) elif method == SATO_RIEDEL: kl = Sato_Riedel(T, self.MW, self.Tb, self.Tc) elif method == GHARAGHEIZI_L: kl = Gharagheizi_liquid(T, self.MW, self.Tb, self.Pc, self.omega) elif method == NICOLA: kl = Nicola(T, self.MW, self.Tc, self.Pc, self.omega) elif method == NICOLA_ORIGINAL: kl = Nicola_original(T, self.MW, self.Tc, self.omega, self.Hfus) elif method == LAKSHMI_PRASAD: kl = Lakshmi_Prasad(T, self.MW) elif method == BAHADORI_L: kl = Bahadori_liquid(T, self.MW) elif method == DIPPR_PERRY_8E: kl = EQ100(T, *self.Perrys2_315_coeffs) elif method == VDI_PPDS: kl = horner(self.VDI_PPDS_coeffs, T) elif method == COOLPROP: kl = CoolProp_T_dependent_property(T, self.CASRN, 'L', 'l') elif method in self.tabular_data: kl = self.interpolate(T, method) return kl
def calculate_P(self, T, P, method): r'''Method to calculate pressure-dependent liquid thermal conductivity at temperature `T` and pressure `P` with a given method. This method has no exception handling; see `TP_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculate liquid thermal conductivity, [K] P : float Pressure at which to calculate liquid thermal conductivity, [K] method : str Name of the method to use Returns ------- kl : float Thermal conductivity of the liquid at T and P, [W/m/K] ''' if method == DIPPR_9G: kl = self.T_dependent_property(T) kl = DIPPR9G(T, P, self.Tc, self.Pc, kl) elif method == MISSENARD: kl = self.T_dependent_property(T) kl = Missenard(T, P, self.Tc, self.Pc, kl) elif method == COOLPROP: kl = PropsSI('L', 'T', T, 'P', P, self.CASRN) elif method in self.tabular_data: kl = self.interpolate_P(T, P, method) return kl
def load_all_methods(self): r'''Method to initialize the object by precomputing any values which may be used repeatedly and by retrieving mixture-specific variables. All data are stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods which should work to calculate the property. Called on initialization only. See the source code for the variables at which the coefficients are stored. The coefficients can safely be altered once the class is initialized. This method can be called again to reset the parameters. ''' methods = [DIPPR_9H, SIMPLE] if len(self.CASs) == 2: methods.append(FILIPPOV) if '7732-18-5' in self.CASs and len(self.CASs)>1: wCASs = [i for i in self.CASs if i != '7732-18-5'] if all([i in Magomedovk_thermal_cond.index for i in wCASs]): methods.append(MAGOMEDOV) self.wCASs = wCASs self.index_w = self.CASs.index('7732-18-5') self.all_methods = set(methods) Tmins = [i.Tmin for i in self.ThermalConductivityLiquids if i.Tmin] Tmaxs = [i.Tmax for i in self.ThermalConductivityLiquids if i.Tmax] if Tmins: self.Tmin = max(Tmins) if Tmaxs: self.Tmax = max(Tmaxs)
def calculate(self, T, P, zs, ws, method): r'''Method to calculate thermal conductivity of a liquid mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : float Temperature at which to calculate the property, [K] P : float Pressure at which to calculate the property, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] method : str Name of the method to use Returns ------- k : float Thermal conductivity of the liquid mixture, [W/m/K] ''' if method == SIMPLE: ks = [i(T, P) for i in self.ThermalConductivityLiquids] return mixing_simple(zs, ks) elif method == DIPPR_9H: ks = [i(T, P) for i in self.ThermalConductivityLiquids] return DIPPR9H(ws, ks) elif method == FILIPPOV: ks = [i(T, P) for i in self.ThermalConductivityLiquids] return Filippov(ws, ks) elif method == MAGOMEDOV: k_w = self.ThermalConductivityLiquids[self.index_w](T, P) ws = list(ws) ; ws.pop(self.index_w) return thermal_conductivity_Magomedov(T, P, ws, self.wCASs, k_w) else: raise Exception('Method not valid')
def load_all_methods(self): r'''Method which picks out coefficients for the specified chemical from the various dictionaries and DataFrames storing it. All data is stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, :obj:`all_methods` and obj:`all_methods_P` as a set of methods for which the data exists for. Called on initialization only. See the source code for the variables at which the coefficients are stored. The coefficients can safely be altered once the class is initialized. This method can be called again to reset the parameters. ''' methods, methods_P = [], [] Tmins, Tmaxs = [], [] if self.CASRN in _VDISaturationDict: methods.append(VDI_TABULAR) Ts, props = VDI_tabular_data(self.CASRN, 'K (g)') self.VDI_Tmin = Ts[0] self.VDI_Tmax = Ts[-1] self.tabular_data[VDI_TABULAR] = (Ts, props) Tmins.append(self.VDI_Tmin); Tmaxs.append(self.VDI_Tmax) if has_CoolProp and self.CASRN in coolprop_dict: methods.append(COOLPROP); methods_P.append(COOLPROP) self.CP_f = coolprop_fluids[self.CASRN] Tmins.append(self.CP_f.Tmin); Tmaxs.append(self.CP_f.Tc) if self.CASRN in Perrys2_314.index: methods.append(DIPPR_PERRY_8E) _, C1, C2, C3, C4, self.Perrys2_314_Tmin, self.Perrys2_314_Tmax = _Perrys2_314_values[Perrys2_314.index.get_loc(self.CASRN)].tolist() self.Perrys2_314_coeffs = [C1, C2, C3, C4] Tmins.append(self.Perrys2_314_Tmin); Tmaxs.append(self.Perrys2_314_Tmax) if self.CASRN in VDI_PPDS_10.index: _, A, B, C, D, E = _VDI_PPDS_10_values[VDI_PPDS_10.index.get_loc(self.CASRN)].tolist() self.VDI_PPDS_coeffs = [A, B, C, D, E] self.VDI_PPDS_coeffs.reverse() methods.append(VDI_PPDS) if all((self.MW, self.Tb, self.Pc, self.omega)): methods.append(GHARAGHEIZI_G) # Turns negative at low T; do not set Tmin Tmaxs.append(3000) if all((self.Cvgm, self.mug, self.MW, self.Tc)): methods.append(DIPPR_9B) Tmins.append(0.01); Tmaxs.append(1E4) # No limit here if all((self.Cvgm, self.mug, self.MW, self.Tc, self.omega)): methods.append(CHUNG) Tmins.append(0.01); Tmaxs.append(1E4) # No limit if all((self.Cvgm, self.MW, self.Tc, self.Vc, self.Zc, self.omega)): methods.append(ELI_HANLEY) Tmaxs.append(1E4) # Numeric error at low T if all((self.Cvgm, self.mug, self.MW)): methods.append(EUCKEN_MOD) methods.append(EUCKEN) Tmins.append(0.01); Tmaxs.append(1E4) # No limits if self.MW: methods.append(BAHADORI_G) # Terrible method, so don't set methods if all([self.MW, self.Tc, self.Vc, self.Zc, self.omega]): methods_P.append(ELI_HANLEY_DENSE) if all([self.MW, self.Tc, self.Vc, self.omega, self.dipole]): methods_P.append(CHUNG_DENSE) if all([self.MW, self.Tc, self.Pc, self.Vc, self.Zc]): methods_P.append(STIEL_THODOS_DENSE) self.all_methods = set(methods) self.all_methods_P = set(methods_P) if Tmins and Tmaxs: self.Tmin, self.Tmax = min(Tmins), max(Tmaxs)
def calculate(self, T, method): r'''Method to calculate low-pressure gas thermal conductivity at tempearture `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature of the gas, [K] method : str Name of the method to use Returns ------- kg : float Thermal conductivity of the gas at T and a low pressure, [W/m/K] ''' if method == GHARAGHEIZI_G: kg = Gharagheizi_gas(T, self.MW, self.Tb, self.Pc, self.omega) elif method == DIPPR_9B: Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug kg = DIPPR9B(T, self.MW, Cvgm, mug, self.Tc) elif method == CHUNG: Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug kg = Chung(T, self.MW, self.Tc, self.omega, Cvgm, mug) elif method == ELI_HANLEY: Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm kg = eli_hanley(T, self.MW, self.Tc, self.Vc, self.Zc, self.omega, Cvgm) elif method == EUCKEN_MOD: Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug kg = Eucken_modified(self.MW, Cvgm, mug) elif method == EUCKEN: Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm mug = self.mug(T) if hasattr(self.mug, '__call__') else self.mug kg = Eucken(self.MW, Cvgm, mug) elif method == DIPPR_PERRY_8E: kg = EQ102(T, *self.Perrys2_314_coeffs) elif method == VDI_PPDS: kg = horner(self.VDI_PPDS_coeffs, T) elif method == BAHADORI_G: kg = Bahadori_gas(T, self.MW) elif method == COOLPROP: kg = CoolProp_T_dependent_property(T, self.CASRN, 'L', 'g') elif method in self.tabular_data: kg = self.interpolate(T, method) return kg
def calculate_P(self, T, P, method): r'''Method to calculate pressure-dependent gas thermal conductivity at temperature `T` and pressure `P` with a given method. This method has no exception handling; see `TP_dependent_property` for that. Parameters ---------- T : float Temperature at which to calculate gas thermal conductivity, [K] P : float Pressure at which to calculate gas thermal conductivity, [K] method : str Name of the method to use Returns ------- kg : float Thermal conductivity of the gas at T and P, [W/m/K] ''' if method == ELI_HANLEY_DENSE: Vmg = self.Vmg(T, P) if hasattr(self.Vmg, '__call__') else self.Vmg Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm kg = eli_hanley_dense(T, self.MW, self.Tc, self.Vc, self.Zc, self.omega, Cvgm, Vmg) elif method == CHUNG_DENSE: Vmg = self.Vmg(T, P) if hasattr(self.Vmg, '__call__') else self.Vmg Cvgm = self.Cvgm(T) if hasattr(self.Cvgm, '__call__') else self.Cvgm mug = self.mug(T, P) if hasattr(self.mug, '__call__') else self.mug kg = chung_dense(T, self.MW, self.Tc, self.Vc, self.omega, Cvgm, Vmg, mug, self.dipole) elif method == STIEL_THODOS_DENSE: kg = self.T_dependent_property(T) Vmg = self.Vmg(T, P) if hasattr(self.Vmg, '__call__') else self.Vmg kg = stiel_thodos_dense(T, self.MW, self.Tc, self.Pc, self.Vc, self.Zc, Vmg, kg) elif method == COOLPROP: kg = PropsSI('L', 'T', T, 'P', P, self.CASRN) elif method in self.tabular_data: kg = self.interpolate_P(T, P, method) return kg
def load_all_methods(self): r'''Method to initialize the object by precomputing any values which may be used repeatedly and by retrieving mixture-specific variables. All data are stored as attributes. This method also sets :obj:`Tmin`, :obj:`Tmax`, and :obj:`all_methods` as a set of methods which should work to calculate the property. Called on initialization only. See the source code for the variables at which the coefficients are stored. The coefficients can safely be altered once the class is initialized. This method can be called again to reset the parameters. ''' methods = [] methods.append(SIMPLE) if none_and_length_check((self.Tbs, self.MWs)): methods.append(LINDSAY_BROMLEY) self.all_methods = set(methods) Tmins = [i.Tmin for i in self.ThermalConductivityGases if i.Tmin] Tmaxs = [i.Tmax for i in self.ThermalConductivityGases if i.Tmax] if Tmins: self.Tmin = max(Tmins) if Tmaxs: self.Tmax = max(Tmaxs)
def calculate(self, T, P, zs, ws, method): r'''Method to calculate thermal conductivity of a gas mixture at temperature `T`, pressure `P`, mole fractions `zs` and weight fractions `ws` with a given method. This method has no exception handling; see `mixture_property` for that. Parameters ---------- T : float Temperature at which to calculate the property, [K] P : float Pressure at which to calculate the property, [Pa] zs : list[float] Mole fractions of all species in the mixture, [-] ws : list[float] Weight fractions of all species in the mixture, [-] method : str Name of the method to use Returns ------- kg : float Thermal conductivity of gas mixture, [W/m/K] ''' if method == SIMPLE: ks = [i(T, P) for i in self.ThermalConductivityGases] return mixing_simple(zs, ks) elif method == LINDSAY_BROMLEY: ks = [i(T, P) for i in self.ThermalConductivityGases] mus = [i(T, P) for i in self.ViscosityGases] return Lindsay_Bromley(T=T, ys=zs, ks=ks, mus=mus, Tbs=self.Tbs, MWs=self.MWs) else: raise Exception('Method not valid')
def molecular_weight(atoms): r'''Calculates molecular weight of a molecule given a dictionary of its atoms and their counts, in the format {symbol: count}. .. math:: MW = \sum_i n_i MW_i Parameters ---------- atoms : dict dictionary of counts of individual atoms, indexed by symbol with proper capitalization, [-] Returns ------- MW : float Calculated molecular weight [g/mol] Notes ----- Elemental data is from rdkit, with CAS numbers added. An exception is raised if an incorrect element symbol is given. Elements up to 118 are supported, as are deutreium and tritium. Examples -------- >>> molecular_weight({'H': 12, 'C': 20, 'O': 5}) # DNA 332.30628 References ---------- .. [1] RDKit: Open-source cheminformatics; http://www.rdkit.org ''' MW = 0 for i in atoms: if i in periodic_table: MW += periodic_table[i].MW*atoms[i] elif i == 'D': # Hardcoded MW until an actual isotope db is created MW += 2.014102*atoms[i] elif i == 'T': # Hardcoded MW until an actual isotope db is created MW += 3.0160492*atoms[i] else: raise Exception('Molecule includes unknown atoms') return MW
def mass_fractions(atoms, MW=None): r'''Calculates the mass fractions of each element in a compound, given a dictionary of its atoms and their counts, in the format {symbol: count}. .. math:: w_i = \frac{n_i MW_i}{\sum_i n_i MW_i} Parameters ---------- atoms : dict dictionary of counts of individual atoms, indexed by symbol with proper capitalization, [-] MW : float, optional Molecular weight, [g/mol] Returns ------- mfracs : dict dictionary of mass fractions of individual atoms, indexed by symbol with proper capitalization, [-] Notes ----- Molecular weight is optional, but speeds up the calculation slightly. It is calculated using the function `molecular_weight` if not specified. Elemental data is from rdkit, with CAS numbers added. An exception is raised if an incorrect element symbol is given. Elements up to 118 are supported. Examples -------- >>> mass_fractions({'H': 12, 'C': 20, 'O': 5}) {'H': 0.03639798802478244, 'C': 0.7228692758981262, 'O': 0.24073273607709128} References ---------- .. [1] RDKit: Open-source cheminformatics; http://www.rdkit.org ''' if not MW: MW = molecular_weight(atoms) mfracs = {} for i in atoms: if i in periodic_table: mfracs[i] = periodic_table[i].MW*atoms[i]/MW else: raise Exception('Molecule includes unknown atoms') return mfracs
def atom_fractions(atoms): r'''Calculates the atomic fractions of each element in a compound, given a dictionary of its atoms and their counts, in the format {symbol: count}. .. math:: a_i = \frac{n_i}{\sum_i n_i} Parameters ---------- atoms : dict dictionary of counts of individual atoms, indexed by symbol with proper capitalization, [-] Returns ------- afracs : dict dictionary of atomic fractions of individual atoms, indexed by symbol with proper capitalization, [-] Notes ----- No actual data on the elements is used, so incorrect or custom compounds would not raise an error. Examples -------- >>> atom_fractions({'H': 12, 'C': 20, 'O': 5}) {'H': 0.32432432432432434, 'C': 0.5405405405405406, 'O': 0.13513513513513514} References ---------- .. [1] RDKit: Open-source cheminformatics; http://www.rdkit.org ''' count = sum(atoms.values()) afracs = {} for i in atoms: afracs[i] = atoms[i]/count return afracs
def similarity_variable(atoms, MW=None): r'''Calculates the similarity variable of an compound, as defined in [1]_. Currently only applied for certain heat capacity estimation routines. .. math:: \alpha = \frac{N}{MW} = \frac{\sum_i n_i}{\sum_i n_i MW_i} Parameters ---------- atoms : dict dictionary of counts of individual atoms, indexed by symbol with proper capitalization, [-] MW : float, optional Molecular weight, [g/mol] Returns ------- similarity_variable : float Similarity variable as defined in [1]_, [mol/g] Notes ----- Molecular weight is optional, but speeds up the calculation slightly. It is calculated using the function `molecular_weight` if not specified. Examples -------- >>> similarity_variable({'H': 32, 'C': 15}) 0.2212654140784498 References ---------- .. [1] Laštovka, Václav, Nasser Sallamie, and John M. Shaw. "A Similarity Variable for Estimating the Heat Capacity of Solid Organic Compounds: Part I. Fundamentals." Fluid Phase Equilibria 268, no. 1-2 (June 25, 2008): 51-60. doi:10.1016/j.fluid.2008.03.019. ''' if not MW: MW = molecular_weight(atoms) return sum(atoms.values())/MW
def atoms_to_Hill(atoms): r'''Determine the Hill formula of a compound, given a dictionary of its atoms and their counts, in the format {symbol: count}. Parameters ---------- atoms : dict dictionary of counts of individual atoms, indexed by symbol with proper capitalization, [-] Returns ------- Hill_formula : str Hill formula, [-] Notes ----- The Hill system is as follows: If the chemical has 'C' in it, this is listed first, and then if it has 'H' in it as well as 'C', then that goes next. All elements are sorted alphabetically afterwards, including 'H' if 'C' is not present. All elements are followed by their count, unless it is 1. Examples -------- >>> atoms_to_Hill({'H': 5, 'C': 2, 'Br': 1}) 'C2H5Br' References ---------- .. [1] Hill, Edwin A."“ON A SYSTEM OF INDEXING CHEMICAL LITERATURE; ADOPTED BY THE CLASSIFICATION DIVISION OF THE U. S. PATENT OFFICE.1." Journal of the American Chemical Society 22, no. 8 (August 1, 1900): 478-94. doi:10.1021/ja02046a005. ''' def str_ele_count(ele): if atoms[ele] == 1: count = '' else: count = str(atoms[ele]) return count atoms = atoms.copy() s = '' if 'C' in atoms.keys(): s += 'C' + str_ele_count('C') del atoms['C'] if 'H' in atoms.keys(): s += 'H' + str_ele_count('H') del atoms['H'] for ele in sorted(atoms.keys()): s += ele + str_ele_count(ele) else: for ele in sorted(atoms.keys()): s += ele + str_ele_count(ele) return s
def simple_formula_parser(formula): r'''Basic formula parser, primarily for obtaining element counts from formulas as formated in PubChem. Handles formulas with integer counts, but no brackets, no hydrates, no charges, no isotopes, and no group multipliers. Strips charges from the end of a formula first. Accepts repeated chemical units. Performs no sanity checking that elements are actually elements. As it uses regular expressions for matching, errors are mostly just ignored. Parameters ---------- formula : str Formula string, very simply formats only. Returns ------- atoms : dict dictionary of counts of individual atoms, indexed by symbol with proper capitalization, [-] Notes ----- Inspiration taken from the thermopyl project, at https://github.com/choderalab/thermopyl. Examples -------- >>> simple_formula_parser('CO2') {'C': 1, 'O': 2} ''' formula = formula.split('+')[0].split('-')[0] groups = _formula_p1.split(formula)[1::2] cnt = Counter() for group in groups: ele, count = _formula_p2.split(group)[1:] cnt[ele] += int(count) if count.isdigit() else 1 return dict(cnt)
def nested_formula_parser(formula, check=True): r'''Improved formula parser which handles braces and their multipliers, as well as rational element counts. Strips charges from the end of a formula first. Accepts repeated chemical units. Performs no sanity checking that elements are actually elements. As it uses regular expressions for matching, errors are mostly just ignored. Parameters ---------- formula : str Formula string, very simply formats only. check : bool If `check` is True, a simple check will be performed to determine if a formula is not a formula and an exception will be raised if it is not, [-] Returns ------- atoms : dict dictionary of counts of individual atoms, indexed by symbol with proper capitalization, [-] Notes ----- Inspired by the approach taken by CrazyMerlyn on a reddit DailyProgrammer challenge, at https://www.reddit.com/r/dailyprogrammer/comments/6eerfk/20170531_challenge_317_intermediate_counting/ Examples -------- >>> pprint(nested_formula_parser('Pd(NH3)4.0001+2')) {'H': 12.0003, 'N': 4.0001, 'Pd': 1} ''' formula = formula.replace('[', '').replace(']', '') charge_splits = bracketed_charge_re.split(formula) if len(charge_splits) > 1: formula = charge_splits[0] else: formula = formula.split('+')[0].split('-')[0] stack = [[]] last = stack[0] tokens = formula_token_matcher_rational.findall(formula) # The set of letters in the tokens should match the set of letters if check: token_letters = set([j for i in tokens for j in i if j in letter_set]) formula_letters = set(i for i in formula if i in letter_set) if formula_letters != token_letters: raise Exception('Input may not be a formula; extra letters were detected') for token in tokens: if token == "(": stack.append([]) last = stack[-1] elif token == ")": temp_dict = {} for d in last: for ele, count in d.items(): if ele in temp_dict: temp_dict[ele] = temp_dict[ele] + count else: temp_dict[ele] = count stack.pop() last = stack[-1] last.append(temp_dict) elif token.isalpha(): last.append({token: 1}) else: v = float(token) v_int = int(v) if v_int == v: v = v_int last[-1] = {ele: count*v for ele, count in last[-1].items()} ans = {} for d in last: for ele, count in d.items(): if ele in ans: ans[ele] = ans[ele] + count else: ans[ele] = count return ans
def charge_from_formula(formula): r'''Basic formula parser to determine the charge from a formula - given that the charge is already specified as one element of the formula. Performs no sanity checking that elements are actually elements. Parameters ---------- formula : str Formula string, very simply formats only, ending in one of '+x', '-x', n*'+', or n*'-' or any of them surrounded by brackets but always at the end of a formula. Returns ------- charge : int Charge of the molecule, [faraday] Notes ----- Examples -------- >>> charge_from_formula('Br3-') -1 >>> charge_from_formula('Br3(-)') -1 ''' negative = '-' in formula positive = '+' in formula if positive and negative: raise ValueError('Both negative and positive signs were found in the formula; only one sign is allowed') elif not (positive or negative): return 0 multiplier, sign = (-1, '-') if negative else (1, '+') hit = False if '(' in formula: hit = bracketed_charge_re.findall(formula) if hit: formula = hit[-1].replace('(', '').replace(')', '') count = formula.count(sign) if count == 1: splits = formula.split(sign) if splits[1] == '' or splits[1] == ')': return multiplier else: return multiplier*int(splits[1]) else: return multiplier*count
def serialize_formula(formula): r'''Basic formula serializer to construct a consistently-formatted formula. This is necessary for handling user-supplied formulas, which are not always well formatted. Performs no sanity checking that elements are actually elements. Parameters ---------- formula : str Formula string as parseable by the method nested_formula_parser, [-] Returns ------- formula : str A consistently formatted formula to describe a molecular formula, [-] Notes ----- Examples -------- >>> serialize_formula('Pd(NH3)4+3') 'H12N4Pd+3' ''' charge = charge_from_formula(formula) element_dict = nested_formula_parser(formula) base = atoms_to_Hill(element_dict) if charge == 0: pass elif charge > 0: if charge == 1: base += '+' else: base += '+' + str(charge) elif charge < 0: if charge == -1: base += '-' else: base += str(charge) return base
async def connect(self): """Establish a connection to the chat server. Returns when an error has occurred, or :func:`disconnect` has been called. """ proxy = os.environ.get('HTTP_PROXY') self._session = http_utils.Session(self._cookies, proxy=proxy) try: self._channel = channel.Channel( self._session, self._max_retries, self._retry_backoff_base ) # Forward the Channel events to the Client events. self._channel.on_connect.add_observer(self.on_connect.fire) self._channel.on_reconnect.add_observer(self.on_reconnect.fire) self._channel.on_disconnect.add_observer(self.on_disconnect.fire) self._channel.on_receive_array.add_observer(self._on_receive_array) # Wrap the coroutine in a Future so it can be cancelled. self._listen_future = asyncio.ensure_future(self._channel.listen()) # Listen for StateUpdate messages from the Channel until it # disconnects. try: await self._listen_future except asyncio.CancelledError: # If this task is cancelled, we need to cancel our child task # as well. We don't need an additional yield because listen # cancels immediately. self._listen_future.cancel() logger.info( 'Client.connect returning because Channel.listen returned' ) finally: await self._session.close()
def get_request_header(self): """Return ``request_header`` for use when constructing requests. Returns: Populated request header. """ # resource is allowed to be null if it's not available yet (the Chrome # client does this for the first getentitybyid call) if self._client_id is not None: self._request_header.client_identifier.resource = self._client_id return self._request_header
async def set_active(self): """Set this client as active. While a client is active, no other clients will raise notifications. Call this method whenever there is an indication the user is interacting with this client. This method may be called very frequently, and it will only make a request when necessary. """ is_active = (self._active_client_state == hangouts_pb2.ACTIVE_CLIENT_STATE_IS_ACTIVE) timed_out = (time.time() - self._last_active_secs > SETACTIVECLIENT_LIMIT_SECS) if not is_active or timed_out: # Update these immediately so if the function is called again # before the API request finishes, we don't start extra requests. self._active_client_state = ( hangouts_pb2.ACTIVE_CLIENT_STATE_IS_ACTIVE ) self._last_active_secs = time.time() # The first time this is called, we need to retrieve the user's # email address. if self._email is None: try: get_self_info_request = hangouts_pb2.GetSelfInfoRequest( request_header=self.get_request_header(), ) get_self_info_response = await self.get_self_info( get_self_info_request ) except exceptions.NetworkError as e: logger.warning('Failed to find email address: {}' .format(e)) return self._email = ( get_self_info_response.self_entity.properties.email[0] ) # If the client_id hasn't been received yet, we can't set the # active client. if self._client_id is None: logger.info( 'Cannot set active client until client_id is received' ) return try: set_active_request = hangouts_pb2.SetActiveClientRequest( request_header=self.get_request_header(), is_active=True, full_jid="{}/{}".format(self._email, self._client_id), timeout_secs=ACTIVE_TIMEOUT_SECS, ) await self.set_active_client(set_active_request) except exceptions.NetworkError as e: logger.warning('Failed to set active client: {}'.format(e)) else: logger.info('Set active client for {} seconds' .format(ACTIVE_TIMEOUT_SECS))
async def upload_image(self, image_file, filename=None, *, return_uploaded_image=False): """Upload an image that can be later attached to a chat message. Args: image_file: A file-like object containing an image. filename (str): (optional) Custom name for the uploaded file. return_uploaded_image (bool): (optional) If True, return :class:`.UploadedImage` instead of image ID. Defaults to False. Raises: hangups.NetworkError: If the upload request failed. Returns: :class:`.UploadedImage` instance, or ID of the uploaded image. """ image_filename = filename or os.path.basename(image_file.name) image_data = image_file.read() # request an upload URL res = await self._base_request( IMAGE_UPLOAD_URL, 'application/x-www-form-urlencoded;charset=UTF-8', 'json', json.dumps({ "protocolVersion": "0.8", "createSessionRequest": { "fields": [{ "external": { "name": "file", "filename": image_filename, "put": {}, "size": len(image_data) } }] } }) ) try: upload_url = self._get_upload_session_status(res)[ 'externalFieldTransfers' ][0]['putInfo']['url'] except KeyError: raise exceptions.NetworkError( 'image upload failed: can not acquire an upload url' ) # upload the image data using the upload_url to get the upload info res = await self._base_request( upload_url, 'application/octet-stream', 'json', image_data ) try: raw_info = ( self._get_upload_session_status(res)['additionalInfo'] ['uploader_service.GoogleRupioAdditionalInfo'] ['completionInfo']['customerSpecificInfo'] ) image_id = raw_info['photoid'] url = raw_info['url'] except KeyError: raise exceptions.NetworkError( 'image upload failed: can not fetch upload info' ) result = UploadedImage(image_id=image_id, url=url) return result if return_uploaded_image else result.image_id
def _get_upload_session_status(res): """Parse the image upload response to obtain status. Args: res: http_utils.FetchResponse instance, the upload response Returns: dict, sessionStatus of the response Raises: hangups.NetworkError: If the upload request failed. """ response = json.loads(res.body.decode()) if 'sessionStatus' not in response: try: info = ( response['errorMessage']['additionalInfo'] ['uploader_service.GoogleRupioAdditionalInfo'] ['completionInfo']['customerSpecificInfo'] ) reason = '{} : {}'.format(info['status'], info['message']) except KeyError: reason = 'unknown reason' raise exceptions.NetworkError('image upload failed: {}'.format( reason )) return response['sessionStatus']
async def _on_receive_array(self, array): """Parse channel array and call the appropriate events.""" if array[0] == 'noop': pass # This is just a keep-alive, ignore it. else: wrapper = json.loads(array[0]['p']) # Wrapper appears to be a Protocol Buffer message, but encoded via # field numbers as dictionary keys. Since we don't have a parser # for that, parse it ad-hoc here. if '3' in wrapper: # This is a new client_id. self._client_id = wrapper['3']['2'] logger.info('Received new client_id: %r', self._client_id) # Once client_id is received, the channel is ready to have # services added. await self._add_channel_services() if '2' in wrapper: pblite_message = json.loads(wrapper['2']['2']) if pblite_message[0] == 'cbu': # This is a (Client)BatchUpdate containing StateUpdate # messages. batch_update = hangouts_pb2.BatchUpdate() pblite.decode(batch_update, pblite_message, ignore_first_item=True) for state_update in batch_update.state_update: logger.debug('Received StateUpdate:\n%s', state_update) header = state_update.state_update_header self._active_client_state = header.active_client_state await self.on_state_update.fire(state_update) else: logger.info('Ignoring message: %r', pblite_message[0])
async def _add_channel_services(self): """Add services to the channel. The services we add to the channel determine what kind of data we will receive on it. The "babel" service includes what we need for Hangouts. If this fails for some reason, hangups will never receive any events. The "babel_presence_last_seen" service is also required to receive presence notifications. This needs to be re-called whenever we open a new channel (when there's a new SID and client_id. """ logger.info('Adding channel services...') # Based on what Hangouts for Chrome does over 2 requests, this is # trimmed down to 1 request that includes the bare minimum to make # things work. services = ["babel", "babel_presence_last_seen"] map_list = [ dict(p=json.dumps({"3": {"1": {"1": service}}})) for service in services ] await self._channel.send_maps(map_list) logger.info('Channel services added')
async def _pb_request(self, endpoint, request_pb, response_pb): """Send a Protocol Buffer formatted chat API request. Args: endpoint (str): The chat API endpoint to use. request_pb: The request body as a Protocol Buffer message. response_pb: The response body as a Protocol Buffer message. Raises: NetworkError: If the request fails. """ logger.debug('Sending Protocol Buffer request %s:\n%s', endpoint, request_pb) res = await self._base_request( 'https://clients6.google.com/chat/v1/{}'.format(endpoint), 'application/x-protobuf', # Request body is Protocol Buffer. 'proto', # Response body is Protocol Buffer. request_pb.SerializeToString() ) try: response_pb.ParseFromString(base64.b64decode(res.body)) except binascii.Error as e: raise exceptions.NetworkError( 'Failed to decode base64 response: {}'.format(e) ) except google.protobuf.message.DecodeError as e: raise exceptions.NetworkError( 'Failed to decode Protocol Buffer response: {}'.format(e) ) logger.debug('Received Protocol Buffer response:\n%s', response_pb) status = response_pb.response_header.status if status != hangouts_pb2.RESPONSE_STATUS_OK: description = response_pb.response_header.error_description raise exceptions.NetworkError( 'Request failed with status {}: \'{}\'' .format(status, description) )
async def _base_request(self, url, content_type, response_type, data): """Send a generic authenticated POST request. Args: url (str): URL of request. content_type (str): Request content type. response_type (str): The desired response format. Valid options are: 'json' (JSON), 'protojson' (pblite), and 'proto' (binary Protocol Buffer). 'proto' requires manually setting an extra header 'X-Goog-Encode-Response-If-Executable: base64'. data (str): Request body data. Returns: FetchResponse: Response containing HTTP code, cookies, and body. Raises: NetworkError: If the request fails. """ headers = { 'content-type': content_type, # This header is required for Protocol Buffer responses. It causes # them to be base64 encoded: 'X-Goog-Encode-Response-If-Executable': 'base64', } params = { # "alternative representation type" (desired response format). 'alt': response_type, # API key (required to avoid 403 Forbidden "Daily Limit for # Unauthenticated Use Exceeded. Continued use requires signup"). 'key': API_KEY, } res = await self._session.fetch( 'post', url, headers=headers, params=params, data=data, ) return res
async def add_user(self, add_user_request): """Invite users to join an existing group conversation.""" response = hangouts_pb2.AddUserResponse() await self._pb_request('conversations/adduser', add_user_request, response) return response
async def create_conversation(self, create_conversation_request): """Create a new conversation.""" response = hangouts_pb2.CreateConversationResponse() await self._pb_request('conversations/createconversation', create_conversation_request, response) return response
async def delete_conversation(self, delete_conversation_request): """Leave a one-to-one conversation. One-to-one conversations are "sticky"; they can't actually be deleted. This API clears the event history of the specified conversation up to ``delete_upper_bound_timestamp``, hiding it if no events remain. """ response = hangouts_pb2.DeleteConversationResponse() await self._pb_request('conversations/deleteconversation', delete_conversation_request, response) return response
async def easter_egg(self, easter_egg_request): """Send an easter egg event to a conversation.""" response = hangouts_pb2.EasterEggResponse() await self._pb_request('conversations/easteregg', easter_egg_request, response) return response
async def get_conversation(self, get_conversation_request): """Return conversation info and recent events.""" response = hangouts_pb2.GetConversationResponse() await self._pb_request('conversations/getconversation', get_conversation_request, response) return response
async def get_entity_by_id(self, get_entity_by_id_request): """Return one or more user entities. Searching by phone number only finds entities when their phone number is in your contacts (and not always even then), and can't be used to find Google Voice contacts. """ response = hangouts_pb2.GetEntityByIdResponse() await self._pb_request('contacts/getentitybyid', get_entity_by_id_request, response) return response
async def get_group_conversation_url(self, get_group_conversation_url_request): """Get URL to allow others to join a group conversation.""" response = hangouts_pb2.GetGroupConversationUrlResponse() await self._pb_request('conversations/getgroupconversationurl', get_group_conversation_url_request, response) return response
async def get_self_info(self, get_self_info_request): """Return info about the current user.""" response = hangouts_pb2.GetSelfInfoResponse() await self._pb_request('contacts/getselfinfo', get_self_info_request, response) return response
async def get_suggested_entities(self, get_suggested_entities_request): """Return suggested contacts.""" response = hangouts_pb2.GetSuggestedEntitiesResponse() await self._pb_request('contacts/getsuggestedentities', get_suggested_entities_request, response) return response
async def query_presence(self, query_presence_request): """Return presence status for a list of users.""" response = hangouts_pb2.QueryPresenceResponse() await self._pb_request('presence/querypresence', query_presence_request, response) return response
async def remove_user(self, remove_user_request): """Remove a participant from a group conversation.""" response = hangouts_pb2.RemoveUserResponse() await self._pb_request('conversations/removeuser', remove_user_request, response) return response
async def rename_conversation(self, rename_conversation_request): """Rename a conversation. Both group and one-to-one conversations may be renamed, but the official Hangouts clients have mixed support for one-to-one conversations with custom names. """ response = hangouts_pb2.RenameConversationResponse() await self._pb_request('conversations/renameconversation', rename_conversation_request, response) return response
async def search_entities(self, search_entities_request): """Return user entities based on a query.""" response = hangouts_pb2.SearchEntitiesResponse() await self._pb_request('contacts/searchentities', search_entities_request, response) return response
async def send_chat_message(self, send_chat_message_request): """Send a chat message to a conversation.""" response = hangouts_pb2.SendChatMessageResponse() await self._pb_request('conversations/sendchatmessage', send_chat_message_request, response) return response
async def modify_otr_status(self, modify_otr_status_request): """Enable or disable message history in a conversation.""" response = hangouts_pb2.ModifyOTRStatusResponse() await self._pb_request('conversations/modifyotrstatus', modify_otr_status_request, response) return response
async def send_offnetwork_invitation( self, send_offnetwork_invitation_request ): """Send an email to invite a non-Google contact to Hangouts.""" response = hangouts_pb2.SendOffnetworkInvitationResponse() await self._pb_request('devices/sendoffnetworkinvitation', send_offnetwork_invitation_request, response) return response
async def set_active_client(self, set_active_client_request): """Set the active client.""" response = hangouts_pb2.SetActiveClientResponse() await self._pb_request('clients/setactiveclient', set_active_client_request, response) return response
async def set_conversation_notification_level( self, set_conversation_notification_level_request ): """Set the notification level of a conversation.""" response = hangouts_pb2.SetConversationNotificationLevelResponse() await self._pb_request( 'conversations/setconversationnotificationlevel', set_conversation_notification_level_request, response ) return response
async def set_focus(self, set_focus_request): """Set focus to a conversation.""" response = hangouts_pb2.SetFocusResponse() await self._pb_request('conversations/setfocus', set_focus_request, response) return response
async def set_group_link_sharing_enabled( self, set_group_link_sharing_enabled_request ): """Set whether group link sharing is enabled for a conversation.""" response = hangouts_pb2.SetGroupLinkSharingEnabledResponse() await self._pb_request('conversations/setgrouplinksharingenabled', set_group_link_sharing_enabled_request, response) return response
async def set_presence(self, set_presence_request): """Set the presence status.""" response = hangouts_pb2.SetPresenceResponse() await self._pb_request('presence/setpresence', set_presence_request, response) return response
async def set_typing(self, set_typing_request): """Set the typing status of a conversation.""" response = hangouts_pb2.SetTypingResponse() await self._pb_request('conversations/settyping', set_typing_request, response) return response
async def sync_all_new_events(self, sync_all_new_events_request): """List all events occurring at or after a timestamp.""" response = hangouts_pb2.SyncAllNewEventsResponse() await self._pb_request('conversations/syncallnewevents', sync_all_new_events_request, response) return response
async def sync_recent_conversations( self, sync_recent_conversations_request ): """Return info on recent conversations and their events.""" response = hangouts_pb2.SyncRecentConversationsResponse() await self._pb_request('conversations/syncrecentconversations', sync_recent_conversations_request, response) return response
async def update_watermark(self, update_watermark_request): """Update the watermark (read timestamp) of a conversation.""" response = hangouts_pb2.UpdateWatermarkResponse() await self._pb_request('conversations/updatewatermark', update_watermark_request, response) return response
def from_timestamp(microsecond_timestamp): """Convert a microsecond timestamp to a UTC datetime instance.""" # Create datetime without losing precision from floating point (yes, this # is actually needed): return datetime.datetime.fromtimestamp( microsecond_timestamp // 1000000, datetime.timezone.utc ).replace(microsecond=(microsecond_timestamp % 1000000))
def from_participantid(participant_id): """Convert hangouts_pb2.ParticipantId to UserID.""" return user.UserID( chat_id=participant_id.chat_id, gaia_id=participant_id.gaia_id )
def to_participantid(user_id): """Convert UserID to hangouts_pb2.ParticipantId.""" return hangouts_pb2.ParticipantId( chat_id=user_id.chat_id, gaia_id=user_id.gaia_id )
def parse_typing_status_message(p): """Return TypingStatusMessage from hangouts_pb2.SetTypingNotification. The same status may be sent multiple times consecutively, and when a message is sent the typing status will not change to stopped. """ return TypingStatusMessage( conv_id=p.conversation_id.id, user_id=from_participantid(p.sender_id), timestamp=from_timestamp(p.timestamp), status=p.type, )