idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
241,100
def Peclet_heat ( V , L , rho = None , Cp = None , k = None , alpha = None ) : r if rho and Cp and k : alpha = k / ( rho * Cp ) elif not alpha : raise Exception ( 'Either heat capacity and thermal conductivity and\ density, or thermal diffusivity is needed' ) return V * L / alpha
r Calculates heat transfer Peclet number or Pe for a specified velocity V characteristic length L and specified properties for the given fluid .
241,101
def Fourier_heat ( t , L , rho = None , Cp = None , k = None , alpha = None ) : r if rho and Cp and k : alpha = k / ( rho * Cp ) elif not alpha : raise Exception ( 'Either heat capacity and thermal conductivity and \density, or thermal diffusivity is needed' ) return t * alpha / L ** 2
r Calculates heat transfer Fourier number or Fo for a specified time t characteristic length L and specified properties for the given fluid .
241,102
def Graetz_heat ( V , D , x , rho = None , Cp = None , k = None , alpha = None ) : r if rho and Cp and k : alpha = k / ( rho * Cp ) elif not alpha : raise Exception ( 'Either heat capacity and thermal conductivity and\ density, or thermal diffusivity is needed' ) return V * D ** 2 / ( x * alpha )
r Calculates Graetz number or Gz for a specified velocity V diameter D axial distance x and specified properties for the given fluid .
241,103
def Schmidt ( D , mu = None , nu = None , rho = None ) : r if rho and mu : return mu / ( rho * D ) elif nu : return nu / D else : raise Exception ( 'Insufficient information provided for Schmidt number calculation' )
r Calculates Schmidt number or Sc for a fluid with the given parameters .
241,104
def Lewis ( D = None , alpha = None , Cp = None , k = None , rho = None ) : r if k and Cp and rho : alpha = k / ( rho * Cp ) elif alpha : pass else : raise Exception ( 'Insufficient information provided for Le calculation' ) return alpha / D
r Calculates Lewis number or Le for a fluid with the given parameters .
241,105
def Confinement ( D , rhol , rhog , sigma , g = g ) : r return ( sigma / ( g * ( rhol - rhog ) ) ) ** 0.5 / D
r Calculates Confinement number or Co for a fluid in a channel of diameter D with liquid and gas densities rhol and rhog and surface tension sigma under the influence of gravitational force g .
241,106
def Morton ( rhol , rhog , mul , sigma , g = g ) : r mul2 = mul * mul return g * mul2 * mul2 * ( rhol - rhog ) / ( rhol * rhol * sigma * sigma * sigma )
r Calculates Morton number or Mo for a liquid and vapor with the specified properties under the influence of gravitational force g .
241,107
def Prandtl ( Cp = None , k = None , mu = None , nu = None , rho = None , alpha = None ) : r if k and Cp and mu : return Cp * mu / k elif nu and rho and Cp and k : return nu * rho * Cp / k elif nu and alpha : return nu / alpha else : raise Exception ( 'Insufficient information provided for Pr calculation' )
r Calculates Prandtl number or Pr for a fluid with the given parameters .
241,108
def Grashof ( L , beta , T1 , T2 = 0 , rho = None , mu = None , nu = None , g = g ) : r if rho and mu : nu = mu / rho elif not nu : raise Exception ( 'Either density and viscosity, or dynamic viscosity, \ is needed' ) return g * beta * abs ( T2 - T1 ) * L ** 3 / nu ** 2
r Calculates Grashof number or Gr for a fluid with the given properties temperature difference and characteristic length .
241,109
def Froude ( V , L , g = g , squared = False ) : r Fr = V / ( L * g ) ** 0.5 if squared : Fr *= Fr return Fr
r Calculates Froude number Fr for velocity V and geometric length L . If desired gravity can be specified as well . Normally the function returns the result of the equation below ; Froude number is also often said to be defined as the square of the equation below .
241,110
def Stokes_number ( V , Dp , D , rhop , mu ) : r return rhop * V * ( Dp * Dp ) / ( 18.0 * mu * D )
r Calculates Stokes Number for a given characteristic velocity V particle diameter Dp characteristic diameter D particle density rhop and fluid viscosity mu .
241,111
def Suratman ( L , rho , mu , sigma ) : r return rho * sigma * L / ( mu * mu )
r Calculates Suratman number Su for a fluid with the given characteristic length density viscosity and surface tension .
241,112
def nu_mu_converter ( rho , mu = None , nu = None ) : r if ( nu and mu ) or not rho or ( not nu and not mu ) : raise Exception ( 'Inputs must be rho and one of mu and nu.' ) if mu : return mu / rho elif nu : return nu * rho
r Calculates either kinematic or dynamic viscosity depending on inputs . Used when one type of viscosity is known as well as density to obtain the other type . Raises an error if both types of viscosity or neither type of viscosity is provided .
241,113
def Engauge_2d_parser ( lines , flat = False ) : z_values = [ ] x_lists = [ ] y_lists = [ ] working_xs = [ ] working_ys = [ ] new_curve = True for line in lines : if line . strip ( ) == '' : new_curve = True elif new_curve : z = float ( line . split ( ',' ) [ 1 ] ) z_values . append ( z ) if working_xs and working_ys :...
Not exposed function to read a 2D file generated by engauge - digitizer ; for curve fitting .
241,114
def isothermal_work_compression ( P1 , P2 , T , Z = 1 ) : r return Z * R * T * log ( P2 / P1 )
r Calculates the work of compression or expansion of a gas going through an isothermal process .
241,115
def isentropic_T_rise_compression ( T1 , P1 , P2 , k , eta = 1 ) : r dT = T1 * ( ( P2 / P1 ) ** ( ( k - 1.0 ) / k ) - 1.0 ) / eta return T1 + dT
r Calculates the increase in temperature of a fluid which is compressed or expanded under isentropic adiabatic conditions assuming constant Cp and Cv . The polytropic model is the same equation ; just provide n instead of k and use a polytropic efficienty for eta instead of a isentropic efficiency .
241,116
def isentropic_efficiency ( P1 , P2 , k , eta_s = None , eta_p = None ) : r if eta_s is None and eta_p : return ( ( P2 / P1 ) ** ( ( k - 1.0 ) / k ) - 1.0 ) / ( ( P2 / P1 ) ** ( ( k - 1.0 ) / ( k * eta_p ) ) - 1.0 ) elif eta_p is None and eta_s : return ( k - 1.0 ) * log ( P2 / P1 ) / ( k * log ( ( eta_s + ( P2 / P1 ) ...
r Calculates either isentropic or polytropic efficiency from the other type of efficiency .
241,117
def P_isothermal_critical_flow ( P , fd , D , L ) : r lambert_term = float ( lambertw ( - exp ( ( - D - L * fd ) / D ) , - 1 ) . real ) return P * exp ( ( D * ( lambert_term + 1.0 ) + L * fd ) / ( 2.0 * D ) )
r Calculates critical flow pressure Pcf for a fluid flowing isothermally and suffering pressure drop caused by a pipe s friction factor .
241,118
def P_upstream_isothermal_critical_flow ( P , fd , D , L ) : lambertw_term = float ( lambertw ( - exp ( - ( fd * L + D ) / D ) , - 1 ) . real ) return exp ( - 0.5 * ( D * lambertw_term + fd * L + D ) / D ) * P
Not part of the public API . Reverses P_isothermal_critical_flow .
241,119
def is_critical_flow ( P1 , P2 , k ) : r Pcf = P_critical_flow ( P1 , k ) return Pcf > P2
r Determines if a flow of a fluid driven by pressure gradient P1 - P2 is critical for a fluid with the given isentropic coefficient . This function calculates critical flow pressure and checks if this is larger than P2 . If so the flow is critical and choked .
241,120
def one_phase_dP ( m , rho , mu , D , roughness = 0 , L = 1 , Method = None ) : r D2 = D * D V = m / ( 0.25 * pi * D2 * rho ) Re = Reynolds ( V = V , rho = rho , mu = mu , D = D ) fd = friction_factor ( Re = Re , eD = roughness / D , Method = Method ) dP = fd * L / D * ( 0.5 * rho * V * V ) return dP
r Calculates single - phase pressure drop . This is a wrapper around other methods .
241,121
def discharge_coefficient_to_K ( D , Do , C ) : r beta = Do / D beta2 = beta * beta beta4 = beta2 * beta2 return ( ( 1.0 - beta4 * ( 1.0 - C * C ) ) ** 0.5 / ( C * beta2 ) - 1.0 ) ** 2
r Converts a discharge coefficient to a standard loss coefficient for use in computation of the actual pressure drop of an orifice or other device .
241,122
def dn ( self , fraction , n = None ) : r if fraction == 1.0 : fraction = 1.0 - epsilon if fraction < 0 : raise ValueError ( 'Fraction must be more than 0' ) elif fraction == 0 : if self . truncated : return self . d_min return 0.0 elif fraction > 1 : raise ValueError ( 'Fraction less than 1' ) return brenth ( lambda d...
r Computes the diameter at which a specified fraction of the distribution falls under . Utilizes a bounded solver to search for the desired diameter .
241,123
def fit ( self , x0 = None , distribution = 'lognormal' , n = None , ** kwargs ) : dist = { 'lognormal' : PSDLognormal , 'GGS' : PSDGatesGaudinSchuhman , 'RR' : PSDRosinRammler } [ distribution ] if distribution == 'lognormal' : if x0 is None : d_characteristic = sum ( [ fi * di for fi , di in zip ( self . fractions , ...
Incomplete method to fit experimental values to a curve . It is very hard to get good initial guesses which are really required for this . Differential evolution is promissing . This API is likely to change in the future .
241,124
def Dis ( self ) : return [ self . di_power ( i , power = 1 ) for i in range ( self . N ) ]
Representative diameters of each bin .
241,125
def SA_tank ( D , L , sideA = None , sideB = None , sideA_a = 0 , sideB_a = 0 , sideA_f = None , sideA_k = None , sideB_f = None , sideB_k = None , full_output = False ) : r if sideA == 'conical' : sideA_SA = SA_conical_head ( D = D , a = sideA_a ) elif sideA == 'ellipsoidal' : sideA_SA = SA_ellipsoidal_head ( D = D , ...
r Calculates the surface are of a cylindrical tank with optional heads . In the degenerate case of being provided with only D and L provides the surface area of a cylinder .
241,126
def pitch_angle_solver ( angle = None , pitch = None , pitch_parallel = None , pitch_normal = None ) : r if angle is not None and pitch is not None : pitch_normal = pitch * sin ( radians ( angle ) ) pitch_parallel = pitch * cos ( radians ( angle ) ) elif angle is not None and pitch_normal is not None : pitch = pitch_no...
r Utility to take any two of angle pitch pitch_parallel and pitch_normal and calculate the other two . This is useful for applications with tube banks as in shell and tube heat exchangers or air coolers and allows for a wider range of user input .
241,127
def A_hollow_cylinder ( Di , Do , L ) : r side_o = pi * Do * L side_i = pi * Di * L cap_circle = pi * Do ** 2 / 4 * 2 cap_removed = pi * Di ** 2 / 4 * 2 return side_o + side_i + cap_circle - cap_removed
r Returns the surface area of a hollow cylinder .
241,128
def A_multiple_hole_cylinder ( Do , L , holes ) : r side_o = pi * Do * L cap_circle = pi * Do ** 2 / 4 * 2 A = cap_circle + side_o for Di , n in holes : side_i = pi * Di * L cap_removed = pi * Di ** 2 / 4 * 2 A = A + side_i * n - cap_removed * n return A
r Returns the surface area of a cylinder with multiple holes . Calculation will naively return a negative value or other impossible result if the number of cylinders added is physically impossible . Holes may be of different shapes but must be perpendicular to the axis of the cylinder .
241,129
def V_from_h ( self , h , method = 'full' ) : r if method == 'full' : return V_from_h ( h , self . D , self . L , self . horizontal , self . sideA , self . sideB , self . sideA_a , self . sideB_a , self . sideA_f , self . sideA_k , self . sideB_f , self . sideB_k ) elif method == 'chebyshev' : if not self . chebyshev :...
r Method to calculate the volume of liquid in a fully defined tank given a specified height h . h must be under the maximum height . If the method is chebyshev and the coefficients have not yet been calculated they are created by calling set_chebyshev_approximators .
241,130
def h_from_V ( self , V , method = 'spline' ) : r if method == 'spline' : if not self . table : self . set_table ( ) return float ( self . interp_h_from_V ( V ) ) elif method == 'chebyshev' : if not self . chebyshev : self . set_chebyshev_approximators ( ) return self . h_from_V_cheb ( V ) elif method == 'brenth' : to_...
r Method to calculate the height of liquid in a fully defined tank given a specified volume of liquid in it V . V must be under the maximum volume . If the method is spline and the interpolation table is not yet defined creates it by calling the method set_table . If the method is chebyshev and the coefficients have no...
241,131
def set_table ( self , n = 100 , dx = None ) : r if dx : self . heights = np . linspace ( 0 , self . h_max , int ( self . h_max / dx ) + 1 ) else : self . heights = np . linspace ( 0 , self . h_max , n ) self . volumes = [ self . V_from_h ( h ) for h in self . heights ] from scipy . interpolate import UnivariateSpline ...
r Method to set an interpolation table of liquids levels versus volumes in the tank for a fully defined tank . Normally run by the h_from_V method this may be run prior to its use with a custom specification . Either the number of points on the table or the vertical distance between steps may be specified .
241,132
def _V_solver_error ( self , Vtarget , D , L , horizontal , sideA , sideB , sideA_a , sideB_a , sideA_f , sideA_k , sideB_f , sideB_k , sideA_a_ratio , sideB_a_ratio ) : a = TANK ( D = float ( D ) , L = float ( L ) , horizontal = horizontal , sideA = sideA , sideB = sideB , sideA_a = sideA_a , sideB_a = sideB_a , sideA...
Function which uses only the variables given and the TANK class itself to determine how far from the desired volume Vtarget the volume produced by the specified parameters in a new TANK instance is . Should only be used by solve_tank_for_V method .
241,133
def plate_exchanger_identifier ( self ) : s = ( 'L' + str ( round ( self . wavelength * 1000 , 2 ) ) + 'A' + str ( round ( self . amplitude * 1000 , 2 ) ) + 'B' + '-' . join ( [ str ( i ) for i in self . chevron_angles ] ) ) return s
Method to create an identifying string in format L + wavelength + A + amplitude + B + chevron angle - chevron angle . Wavelength and amplitude are specified in units of mm and rounded to two decimal places .
241,134
def linspace ( start , stop , num = 50 , endpoint = True , retstep = False , dtype = None ) : num = int ( num ) start = start * 1. stop = stop * 1. if num <= 0 : return [ ] if endpoint : if num == 1 : return [ start ] step = ( stop - start ) / float ( ( num - 1 ) ) if num == 1 : step = nan y = [ start ] for _ in range ...
Port of numpy s linspace to pure python . Does not support dtype and returns lists of floats .
241,135
def derivative ( func , x0 , dx = 1.0 , n = 1 , args = ( ) , order = 3 ) : if order < n + 1 : raise ValueError if order % 2 == 0 : raise ValueError weights = central_diff_weights ( order , n ) tot = 0.0 ho = order >> 1 for k in range ( order ) : tot += weights [ k ] * func ( x0 + ( k - ho ) * dx , * args ) return tot /...
Reimplementation of SciPy s derivative function with more cached coefficients and without using numpy . If new coefficients not cached are needed they are only calculated once and are remembered .
241,136
def polyder ( c , m = 1 , scl = 1 , axis = 0 ) : c = list ( c ) cnt = int ( m ) if cnt == 0 : return c n = len ( c ) if cnt >= n : c = c [ : 1 ] * 0 else : for i in range ( cnt ) : n = n - 1 c *= scl der = [ 0.0 for _ in range ( n ) ] for j in range ( n , 0 , - 1 ) : der [ j - 1 ] = j * c [ j ] c = der return c
not quite a copy of numpy s version because this was faster to implement .
241,137
def horner_log ( coeffs , log_coeff , x ) : tot = 0.0 for c in coeffs : tot = tot * x + c return tot + log_coeff * log ( x )
Technically possible to save one addition of the last term of coeffs is removed but benchmarks said nothing was saved
241,138
def implementation_optimize_tck ( tck ) : if IS_PYPY : return tck else : if len ( tck ) == 3 : tck [ 0 ] = np . array ( tck [ 0 ] ) tck [ 1 ] = np . array ( tck [ 1 ] ) elif len ( tck ) == 5 : tck [ 0 ] = np . array ( tck [ 0 ] ) tck [ 1 ] = np . array ( tck [ 1 ] ) tck [ 2 ] = np . array ( tck [ 2 ] ) else : raise Not...
Converts 1 - d or 2 - d splines calculated with SciPy s splrep or bisplrep to a format for fastest computation - lists in PyPy and numpy arrays otherwise . Only implemented for 3 and 5 length tck s .
241,139
def py_bisect ( f , a , b , args = ( ) , xtol = _xtol , rtol = _rtol , maxiter = _iter , ytol = None , full_output = False , disp = True ) : fa = f ( a , * args ) fb = f ( b , * args ) if fa * fb > 0.0 : raise ValueError ( "f(a) and f(b) must have different signs" ) elif fa == 0.0 : return a elif fb == 0.0 : return b d...
Port of SciPy s C bisect routine .
241,140
def is_choked_turbulent_l ( dP , P1 , Psat , FF , FL = None , FLP = None , FP = None ) : r if FLP and FP : return dP >= ( FLP / FP ) ** 2 * ( P1 - FF * Psat ) elif FL : return dP >= FL ** 2 * ( P1 - FF * Psat ) else : raise Exception ( 'Either (FLP and FP) or FL is needed' )
r Calculates if a liquid flow in IEC 60534 calculations is critical or not for use in IEC 60534 liquid valve sizing calculations . Either FL may be provided or FLP and FP depending on the calculation process .
241,141
def is_choked_turbulent_g ( x , Fgamma , xT = None , xTP = None ) : r if xT : return x >= Fgamma * xT elif xTP : return x >= Fgamma * xTP else : raise Exception ( 'Either xT or xTP is needed' )
r Calculates if a gas flow in IEC 60534 calculations is critical or not for use in IEC 60534 gas valve sizing calculations . Either xT or xTP must be provided depending on the calculation process .
241,142
def Reynolds_valve ( nu , Q , D1 , FL , Fd , C ) : r return N4 * Fd * Q / nu / ( C * FL ) ** 0.5 * ( FL ** 2 * C ** 2 / ( N2 * D1 ** 4 ) + 1 ) ** 0.25
r Calculates Reynolds number of a control valve for a liquid or gas flowing through it at a specified Q for a specified D1 FL Fd C and with kinematic viscosity nu according to IEC 60534 calculations .
241,143
def Reynolds_factor ( FL , C , d , Rev , full_trim = True ) : r if full_trim : n1 = N2 / ( min ( C / d ** 2 , 0.04 ) ) ** 2 FR_1a = 1 + ( 0.33 * FL ** 0.5 ) / n1 ** 0.25 * log10 ( Rev / 10000. ) FR_2 = 0.026 / FL * ( n1 * Rev ) ** 0.5 if Rev < 10 : FR = FR_2 else : FR = min ( FR_2 , FR_1a ) else : n2 = 1 + N32 * ( C / ...
r Calculates the Reynolds number factor FR for a valve with a Reynolds number Rev diameter d flow coefficient C liquid pressure recovery factor FL and with either full or reduced trim all according to IEC 60534 calculations .
241,144
def func_args ( func ) : try : return tuple ( inspect . signature ( func ) . parameters ) except : return tuple ( inspect . getargspec ( func ) . args )
Basic function which returns a tuple of arguments of a function or method .
241,145
def cast_scalar ( method ) : @ wraps ( method ) def new_method ( self , other ) : if np . isscalar ( other ) : other = type ( self ) ( [ other ] , self . domain ( ) ) return method ( self , other ) return new_method
Cast scalars to constant interpolating objects
241,146
def dct ( data ) : N = len ( data ) // 2 fftdata = fftpack . fft ( data , axis = 0 ) [ : N + 1 ] fftdata /= N fftdata [ 0 ] /= 2. fftdata [ - 1 ] /= 2. if np . isrealobj ( data ) : data = np . real ( fftdata ) else : data = fftdata return data
Compute DCT using FFT
241,147
def _cutoff ( self , coeffs , vscale ) : bnd = self . _threshold ( vscale ) inds = np . nonzero ( abs ( coeffs ) >= bnd ) if len ( inds [ 0 ] ) : N = inds [ 0 ] [ - 1 ] else : N = 0 return N + 1
Compute cutoff index after which the coefficients are deemed negligible .
241,148
def same_domain ( self , fun2 ) : return np . allclose ( self . domain ( ) , fun2 . domain ( ) , rtol = 1e-14 , atol = 1e-14 )
Returns True if the domains of two objects are the same .
241,149
def restrict ( self , subinterval ) : if ( subinterval [ 0 ] < self . _domain [ 0 ] ) or ( subinterval [ 1 ] > self . _domain [ 1 ] ) : raise ValueError ( "Can only restrict to subinterval" ) return self . from_function ( self , subinterval )
Return a Polyfun that matches self on subinterval .
241,150
def basis ( self , n ) : if n == 0 : return self ( np . array ( [ 1. ] ) ) vals = np . ones ( n + 1 ) vals [ 1 : : 2 ] = - 1 return self ( vals )
Chebyshev basis functions T_n .
241,151
def sum ( self ) : ak = self . coefficients ( ) ak2 = ak [ : : 2 ] n = len ( ak2 ) Tints = 2 / ( 1 - ( 2 * np . arange ( n ) ) ** 2 ) val = np . sum ( ( Tints * ak2 . T ) . T , axis = 0 ) a_ , b_ = self . domain ( ) return 0.5 * ( b_ - a_ ) * val
Evaluate the integral over the given interval using Clenshaw - Curtis quadrature .
241,152
def integrate ( self ) : coeffs = self . coefficients ( ) a , b = self . domain ( ) int_coeffs = 0.5 * ( b - a ) * poly . chebyshev . chebint ( coeffs ) antiderivative = self . from_coeff ( int_coeffs , domain = self . domain ( ) ) return antiderivative - antiderivative ( a )
Return the object representing the primitive of self over the domain . The output starts at zero on the left - hand side of the domain .
241,153
def differentiate ( self , n = 1 ) : ak = self . coefficients ( ) a_ , b_ = self . domain ( ) for _ in range ( n ) : ak = self . differentiator ( ak ) return self . from_coeff ( ( 2. / ( b_ - a_ ) ) ** n * ak , domain = self . domain ( ) )
n - th derivative default 1 .
241,154
def sample_function ( self , f , N ) : x = self . interpolation_points ( N + 1 ) return f ( x )
Sample a function on N + 1 Chebyshev points .
241,155
def interpolator ( self , x , values ) : p = Bary ( [ 0. ] ) N = len ( values ) weights = np . ones ( N ) weights [ 0 ] = .5 weights [ 1 : : 2 ] = - 1 weights [ - 1 ] *= .5 p . wi = weights p . xi = x p . set_yi ( values ) return p
Returns a polynomial with vector coefficients which interpolates the values at the Chebyshev points x
241,156
def drag_sphere ( Re , Method = None , AvailableMethods = False ) : r def list_methods ( ) : methods = [ ] for key , ( func , Re_min , Re_max ) in drag_sphere_correlations . items ( ) : if ( Re_min is None or Re > Re_min ) and ( Re_max is None or Re < Re_max ) : methods . append ( key ) return methods if AvailableMetho...
r This function handles calculation of drag coefficient on spheres . Twenty methods are available all requiring only the Reynolds number of the sphere . Most methods are valid from Re = 0 to Re = 200 000 . A correlation will be automatically selected if none is specified . The full list of correlations valid for a give...
241,157
def v_terminal ( D , rhop , rho , mu , Method = None ) : r v_lam = g * D * D * ( rhop - rho ) / ( 18 * mu ) Re_lam = Reynolds ( V = v_lam , D = D , rho = rho , mu = mu ) if Re_lam < 0.01 or Method == 'Stokes' : return v_lam Re_almost = rho * D / mu main = 4 / 3. * g * D * ( rhop - rho ) / rho V_max = 1E6 / rho / D * mu...
r Calculates terminal velocity of a falling sphere using any drag coefficient method supported by drag_sphere . The laminar solution for Re < 0 . 01 is first tried ; if the resulting terminal velocity does not put it in the laminar regime a numerical solution is used .
241,158
def integrate_drag_sphere ( D , rhop , rho , mu , t , V = 0 , Method = None , distance = False ) : r laminar_initial = Reynolds ( V = V , rho = rho , D = D , mu = mu ) < 0.01 v_laminar_end_assumed = v_terminal ( D = D , rhop = rhop , rho = rho , mu = mu , Method = Method ) laminar_end = Reynolds ( V = v_laminar_end_ass...
r Integrates the velocity and distance traveled by a particle moving at a speed which will converge to its terminal velocity .
241,159
def bend_rounded_Ito ( Di , angle , Re , rc = None , bend_diameters = None , roughness = 0.0 ) : if not rc : if bend_diameters is None : bend_diameters = 5.0 rc = Di * bend_diameters radius_ratio = rc / Di angle_rad = radians ( angle ) De2 = Re * ( Di / rc ) ** 2.0 if rc > 50.0 * Di : alpha = 1.0 else : alpha_45 = 1.0 ...
Ito method as shown in Blevins . Curved friction factor as given in Blevins with minor tweaks to be more accurate to the original methods .
241,160
def geopy_geolocator ( ) : global geolocator if geolocator is None : try : from geopy . geocoders import Nominatim except ImportError : return None geolocator = Nominatim ( user_agent = geolocator_user_agent ) return geolocator return geolocator
Lazy loader for geocoder from geopy . This currently loads the Nominatim geocode and returns an instance of it taking ~2 us .
241,161
def heating_degree_days ( T , T_base = F2K ( 65 ) , truncate = True ) : r dd = T - T_base if truncate and dd < 0.0 : dd = 0.0 return dd
r Calculates the heating degree days for a period of time .
241,162
def cooling_degree_days ( T , T_base = 283.15 , truncate = True ) : r dd = T_base - T if truncate and dd < 0.0 : dd = 0.0 return dd
r Calculates the cooling degree days for a period of time .
241,163
def get_station_year_text ( WMO , WBAN , year ) : if WMO is None : WMO = 999999 if WBAN is None : WBAN = 99999 station = str ( int ( WMO ) ) + '-' + str ( int ( WBAN ) ) gsod_year_dir = os . path . join ( data_dir , 'gsod' , str ( year ) ) path = os . path . join ( gsod_year_dir , station + '.op' ) if os . path . exist...
Basic method to download data from the GSOD database given a station identifier and year .
241,164
def _Stichlmair_flood_f ( inputs , Vl , rhog , rhol , mug , voidage , specific_area , C1 , C2 , C3 , H ) : Vg , dP_irr = float ( inputs [ 0 ] ) , float ( inputs [ 1 ] ) dp = 6.0 * ( 1.0 - voidage ) / specific_area Re = Vg * rhog * dp / mug f0 = C1 / Re + C2 / Re ** 0.5 + C3 dP_dry = 0.75 * f0 * ( 1.0 - voidage ) / void...
Internal function which calculates the errors of the two Stichlmair objective functions and their jacobian .
241,165
def Robbins ( L , G , rhol , rhog , mul , H = 1.0 , Fpd = 24.0 ) : r L = L * 737.33812 G = G * 737.33812 rhol = rhol * 0.062427961 rhog = rhog * 0.062427961 mul = mul * 1000.0 C3 = 7.4E-8 C4 = 2.7E-5 Fpd_root_term = ( .05 * Fpd ) ** 0.5 Lf = L * ( 62.4 / rhol ) * Fpd_root_term * mul ** 0.1 Gf = G * ( 0.075 / rhog ) ** ...
r Calculates pressure drop across a packed column using the Robbins equation .
241,166
def dP_packed_bed ( dp , voidage , vs , rho , mu , L = 1 , Dt = None , sphericity = None , Method = None , AvailableMethods = False ) : r def list_methods ( ) : methods = [ ] if all ( ( dp , voidage , vs , rho , mu , L ) ) : for key , values in packed_beds_correlations . items ( ) : if Dt or not values [ 1 ] : methods ...
r This function handles choosing which pressure drop in a packed bed correlation is used . Automatically select which correlation to use if none is provided . Returns None if insufficient information is provided .
241,167
def Friedel ( m , x , rhol , rhog , mul , mug , sigma , D , roughness = 0 , L = 1 ) : r v_lo = m / rhol / ( pi / 4 * D ** 2 ) Re_lo = Reynolds ( V = v_lo , rho = rhol , mu = mul , D = D ) fd_lo = friction_factor ( Re = Re_lo , eD = roughness / D ) dP_lo = fd_lo * L / D * ( 0.5 * rhol * v_lo ** 2 ) v_go = m / rhog / ( p...
r Calculates two - phase pressure drop with the Friedel correlation .
241,168
def airmass ( func , angle , H_max = 86400.0 , R_planet = 6.371229E6 , RI = 1.000276 ) : r delta0 = RI - 1.0 rho0 = func ( 0.0 ) angle_term = cos ( radians ( angle ) ) def to_int ( Z ) : rho = func ( Z ) t1 = ( 1.0 + 2.0 * delta0 * ( 1.0 - rho / rho0 ) ) t2 = ( angle_term / ( 1.0 + Z / R_planet ) ) ** 2 t3 = ( 1.0 - t1...
r Calculates mass of air per square meter in the atmosphere using a provided atmospheric model . The lowest air mass is calculated straight up ; as the angle is lowered to nearer and nearer the horizon the air mass increases and can approach 40x or more the minimum airmass .
241,169
def _get_ind_from_H ( H ) : r if H <= 0 : return 0 for ind , Hi in enumerate ( H_std ) : if Hi >= H : return ind - 1 return 7
r Method defined in the US Standard Atmosphere 1976 for determining the index of the layer a specified elevation is above . Levels are 0 11E3 20E3 32E3 47E3 51E3 71E3 84852 meters respectively .
241,170
def gauge_from_t ( t , SI = True , schedule = 'BWG' ) : r tol = 0.1 if SI : t_inch = round ( t / inch , 9 ) else : t_inch = t try : sch_integers , sch_inch , sch_SI , decreasing = wire_schedules [ schedule ] except : raise ValueError ( 'Wire gauge schedule not found' ) sch_max , sch_min = sch_inch [ 0 ] , sch_inch [ - ...
r Looks up the gauge of a given wire thickness of given schedule . Values are all non - linear and tabulated internally .
241,171
def t_from_gauge ( gauge , SI = True , schedule = 'BWG' ) : r try : sch_integers , sch_inch , sch_SI , decreasing = wire_schedules [ schedule ] except : raise ValueError ( "Wire gauge schedule not found; supported gauges are \'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', and 'SSWG'." ) try : i = sch_integers . index ( gauge ) ex...
r Looks up the thickness of a given wire gauge of given schedule . Values are all non - linear and tabulated internally .
241,172
def API520_F2 ( k , P1 , P2 ) : r r = P2 / P1 return ( k / ( k - 1 ) * r ** ( 2. / k ) * ( ( 1 - r ** ( ( k - 1. ) / k ) ) / ( 1. - r ) ) ) ** 0.5
r Calculates coefficient F2 for subcritical flow for use in API 520 subcritical flow relief valve sizing .
241,173
def API520_SH ( T1 , P1 ) : r if P1 > 20780325.0 : raise Exception ( 'For P above 20679 kPag, use the critical flow model' ) if T1 > 922.15 : raise Exception ( 'Superheat cannot be above 649 degrees Celcius' ) if T1 < 422.15 : return 1. return float ( bisplev ( T1 , P1 , API520_KSH_tck ) )
r Calculates correction due to steam superheat for steam flow for use in API 520 relief valve sizing . 2D interpolation among a table with 28 pressures and 10 temperatures is performed .
241,174
def API520_W ( Pset , Pback ) : r gauge_backpressure = ( Pback - atm ) / ( Pset - atm ) * 100.0 if gauge_backpressure < 15.0 : return 1.0 return interp ( gauge_backpressure , Kw_x , Kw_y )
r Calculates capacity correction due to backpressure on balanced spring - loaded PRVs in liquid service . For pilot operated valves this is always 1 . Applicable up to 50% of the percent gauge backpressure For use in API 520 relief valve sizing . 1D interpolation among a table with 53 backpressures is performed .
241,175
def API520_B ( Pset , Pback , overpressure = 0.1 ) : r gauge_backpressure = ( Pback - atm ) / ( Pset - atm ) * 100 if overpressure not in [ 0.1 , 0.16 , 0.21 ] : raise Exception ( 'Only overpressure of 10%, 16%, or 21% are permitted' ) if ( overpressure == 0.1 and gauge_backpressure < 30 ) or ( overpressure == 0.16 and...
r Calculates capacity correction due to backpressure on balanced spring - loaded PRVs in vapor service . For pilot operated valves this is always 1 . Applicable up to 50% of the percent gauge backpressure For use in API 520 relief valve sizing . 1D interpolation among a table with 53 backpressures is performed .
241,176
def API520_A_g ( m , T , Z , MW , k , P1 , P2 = 101325 , Kd = 0.975 , Kb = 1 , Kc = 1 ) : r P1 , P2 = P1 / 1000. , P2 / 1000. m = m * 3600. if is_critical_flow ( P1 , P2 , k ) : C = API520_C ( k ) A = m / ( C * Kd * Kb * Kc * P1 ) * ( T * Z / MW ) ** 0.5 else : F2 = API520_F2 ( k , P1 , P2 ) A = 17.9 * m / ( F2 * Kd * ...
r Calculates required relief valve area for an API 520 valve passing a gas or a vapor at either critical or sub - critical flow .
241,177
def API520_A_steam ( m , T , P1 , Kd = 0.975 , Kb = 1 , Kc = 1 ) : r KN = API520_N ( P1 ) KSH = API520_SH ( T , P1 ) P1 = P1 / 1000. m = m * 3600. A = 190.5 * m / ( P1 * Kd * Kb * Kc * KN * KSH ) return A * 0.001 ** 2
r Calculates required relief valve area for an API 520 valve passing a steam at either saturation or superheat but not partially condensed .
241,178
def getFile ( self , name , relative = None ) : if self . pathCallback is not None : return getFile ( self . _getFileDeprecated ( name , relative ) ) return getFile ( name , relative or self . pathDirectory )
Returns a file name or None
241,179
def getFontName ( self , names , default = "helvetica" ) : if type ( names ) is not ListType : if type ( names ) not in six . string_types : names = str ( names ) names = names . strip ( ) . split ( "," ) for name in names : if type ( name ) not in six . string_types : name = str ( name ) font = self . fontList . get (...
Name of a font
241,180
def pisaPreLoop ( node , context , collect = False ) : data = u"" if node . nodeType == Node . TEXT_NODE and collect : data = node . data elif node . nodeType == Node . ELEMENT_NODE : name = node . tagName . lower ( ) if name in ( "style" , "link" ) : attr = pisaGetAttributes ( context , name , node . attributes ) medi...
Collect all CSS definitions
241,181
def pisaParser ( src , context , default_css = "" , xhtml = False , encoding = None , xml_output = None ) : global CSSAttrCache CSSAttrCache = { } if xhtml : parser = html5lib . XHTMLParser ( tree = treebuilders . getTreeBuilder ( "dom" ) ) else : parser = html5lib . HTMLParser ( tree = treebuilders . getTreeBuilder ( ...
- Parse HTML and get miniDOM - Extract CSS informations add default CSS parse CSS - Handle the document DOM itself and build reportlab story - Return Context object
241,182
def doLayout ( self , width ) : self . width = width font_sizes = [ 0 ] + [ frag . get ( "fontSize" , 0 ) for frag in self ] self . fontSize = max ( font_sizes ) self . height = self . lineHeight = max ( frag * self . LINEHEIGHT for frag in font_sizes ) y = ( self . lineHeight - self . fontSize ) for frag in self : fra...
Align words in previous line .
241,183
def splitIntoLines ( self , maxWidth , maxHeight , splitted = False ) : self . lines = [ ] self . height = 0 self . maxWidth = self . width = maxWidth self . maxHeight = maxHeight boxStack = [ ] style = self . style x = 0 if not splitted : x = style [ "textIndent" ] lenText = len ( self ) pos = 0 while pos < lenText : ...
Split text into lines and calculate X positions . If we need more space in height than available we return the rest of the text
241,184
def dumpLines ( self ) : for i , line in enumerate ( self . lines ) : logger . debug ( "Line %d:" , i ) logger . debug ( line . dumpFragments ( ) )
For debugging dump all line and their content
241,185
def wrap ( self , availWidth , availHeight ) : self . avWidth = availWidth self . avHeight = availHeight logger . debug ( "*** wrap (%f, %f)" , availWidth , availHeight ) if not self . text : logger . debug ( "*** wrap (%f, %f) needed" , 0 , 0 ) return 0 , 0 width = availWidth self . splitIndex = self . text . splitInt...
Determine the rectangle this paragraph really needs .
241,186
def split ( self , availWidth , availHeight ) : logger . debug ( "*** split (%f, %f)" , availWidth , availHeight ) splitted = [ ] if self . splitIndex : text1 = self . text [ : self . splitIndex ] text2 = self . text [ self . splitIndex : ] p1 = Paragraph ( Text ( text1 ) , self . style , debug = self . debug ) p2 = Pa...
Split ourselves in two paragraphs .
241,187
def draw ( self ) : logger . debug ( "*** draw" ) if not self . text : return canvas = self . canv style = self . style canvas . saveState ( ) if self . debug : bw = 0.5 bc = Color ( 1 , 1 , 0 ) bg = Color ( 0.9 , 0.9 , 0.9 ) canvas . setStrokeColor ( bc ) canvas . setLineWidth ( bw ) canvas . setFillColor ( bg ) canva...
Render the content of the paragraph .
241,188
def showLogging ( debug = False ) : try : log_level = logging . WARN log_format = LOG_FORMAT_DEBUG if debug : log_level = logging . DEBUG logging . basicConfig ( level = log_level , format = log_format ) except : logging . basicConfig ( )
Shortcut for enabling log dump
241,189
def parseFile ( self , srcFile , closeFile = False ) : try : result = self . parse ( srcFile . read ( ) ) finally : if closeFile : srcFile . close ( ) return result
Parses CSS file - like objects using the current cssBuilder . Use for external stylesheets .
241,190
def parse ( self , src ) : self . cssBuilder . beginStylesheet ( ) try : src = cssSpecial . cleanupCSS ( src ) try : src , stylesheet = self . _parseStylesheet ( src ) except self . ParseError as err : err . setFullCSSSource ( src ) raise finally : self . cssBuilder . endStylesheet ( ) return stylesheet
Parses CSS string source using the current cssBuilder . Use for embedded stylesheets .
241,191
def parseInline ( self , src ) : self . cssBuilder . beginInline ( ) try : try : src , properties = self . _parseDeclarationGroup ( src . strip ( ) , braces = False ) except self . ParseError as err : err . setFullCSSSource ( src , inline = True ) raise result = self . cssBuilder . inline ( properties ) finally : self ...
Parses CSS inline source string using the current cssBuilder . Use to parse a tag s sytle - like attribute .
241,192
def parseAttributes ( self , attributes = None , ** kwAttributes ) : attributes = attributes if attributes is not None else { } if attributes : kwAttributes . update ( attributes ) self . cssBuilder . beginInline ( ) try : properties = [ ] try : for propertyName , src in six . iteritems ( kwAttributes ) : src , propert...
Parses CSS attribute source strings and return as an inline stylesheet . Use to parse a tag s highly CSS - based attributes like font .
241,193
def parseSingleAttr ( self , attrValue ) : results = self . parseAttributes ( temp = attrValue ) if 'temp' in results [ 1 ] : return results [ 1 ] [ 'temp' ] else : return results [ 0 ] [ 'temp' ]
Parse a single CSS attribute source string and returns the built CSS expression . Use to parse a tag s highly CSS - based attributes like font .
241,194
def _parseAtFrame ( self , src ) : src = src [ len ( '@frame ' ) : ] . lstrip ( ) box , src = self . _getIdent ( src ) src , properties = self . _parseDeclarationGroup ( src . lstrip ( ) ) result = [ self . cssBuilder . atFrame ( box , properties ) ] return src . lstrip ( ) , result
XXX Proprietary for PDF
241,195
def ErrorMsg ( ) : import traceback limit = None _type , value , tb = sys . exc_info ( ) _list = traceback . format_tb ( tb , limit ) + traceback . format_exception_only ( _type , value ) return "Traceback (innermost last):\n" + "%-20s %s" % ( " " . join ( _list [ : - 1 ] ) , _list [ - 1 ] )
Helper to get a nice traceback as string
241,196
def transform_attrs ( obj , keys , container , func , extras = None ) : cpextras = extras for reportlab , css in keys : extras = cpextras if extras is None : extras = [ ] elif not isinstance ( extras , list ) : extras = [ extras ] if css in container : extras . insert ( 0 , container [ css ] ) setattr ( obj , reportlab...
Allows to apply one function to set of keys cheching if key is in container also trasform ccs key to report lab keys .
241,197
def copy_attrs ( obj1 , obj2 , attrs ) : for attr in attrs : value = getattr ( obj2 , attr ) if hasattr ( obj2 , attr ) else None if value is None and isinstance ( obj2 , dict ) and attr in obj2 : value = obj2 [ attr ] setattr ( obj1 , attr , value )
Allows copy a list of attributes from object2 to object1 . Useful for copy ccs attributes to fragment
241,198
def set_value ( obj , attrs , value , _copy = False ) : for attr in attrs : if _copy : value = copy ( value ) setattr ( obj , attr , value )
Allows set the same value to a list of attributes
241,199
def getColor ( value , default = None ) : if isinstance ( value , Color ) : return value value = str ( value ) . strip ( ) . lower ( ) if value == "transparent" or value == "none" : return default if value in COLOR_BY_NAME : return COLOR_BY_NAME [ value ] if value . startswith ( "#" ) and len ( value ) == 4 : value = "...
Convert to color value . This returns a Color object instance from a text bit .