idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
240,100
def _get_session ( team , timeout = None ) : global _sessions # pylint:disable=C0103 session = _sessions . get ( team ) if session is None : auth = _create_auth ( team , timeout ) _sessions [ team ] = session = _create_session ( team , auth ) assert session is not None return session
Creates a session or returns an existing session .
78
10
240,101
def _check_team_login ( team ) : contents = _load_auth ( ) for auth in itervalues ( contents ) : existing_team = auth . get ( 'team' ) if team and team != existing_team : raise CommandException ( "Can't log in as team %r; log out first." % team ) elif not team and existing_team : raise CommandException ( "Can't log in ...
Disallow simultaneous public cloud and team logins .
108
10
240,102
def _check_team_exists ( team ) : if team is None : return hostname = urlparse ( get_registry_url ( team ) ) . hostname try : socket . gethostbyname ( hostname ) except IOError : try : # Do we have internet? socket . gethostbyname ( 'quiltdata.com' ) except IOError : message = "Can't find quiltdata.com. Check your inte...
Check that the team registry actually exists .
125
8
240,103
def login_with_token ( refresh_token , team = None ) : # Get an access token and a new refresh token. _check_team_id ( team ) auth = _update_auth ( team , refresh_token ) url = get_registry_url ( team ) contents = _load_auth ( ) contents [ url ] = auth _save_auth ( contents ) _clear_session ( team )
Authenticate using an existing token .
88
7
240,104
def generate ( directory , outfilename = DEFAULT_BUILDFILE ) : try : buildfilepath = generate_build_file ( directory , outfilename = outfilename ) except BuildException as builderror : raise CommandException ( str ( builderror ) ) print ( "Generated build-file %s." % ( buildfilepath ) )
Generate a build - file for quilt build from a directory of source files .
72
17
240,105
def build ( package , path = None , dry_run = False , env = 'default' , force = False , build_file = False ) : # TODO: rename 'path' param to 'target'? team , _ , _ , subpath = parse_package ( package , allow_subpath = True ) _check_team_id ( team ) logged_in_team = _find_logged_in_team ( ) if logged_in_team is not Non...
Compile a Quilt data package either from a build file or an existing package node .
370
18
240,106
def build_from_node ( package , node ) : team , owner , pkg , subpath = parse_package ( package , allow_subpath = True ) _check_team_id ( team ) store = PackageStore ( ) pkg_root = get_or_create_package ( store , team , owner , pkg , subpath ) if not subpath and not isinstance ( node , nodes . GroupNode ) : raise Comma...
Compile a Quilt data package from an existing package node .
601
13
240,107
def build_from_path ( package , path , dry_run = False , env = 'default' , outfilename = DEFAULT_BUILDFILE ) : team , owner , pkg , subpath = parse_package ( package , allow_subpath = True ) if not os . path . exists ( path ) : raise CommandException ( "%s does not exist." % path ) try : if os . path . isdir ( path ) :...
Compile a Quilt data package from a build file . Path can be a directory in which case the build file will be generated automatically .
262
28
240,108
def log ( package ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) response = session . get ( "{url}/api/log/{owner}/{pkg}/" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg ) ) table = [ ( "Hash" , "Pushed" , "Author" , "Tags" , "Versions" ) ] for entry in revers...
List all of the changes to a package on the server .
220
12
240,109
def push ( package , is_public = False , is_team = False , reupload = False , hash = None ) : team , owner , pkg , subpath = parse_package ( package , allow_subpath = True ) _check_team_id ( team ) session = _get_session ( team ) store , pkgroot = PackageStore . find_package ( team , owner , pkg , pkghash = hash ) if p...
Push a Quilt data package to the server
765
9
240,110
def version_list ( package ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) response = session . get ( "{url}/api/version/{owner}/{pkg}/" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg ) ) for version in response . json ( ) [ 'versions' ] : print ( "%s: %s" % ( ...
List the versions of a package .
117
7
240,111
def version_add ( package , version , pkghash , force = False ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) try : Version ( version ) except ValueError : url = "https://www.python.org/dev/peps/pep-0440/#examples-of-compliant-version-schemes" raise CommandException ( "Invalid version...
Add a new version for a given package hash .
220
10
240,112
def tag_list ( package ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) response = session . get ( "{url}/api/tag/{owner}/{pkg}/" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg ) ) for tag in response . json ( ) [ 'tags' ] : print ( "%s: %s" % ( tag [ 'tag' ] , ...
List the tags of a package .
117
7
240,113
def tag_add ( package , tag , pkghash ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) session . put ( "{url}/api/tag/{owner}/{pkg}/{tag}" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg , tag = tag ) , data = json . dumps ( dict ( hash = _match_hash ( package , ...
Add a new tag for a given package hash .
115
10
240,114
def install_via_requirements ( requirements_str , force = False ) : if requirements_str [ 0 ] == '@' : path = requirements_str [ 1 : ] if os . path . isfile ( path ) : yaml_data = load_yaml ( path ) if 'packages' not in yaml_data . keys ( ) : raise CommandException ( 'Error in {filename}: missing "packages" node' . for...
Download multiple Quilt data packages via quilt . xml requirements file .
195
14
240,115
def access_list ( package ) : team , owner , pkg = parse_package ( package ) session = _get_session ( team ) lookup_url = "{url}/api/access/{owner}/{pkg}/" . format ( url = get_registry_url ( team ) , owner = owner , pkg = pkg ) response = session . get ( lookup_url ) data = response . json ( ) users = data [ 'users' ]...
Print list of users who can access a package .
112
10
240,116
def delete ( package ) : team , owner , pkg = parse_package ( package ) answer = input ( "Are you sure you want to delete this package and its entire history? " "Type '%s' to confirm: " % package ) if answer != package : print ( "Not deleting." ) return 1 session = _get_session ( team ) session . delete ( "%s/api/packa...
Delete a package from the server .
117
7
240,117
def search ( query , team = None ) : if team is None : team = _find_logged_in_team ( ) if team is not None : session = _get_session ( team ) response = session . get ( "%s/api/search/" % get_registry_url ( team ) , params = dict ( q = query ) ) print ( "* Packages in team %s" % team ) packages = response . json ( ) [ '...
Search for packages
259
3
240,118
def ls ( ) : # pylint:disable=C0103 for pkg_dir in PackageStore . find_store_dirs ( ) : print ( "%s" % pkg_dir ) packages = PackageStore ( pkg_dir ) . ls_packages ( ) for package , tag , pkghash in sorted ( packages ) : print ( "{0:30} {1:20} {2}" . format ( package , tag , pkghash ) )
List all installed Quilt data packages
103
7
240,119
def inspect ( package ) : team , owner , pkg = parse_package ( package ) store , pkgroot = PackageStore . find_package ( team , owner , pkg ) if pkgroot is None : raise CommandException ( "Package {package} not found." . format ( package = package ) ) def _print_children ( children , prefix , path ) : for idx , ( name ...
Inspect package details
448
4
240,120
def load ( pkginfo , hash = None ) : node , pkgroot , info = _load ( pkginfo , hash ) for subnode_name in info . subpath : node = node [ subnode_name ] return node
functional interface to from quilt . data . USER import PKG
53
14
240,121
def c_ideal_gas ( T , k , MW ) : Rspecific = R * 1000. / MW return ( k * Rspecific * T ) ** 0.5
r Calculates speed of sound c in an ideal gas at temperature T .
37
15
240,122
def Reynolds ( V , D , rho = None , mu = None , nu = None ) : if rho and mu : nu = mu / rho elif not nu : raise Exception ( 'Either density and viscosity, or dynamic viscosity, \ is needed' ) return V * D / nu
r Calculates Reynolds number or Re for a fluid with the given properties for the specified velocity and diameter .
66
21
240,123
def Peclet_heat ( V , L , rho = None , Cp = None , k = None , alpha = None ) : 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 .
85
27
240,124
def Fourier_heat ( t , L , rho = None , Cp = None , k = None , alpha = None ) : 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 .
86
26
240,125
def Graetz_heat ( V , D , x , rho = None , Cp = None , k = None , alpha = None ) : 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 .
92
28
240,126
def Schmidt ( D , mu = None , nu = None , rho = None ) : 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 .
58
15
240,127
def Lewis ( D = None , alpha = None , Cp = None , k = None , rho = None ) : 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 .
70
15
240,128
def Confinement ( D , rhol , rhog , sigma , g = g ) : 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 .
43
41
240,129
def Morton ( rhol , rhog , mul , sigma , g = g ) : 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 .
58
24
240,130
def Prandtl ( Cp = None , k = None , mu = None , nu = None , rho = None , alpha = None ) : 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 .
94
17
240,131
def Grashof ( L , beta , T1 , T2 = 0 , rho = None , mu = None , nu = None , g = g ) : 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 .
95
22
240,132
def Froude ( V , L , g = g , squared = False ) : 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 .
40
55
240,133
def Stokes_number ( V , Dp , D , rhop , mu ) : 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 .
42
30
240,134
def Suratman ( L , rho , mu , sigma ) : return rho * sigma * L / ( mu * mu )
r Calculates Suratman number Su for a fluid with the given characteristic length density viscosity and surface tension .
30
24
240,135
def nu_mu_converter ( rho , mu = None , nu = None ) : 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 .
75
57
240,136
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 .
322
23
240,137
def isothermal_work_compression ( P1 , P2 , T , Z = 1 ) : return Z * R * T * log ( P2 / P1 )
r Calculates the work of compression or expansion of a gas going through an isothermal process .
37
19
240,138
def isentropic_T_rise_compression ( T1 , P1 , P2 , k , eta = 1 ) : 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 .
70
69
240,139
def isentropic_efficiency ( P1 , P2 , k , eta_s = None , eta_p = None ) : 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 .
197
20
240,140
def P_isothermal_critical_flow ( P , fd , D , L ) : # Correct branch of lambertw found by trial and error 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 .
98
28
240,141
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 .
86
19
240,142
def is_critical_flow ( P1 , P2 , k ) : 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 .
36
58
240,143
def one_phase_dP ( m , rho , mu , D , roughness = 0 , L = 1 , Method = None ) : 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 .
124
17
240,144
def discharge_coefficient_to_K ( D , Do , C ) : 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 .
74
28
240,145
def dn ( self , fraction , n = None ) : if fraction == 1.0 : # Avoid returning the maximum value of the search interval fraction = 1.0 - epsilon if fraction < 0 : raise ValueError ( 'Fraction must be more than 0' ) elif fraction == 0 : # pragma: no cover if self . truncated : return self . d_min return 0.0 # Solve to f...
r Computes the diameter at which a specified fraction of the distribution falls under . Utilizes a bounded solver to search for the desired diameter .
352
30
240,146
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 .
257
45
240,147
def Dis ( self ) : return [ self . di_power ( i , power = 1 ) for i in range ( self . N ) ]
Representative diameters of each bin .
30
8
240,148
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 ) : # Side A if sideA == 'conical' : sideA_SA = SA_conical_head ( D = D , a = sideA_a ) elif sideA == 'ellipsoidal' : sideA_SA = SA_ellipsoidal_head ( 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 .
515
37
240,149
def pitch_angle_solver ( angle = None , pitch = None , pitch_parallel = None , pitch_normal = None ) : 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_norm...
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 .
339
53
240,150
def A_hollow_cylinder ( Di , Do , L ) : 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 .
78
10
240,151
def A_multiple_hole_cylinder ( Do , L , holes ) : 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 .
96
53
240,152
def V_from_h ( self , h , method = 'full' ) : 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 : s...
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 .
168
60
240,153
def h_from_V ( self , V , method = 'spline' ) : 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_so...
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...
189
89
240,154
def set_table ( self , n = 100 , dx = None ) : 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 se...
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 .
145
63
240,155
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 .
215
52
240,156
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 .
81
45
240,157
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 .
184
23
240,158
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 .
112
35
240,159
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 .
128
16
240,160
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
49
23
240,161
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 .
135
50
240,162
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 .
291
10
240,163
def is_choked_turbulent_l ( dP , P1 , Psat , FF , FL = None , FLP = None , FP = None ) : 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 .
105
47
240,164
def is_choked_turbulent_g ( x , Fgamma , xT = None , xTP = None ) : 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 .
72
46
240,165
def Reynolds_valve ( nu , Q , D1 , FL , Fd , C ) : 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 .
67
48
240,166
def Reynolds_factor ( FL , C , d , Rev , full_trim = True ) : if full_trim : n1 = N2 / ( min ( C / d ** 2 , 0.04 ) ) ** 2 # C/d**2 must not exceed 0.04 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 ) ...
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 .
250
43
240,167
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 .
38
14
240,168
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
63
8
240,169
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
94
7
240,170
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 .
75
12
240,171
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 .
47
12
240,172
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 .
72
12
240,173
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 .
54
10
240,174
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 .
98
19
240,175
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 .
94
27
240,176
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 .
78
7
240,177
def sample_function ( self , f , N ) : x = self . interpolation_points ( N + 1 ) return f ( x )
Sample a function on N + 1 Chebyshev points .
30
13
240,178
def interpolator ( self , x , values ) : # hacking the barycentric interpolator by computing the weights in advance 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
96
21
240,179
def drag_sphere ( Re , Method = None , AvailableMethods = False ) : 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 AvailableMethods...
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...
297
70
240,180
def v_terminal ( D , rhop , rho , mu , Method = None ) : '''The following would be the ideal implementation. The actual function is optimized for speed, not readability def err(V): Re = rho*V*D/mu Cd = Barati_high(Re) V2 = (4/3.*g*D*(rhop-rho)/rho/Cd)**0.5 return (V-V2) return fsolve(err, 1.)''' v_lam = g * D * D * ( r...
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 .
323
57
240,181
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 is up t...
Ito method as shown in Blevins . Curved friction factor as given in Blevins with minor tweaks to be more accurate to the original methods .
353
32
240,182
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 .
78
33
240,183
def heating_degree_days ( T , T_base = F2K ( 65 ) , truncate = True ) : 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 .
50
13
240,184
def cooling_degree_days ( T , T_base = 283.15 , truncate = True ) : 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 .
47
13
240,185
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 .
450
17
240,186
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 .
433
23
240,187
def Robbins ( L , G , rhol , rhog , mul , H = 1.0 , Fpd = 24.0 ) : # Convert SI units to imperial for use in correlation L = L * 737.33812 # kg/s/m^2 to lb/hr/ft^2 G = G * 737.33812 # kg/s/m^2 to lb/hr/ft^2 rhol = rhol * 0.062427961 # kg/m^3 to lb/ft^3 rhog = rhog * 0.062427961 # kg/m^3 to lb/ft^3 mul = mul * 1000.0 # ...
r Calculates pressure drop across a packed column using the Robbins equation .
393
14
240,188
def dP_packed_bed ( dp , voidage , vs , rho , mu , L = 1 , Dt = None , sphericity = None , Method = None , AvailableMethods = False ) : 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 .
395
36
240,189
def Friedel ( m , x , rhol , rhog , mul , mug , sigma , D , roughness = 0 , L = 1 ) : # Liquid-only properties, for calculation of E, dP_lo 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 / ...
r Calculates two - phase pressure drop with the Friedel correlation .
527
14
240,190
def airmass ( func , angle , H_max = 86400.0 , R_planet = 6.371229E6 , RI = 1.000276 ) : 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 .
187
54
240,191
def _get_ind_from_H ( H ) : 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 .
44
50
240,192
def gauge_from_t ( t , SI = True , schedule = 'BWG' ) : tol = 0.1 # Handle units if SI : t_inch = round ( t / inch , 9 ) # all schedules are in inches else : t_inch = t # Get the schedule try : sch_integers , sch_inch , sch_SI , decreasing = wire_schedules [ schedule ] except : raise ValueError ( 'Wire gauge schedule n...
r Looks up the gauge of a given wire thickness of given schedule . Values are all non - linear and tabulated internally .
306
25
240,193
def t_from_gauge ( gauge , SI = True , schedule = 'BWG' ) : 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 ) exc...
r Looks up the thickness of a given wire gauge of given schedule . Values are all non - linear and tabulated internally .
147
25
240,194
def API520_F2 ( k , P1 , P2 ) : 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 .
72
22
240,195
def API520_SH ( T1 , P1 ) : if P1 > 20780325.0 : # 20679E3+atm 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. # No superheat under 15 psig return float ( bisplev ( T1 , P1 , API520_...
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 .
118
37
240,196
def API520_W ( Pset , Pback ) : gauge_backpressure = ( Pback - atm ) / ( Pset - atm ) * 100.0 # in percent 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 .
71
65
240,197
def API520_B ( Pset , Pback , overpressure = 0.1 ) : gauge_backpressure = ( Pback - atm ) / ( Pset - atm ) * 100 # in percent 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 ...
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 .
236
65
240,198
def API520_A_g ( m , T , Z , MW , k , P1 , P2 = 101325 , Kd = 0.975 , Kb = 1 , Kc = 1 ) : P1 , P2 = P1 / 1000. , P2 / 1000. # Pa to Kpa in the standard m = m * 3600. # kg/s to kg/hr 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 (...
r Calculates required relief valve area for an API 520 valve passing a gas or a vapor at either critical or sub - critical flow .
211
27
240,199
def API520_A_steam ( m , T , P1 , Kd = 0.975 , Kb = 1 , Kc = 1 ) : KN = API520_N ( P1 ) KSH = API520_SH ( T , P1 ) P1 = P1 / 1000. # Pa to kPa m = m * 3600. # kg/s to kg/hr 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 .
118
26